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?
Printable View
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?
The latest file that was created ? or the latest file that was modified ?. In essence you use the CreateFile API to get a file handle and the GetFileTime API to get the created, modified and last accessed dates/times. Take a look at the "File and Folder Time/Date changer" app in my signature. It has all the code for getting (and setting) a file's or folder's date/time data. The only other thing you need is to list and iterate through the necessary files.
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.Quote:
Originally Posted by peet1909
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