Dim FilDate As Variant
Dim NewestFile as String
Dim FSO As New Scripting.FileSystemObject
Dim Fil As Scripting.File
' substitute C:\Temp for your folder of choice
For Each Fil In FSO.GetFolder("C:\Temp".Files
If DateDiff("s", Fil.DateLastModified, FilDate) < 0 Then
NewestFile= Fil.Name
End If
FilDate = Fil.DateLastModified
Next
After this code runs, the variable NewestFile will hold the file name + extension of the file last modified in the folder.
You must select Project/References from the VB menu, and check the reference to "Microsoft Scripting Runtime" for this to work!
I filtered out the file extension to make sure to only look at text files and this did it for me, however, I am curious about why going through all files it didn't get me the latest modified. Any insight?
function:
Function GetLatestFile(Folder As String) As String
Dim FilDate As Variant
Dim FSO As New Scripting.FileSystemObject
Dim Fil As Scripting.File
For Each Fil In FSO.GetFolder(Folder).Files
If GetExtension(Fil.Name) = "txt" Then
If DateDiff("s", Fil.DateLastModified, FilDate) < 0 Then
GetLatestFile = Fil.Name
End If
FilDate = Fil.DateLastModified
End If
Next
Hmmm. I don't know. I tested it here on my PC, and the code I gave you worked fine for me. I ran it once, and it found the newest file. I then created a file in the directory and ran it again and it found the file that I just created. I don't know why adding the .txt filter made it work for you.
I see a couple of potential problems with the function as shown. For the first file that is checked, FilDate has not been initialized - that may or may not be a problem, but I wouldn't want to risk it.
Secondly, FilDate is being reset for each iteration in the loop, not just being reset for the latest file. Therefore, the function will return the latest only between the last two files in the directory. I would suggest that you try following
Dim FilDate As Variant
Dim NewestFile As String
Dim FSO As New Scripting.FileSystemObject
Dim Fil As Scripting.File
FilDate = ""
For Each Fil In FSO.GetFolder("<Dir Name>".Files
If (FilDate = "" Then
NewestFile = Fil.Name
FilDate = Fil.DateLastModified
Else
If DateDiff("s", Fil.DateLastModified, FilDate) < 0 Then
NewestFile = Fil.Name
FilDate = Fil.DateLastModified
End If
End If
Next
GetLatestFile = NewestFile Good Luck
-------------- As a circle of light increases so does the circumference of darkness around it. - Albert Einstein
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.