Thursday, 13 April 2017

How to find recent excel file in a folder.

Sub Recent_File()

Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date

'specify the directory
Directory = "C:\Users\" & Environ("username") & "\Downloads\"
FileName = Dir(Directory & "*.xlsx", 0)
If FileName <> "" Then
    MostRecentFile = FileName
    MostRecentDate = FileDateTime(Directory & FileName)
    Do While FileName <> ""
        If FileDateTime(Directory & FileName) > MostRecentDate Then
             MostRecentFile = FileName
             MostRecentDate = FileDateTime(Directory & FileName)
         End If
         FileName = Dir
    Loop
End If
NewestFile = MostRecentFile
MsgBox "Recent File is " & NewestFile
End Sub

No comments:

Post a Comment