VBA Get Most Recent File Based on Timestamp

VBA to find the most recent file in a folder based on when the file was last updated.

 

VBA Get Most Recent File Based on Timestamp

Dim FileSpec, Directory, FileName, MostRecentFile, MostRecentDate, FileDateTime
FileSpec = "*.*"
Directory = "Z:\Downloads"
FileName = Dir(Directory & FileSpec)

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 NewestFile & " is the most recent file in " & Directory