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
[efb_likebox fanpage_url="https://www.facebook.com/vbamarket/" box_width="840" box_height=340"" responsive="1" show_faces="1" show_stream="1" hide_cover="1" small_header="0" hide_cta="0" locale="en_US"]