Using VBScript to find most recent file date in a single folder

For working with files on VBScript it is recommended you use the FileSystemObject.

The FileSystemObject has the following feature's that help you solve your problem:

  • FileSystemObject.GetFolder - Returns a Folder object corresponding to the folder in a specified path.
  • Folder.Files - Returns a Files collection consisting of all File objects contained in the specified folder.
  • File.DateLastModified - Returns the date and time that the specified file or folder was last modified.

To demonstrate, I have supplied an implementation of GetRecentFile (and GetRecentFolder) which scans the supplied input path and determines the most recent file by finding the file that has the greatest DateLastModified property.

Option Explicit  

Function GetRecentFile(path)
  Dim fso, file
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set GetRecentFile = Nothing
  For Each file in fso.GetFolder(path).Files
    If GetRecentFile is Nothing Then
      Set GetRecentFile = file
    ElseIf file.DateLastModified > GetRecentFile.DateLastModified Then
      Set GetRecentFile = file
    End If
  Next
End Function

Function GetRecentFolder(path)
  Dim fso, folder
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set GetRecentFolder = Nothing
  For Each folder in fso.GetFolder(path).SubFolders
    If GetRecentFolder is Nothing Then
      Set GetRecentFolder = folder
    ElseIf folder.DateLastModified > GetRecentFolder.DateLastModified Then
      Set GetRecentFolder = folder
    End If
  Next
End Function

Dim recentFile
Set recentFile = GetRecentFolder("C:\Temp")
If recentFile is Nothing Then
  WScript.Echo "No recent files found"
Else
  WScript.Echo "Recent file is " & recentFile.Name & " " & recentFile.DateLastModified
End If

References:

  • https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filesystemobject-object
  • https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/getfolder-method
  • https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/files-property
  • https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/datelastmodified-property