Loop Through All Subfolders Using VBA
Solution 1
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
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
Solution 2
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
Loop
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...)
Jake
Updated on July 09, 2022Comments
-
Jake almost 2 years
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".
-
Jake about 10 yearsThank you, I figured it was something simple!
-
Rich about 10 yearsNo problem, all programmers keep a copy of this subfolder iterations at one point or another, it was mostly copy and paste. Don't forget to mark an answer my friend.
-
Cor_Blimey about 10 yearsnon-recursive method added below for completeness ;)
-
Rich about 10 years+1 This is seriously badass. I need to read more on collections.
-
Rich about 10 yearsI'm curious now. If there are 3 subfolders in the
.Subfolders
object, and it performs thequeue.Add oSubfolder
three times. Won't it bypass the other 2 during the next loop call andSet oFolder = queue(1)
is activated? -
Cor_Blimey about 10 years@Rich it will, but the other 2 have been stored in the collection which we then process in the next 2 loops (don't forget
queue.Remove 1
removes the first folder, so the second folder is now the first member of the collection and so is retrieved on the next call to queue(1). A stack approach would go the opposite way and always operate on the last folder added (replace queue(1) with queue(queue.Count) and queue.Remove 1 with queue.Remove queue.Count). -
Rich about 10 yearsMakes sense. Thanks dude. I'll definitely be using this feature more often.
-
Cor_Blimey about 10 yearsCollections are super useful in VBA as they are basically our only "list" type of object (keyed dictionaries can be used from Scripting.Runtime as well). You can use them easily add results as you are processing something, then worry about getting into an array at the end (saves on array copying overhead that using Redim preserve would have each loop). You use them to find uniques, to map values, to do quick lookups on large amounts of data, and so many other things.
-
Rich about 10 yearsYeah, and ASPX has the entire global Session() collection built into it, which is pretty epic, and I've used dictionaries a-lot for vbs, not as much vba.
-
lapis about 9 yearsI'd like to point out that if the order of processing is important for you, this method will not give the same order as the recursive method. Here the folders processing order will be like this:
Root
,Root\Sub1
,Root\Sub2
,Root\Sub1\Sub1.1
,Root\Sub1\Sub1.2
,Root\Sub2\Sub2.1
,Root\Sub2\Sub2.2
... That is, folders are processed level by level. -
Cor_Blimey about 9 years@Lapis good point. The same order can be obtained in the non-recursive way by using a stack instead of a queue (so instead of
x = queue(1): queue.remove 1
it would be something likex = queue(queue.count): queue.remove(queue.count)
-
robotik almost 8 years@lapis even better, that's the behaviour i was looking for.
-
mojo3340 over 7 yearsHave you forgotten to define something? not working for me :(
-
jellz77 over 6 yearsthis is fantastic +1
-
Mistella over 5 years@Rich You might want to consider wrapping the sample use/calling-code within a working sub. Newer coders seem to be getting confused on how to deal with it....
-
hypers over 5 yearsI guess you can't get away with just having SubFolder as variant. It needs to be Dim SubFolder as Object
-
johny why almost 3 yearsAs written, files in the deepest sub-folder will be processed first. The order of the two loops can be reversed, so that files in the top folder will be processed first.
For Each File...
first, followed byFor Each SubFolder...
-
johny why almost 3 yearsPersonally, i wouldn't ask the calling fx to create the FSO or get the folder object. That should be left to the DoFolder proc. The caller should only have to pass the target directory as a string.
-
johny why almost 3 yearsi would call DoFolder something more meaningful, like "Get_Files". DoFolder doesn't tell us what we're "doing" to the folder.