I found the following in my library of utility procs. It will return the
fully qualified name of the most recently used file in the folder specified
by DirPath and having an extension equal to Extension. Extension may be
either a simple string (e.g., "xls" for Excel 97/2003 workbooks) or it may
be an array of one or more extensions (e.g,. Array("xls","xlsm","xlsx") for
2007 and earlier workbooks). It will return vbNullString if no files
matching Extension are found in the DirPath folder or if there are no files
in DirPath.
Function MostRecentFileName(DirPath As String, Extension As Variant) As
String
Dim SaveDir As String
Dim FileName As String
Dim MostRecent As Double
Dim MostRecentFile As String
Dim CurrFileDate As Double
Dim Ext As String
Dim CurrFileExt As String
Dim N As Long
Dim Pos As Long
FileName = "C:\Book1.xlsm"
Pos = InStrRev(FileName, ".")
CurrFileExt = Mid(FileName, Pos + 1)
SaveDir = CurDir
On Error Resume Next
ChDrive DirPath
If Err.Number <> 0 Then
Debug.Print "Invalid Path: " & DirPath
Exit Function
End If
ChDir DirPath
If Err.Number <> 0 Then
Debug.Print "Invalid Path: " & DirPath
Exit Function
End If
FileName = Dir(DirPath & "\*.*")
Do Until FileName = vbNullString
FileName = DirPath & "\" & FileName
CurrFileDate = FileDateTime(FileName)
If CurrFileDate > MostRecent Then
Pos = InStrRev(FileName, ".")
If Pos > 0 Then
CurrFileExt = Mid(FileName, Pos + 1)
If IsArray(Extension) = True Then
For N = LBound(Extension) To UBound(Extension)
Ext = Extension(N)
If StrComp(Ext, CurrFileExt, vbTextCompare) = 0 Then
MostRecent = CurrFileDate
MostRecentFile = FileName
Exit For
End If
Next N
Else
If (StrComp(Extension, "*", vbBinaryCompare) = 0) Or _
(StrComp(Extension, vbNullString, vbBinaryCompare) =
0) Then
MostRecent = CurrFileDate
MostRecentFile = FileName
Else
If StrComp(CurrFileExt, Extension, vbTextCompare) =
0 Then
MostRecent = CurrFileDate
MostRecentFile = FileName
End If
End If
End If
End If
End If
FileName = Dir()
Loop
ChDrive SaveDir
ChDir SaveDir
MostRecentFileName = MostRecentFile
End Function
You can then call this function with code like
Sub AAA()
Dim FileName As String
Dim ModDate As Date
Dim FilePath As String
Dim Ext As Variant
FilePath = ""
Ext = "xls" ' <<< SIMPLE STRING EXTENSION
' OR
Ext = Array("xls", "xlsm", "xlsx") '<< ARRAY OF EXTENSIONS
FileName = MostRecentFileName(DirPath:=FilePath, Extension:=Ext)
If FileName = vbNullString Then
Debug.Print "No file found"
Else
ModDate = FileDateTime(FileName)
Debug.Print "File: " & FileName, "Modified: " & ModDate
End If
End Sub
--
Cordially,
Chip Pearson
Microsoft MVP - Excel, 10 Years
Pearson Software Consulting
www.cpearson.com
(email on the web site)