As per my comments, this function should do the trick:
Public Function MostRecentFile(ByVal searchDirectory As String, ByVal wildCard As String) As String
'''Returns the most recent file in searchDirectory, which matches wildCard criteria
Dim strFile As String 'holds the name of the file we're currently looking at
Dim mostRecent As Date 'holds the date of creation for the most recent file
Dim currDate As Date 'date of creation for the current file
Dim mostRecentPath As String 'path of file with most recent date
strFile = Dir(searchDirectory & wildCard) 'look for file in directory which matches wildcard
Do While Len(strFile) > 0 'loop until Dir returns empty quotes (no files)
currDate = FileDateTime(searchDirectory & strFile)
If currDate > mostRecent Then 'check whether current file is more recent than previous files
mostRecent = currDate 'if so, update most recent date and file
mostRecentPath = searchDirectory & strFile
End If
strFile = Dir 'move to next file in directory
Loop
If mostRecent = 0 Then 'check whether any files were returned
MostRecentFile = "No files match '" & searchDirectory & wildCard & "'"
Else
MostRecentFile = mostRecentPath
End If
End Function
It takes input strings searchDirectory
and wildCard
, the first specifies which folder to look in, the second specifies the type of file to search for.
e.g.
MostRecentFile("C:/Users/[USERNAME]/Downloads/", "*.xls")
Returns the path to the most recent file from the ".xlsm",".xls",".xlsx"
(excel files) in your downloads folder as a String
I've added code comments so hopefully you can learn what each step is doing