Loop Through All Subfolders Using VBA


I'm looking for a VBA script that will loop through all subfolders of a specified folder. When I say all subfolders, I mean each folder inside the specified folder, and each folder inside of that, and each folder inside of that...in theory there could be infinite nested subfolders, but in actuality it will probably not go above 3 or 4. I'm using the VBA Scripting Runtime objects, so that once I loop into the folder I can check properties of some files (but I know how to do that part).

Thank you for your help!

This question is different from the listed "similar" questions in the previous questions contained known directories, whereas the need here was to find known and unknown directories. Also needed multiple layers of subdirectories. You guys really should just read the question before you fire off "duplicate".

This question is tagged with vba filesystemobject

~ Asked on 2014-03-25 20:16:12

The Best Answer is


Just a simple folder drill down.

sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "C:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
End Sub

~ Answered on 2014-03-25 20:21:15


And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

~ Answered on 2014-03-25 20:58:13

Most Viewed Questions: