Skip to main content

Get most recent file from a directory

I found this snippet by doing a google search and adapting it to IDEA.  It will return the name of the most recently saved file from a directory.  With a bit of change it should also find the most recently modified file from a directory.

Snippet


Function GetMostRecentFile(myDir As String)

Dim FileSys As Object
Dim objFile As Object
Dim myFolder
Dim strFilename As String
Dim dteFile As Date

'set up filesys objects
Set FileSys = CreateObject("Scripting.FileSystemObject")
Set myFolder = FileSys.GetFolder(myDir)

'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If objFile.DateLastModified > dteFile Then
dteFile = objFile.DateLastModified
strFilename = objFile.Name
End If
Next objFile

GetMostRecentFile = strFilename

Set FileSys = Nothing
Set myFolder = Nothing
End Function