Public Sub OpenLatestFile()
' Run this procedure to invoke the latest
' file in its default application.
Dim vntLatestFile As Variant
Dim strLatestPath As String
Dim dtmLatestDate As Date
On Error GoTo ErrHandler
vntLatestFile = GetLatestFile("H:\Everyone\SOFTCON PCS", "EGBCIS13", True)
If Not IsEmpty(vntLatestFile) Then
dtmLatestDate = vntLatestFile(0)
strLatestPath = vntLatestFile(1)
Call CreateObject("Shell.Application").ShellExecute(strLatestPath)
Else
MsgBox "No matching files were found.", vbExclamation
End If
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
End Sub
Private Function GetLatestFile(ByVal strFolderPath As String, _
Optional ByVal strFilenamePattern As String = vbNullString, _
Optional ByVal blnIncludeSubfolders As Boolean = False) As Variant
' Finds the most recent file in the specified folder, based on date created.
' Can optionally specify a filename pattern, which can use wildcards (such as ?*#).
' Can optionally search subfolders recursively.
' Returns variant array containing date and path of file.
' Returns Empty if no matches are found.
Dim vntSubfolderResult As Variant
Dim strLatestPath As String
Dim dtmLatestDate As Date
Dim objSubfolder As Object
Dim objFileSys As Object
Dim objFolder As Object
Dim objFile As Object
' On Error GoTo ErrHandler
Set objFileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFileSys.GetFolder(strFolderPath)
dtmLatestDate = CDate(0)
For Each objFile In objFolder.Files
If UCase(objFile.Name) Like Chr(42) & UCase(strFilenamePattern) & Chr(42) Then
If objFile.DateCreated > dtmLatestDate Then
dtmLatestDate = objFile.DateCreated
strLatestPath = objFile.Path
End If
End If
Next objFile
If blnIncludeSubfolders Then
For Each objSubfolder In objFolder.SubFolders
vntSubfolderResult = GetLatestFile(objSubfolder.Path, strFilenamePattern, True)
If Not IsEmpty(vntSubfolderResult) Then
If vntSubfolderResult(0) > dtmLatestDate Then
dtmLatestDate = vntSubfolderResult(0)
strLatestPath = vntSubfolderResult(1)
End If
End If
Next objSubfolder
End If
If strLatestPath <> vbNullString Then
GetLatestFile = Array(dtmLatestDate, strLatestPath)
Else
GetLatestFile = Empty
End If
ExitProc:
Set objSubfolder = Nothing
Set objFileSys = Nothing
Set objFolder = Nothing
Set objFile = Nothing
Exit Function
ErrHandler:
GetLatestFile = Empty
Resume ExitProc
End Function