Home » excel » excel – VBA : Looping through Filesystem and finding the newest file

excel – VBA : Looping through Filesystem and finding the newest file

Posted by: admin May 14, 2020 Leave a comment

Questions:

In my program, i want to browse through a complex file structure, and display the newest file in it.

The file structure has several folders and subfolders, most of the time empty. So this macro would help to reveal where the latest information is.

Sub newestFile()
Dim FileSystem as object
Dim MostRecentFile as string
Dim MostRecentDate as Date
Dim FileSpec as String
Dim filename as string

'This is where i specify what type of files i would be looking for
FileSpec ="*.*"

'This is where i specify where the master directory is, so that i may look down into it
Directory ="c:\Directory1\"
filename = Dir(Directory & FileSpec)

set Filesystem = CreateObject("Scripting.FileSystemObject")
Do Folder FileSystem.getFolder(Directory)

set ws = Sheets("Events")
ws.cells(2,7).value = MostRecentFile
ws.cells(2,8).value = MostRecentDate
end sub

private Function DoFolder(Directory)

For each subfolder in Directory.SubFolders
   DoFolder subfolder

Dim file

For each File in Directory.files
    'actions go here
    If File <> "" Then
    MostRecentFile = File
    MostRecentDate = FileDateTime(Directory)
        If FileDateTime(File) > MostRecentDate Then
            MostRecentFile = File
            MostRecentDate = FileDateTime(File)
        End if
    End If
next

next

End Function

on this code i always loose the variables (MostRecentFile and MostRecentDate) when the code goes to another subfolder.

I expected on having the name of the newest file (of the whole structure), and the date.

How to&Answers:

You need to declare the variables at module level

Private MostRecentFile as string
Private MostRecentDate as Date

Sub newestFile()
....
End Sub

Answer:

As was said, scope is certainly a concern. Here’s a loop within the subroutine:

Sub newestFile()
    Dim FileSystem As Object  ' Needed to get file properties
    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    Dim MostRecentDate As Date
    Dim MostRecentFile As String
    Directory = "c:\Directory1\"
    FileSpec = "*.txt"                  '<-- can be "*.xls*" or whatever criteria needed
    MyFile = ""
'Loop through text files in Directory finding the most current file
    MyFile = Dir(Directory & FileSpec)  'Get first file name in directory
    Do While MyFile <> ""
        If MostRecentDate < FileSystem.GetFile(Directory & MyFile).DateLastModified Then
            MostRecentDate = FileSystem.GetFile(Directory & MyFile).DateLastModified
            MostRecentFile = MyFile
        End If
        MyFile = Dir                    'Get next file matching criteria
    Loop
    set ws = Sheets("Events")
    ws.cells(2,7).value = MostRecentFile
    ws.cells(2,8).value = MostRecentDate
End Sub