count subfolders

pandemar

New Member
Joined
Oct 29, 2009
Messages
5
Hi,
I have code to count files in folders...
I need help writing vba to just count the subfolders in a folder.
(needs to include all nested subfolders)

thanks,

peter
<!-- / message -->
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
Try this. The code can go in a standard module or a sheet module. Call the function as shown in the test routine.

Code:
Public Sub Count_Subfolders_Test()
    
    Dim oFso As Object
    
    Set oFso = CreateObject("Scripting.FileSystemObject")
    MsgBox Count_Subfolders(oFso, "F:\temp")
    
    Set oFso = Nothing

End Sub

Private Function Count_Subfolders(oFso As Object, folderPath As String) As Long
    
    Dim Folder As Object, Subfolder As Object
        
    Set Folder = oFso.GetFolder(folderPath)
        
    Count_Subfolders = 0
    For Each Subfolder In Folder.subfolder
        Count_Subfolders = Count_Subfolders + 1 + Count_Subfolders(oFso, Subfolder.Path)
    Next
    
End Function
 
Upvote 0
Hi,
Thanks for the quick reply.
I replaced the temp path with a valid path (mapped drive/folder),
but the following line of code err's.

For Each Subfolder In Folder.Subfolder
object does't support this property or method.

Is there something I'm forgetting or doing wrong???

peter
 
Upvote 0
No, a bug must have got in when I pasted the code. The fix is:

For Each Subfolder In Folder.subfolders
 
Upvote 0
thanks again ( I should have spotted it, getting late, getting tired)

Works fine...

Is there any way to incorporate the totaling of files and file size so that I don't have to iterate 3 times???

peter
 
Upvote 0

Forum statistics

Threads
1,223,673
Messages
6,173,741
Members
452,533
Latest member
Alex19k

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top