Here's one way:
VB Code:
Public Function GetOldestFileFromDir( _
ByVal filePathAndPattern As String, _
Optional ByVal attributes As VbFileAttribute = vbNormal) As String
Dim strFile As String
Dim strOldest As String
Dim strPath As String
' Get the path being checked
strPath = Left(filePathAndPattern, InStrRev(filePathAndPattern, "\"))
' Get the first file in the specified location
strFile = Dir(filePathAndPattern, attributes)
' Loop while there are files
Do While Len(strFile) > 0
' if there isn't an "oldest file" use this one
If Len(strOldest) = 0 Then
strOldest = strFile
' Otherwise, compare the date of this file to
' the current "oldest" file and if this file is
' older, make "it" the "oldest" file
ElseIf FileDateTime(strPath & strFile) < FileDateTime(strPath & strOldest) Then
strOldest = strFile
End If
' Get the next file
strFile = Dir
Loop
' Return the "oldest" file
GetOldestFileFromDir = strOldest
End Function
Example Usage:
VB Code:
Private Sub Command1_Click()
Debug.Print GetOldestFileFromDir("C:\Test\*.*")
End Sub
Regards,
- Aaron.