
Originally Posted by
peet1909
I am trying to get the filename of the latest file created in a specified folder.
Can anyone help me on how to do this?
schoolbusdriver made a good point on which date do you want to use? I just slapped this together but it seems to work. I chose DateLastModified. There is also DateLastAccessed and DateCreated.
Make a reference to Microsoft Scripting Runtime
Code:
Private Sub Command1_Click()
Dim strPrevFileDate As String
Dim strCurrFileDate As String
Dim strFileName As String
Dim fso As Object
Dim f As Folder
Dim f1 As File
Dim fj As Variant
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("C:\TestIt")
Set fj = f.Files
For Each f1 In fj
strCurrFileDate = Format(f1.DateLastModified, "YYYYMMDDHHMMSS")
If strCurrFileDate > strPrevFileDate Then
strPrevFileDate = strCurrFileDate
strFileName = f1.Name
End If
Next
Debug.Print strFileName
End Sub