Macro -> count number of folders

wickitom

New Member
Joined
May 21, 2010
Messages
16
Anyone know what are the commands for a macro to count the number of sub-folders in a folder and return the number in a variable
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
To make this work, you first need to set the VBA reference.
In the VBA editor go to "Tools", then "References."
Now scroll down to "Microsoft Scripting Runtime" and check the box, if it isn't already checked.

Then, put the following code into a module:

Code:
Sub FindSubFolders()
    
    On Error GoTo ErrorHandler
    
    Dim fso As New FileSystemObject
    Dim flds As Folders
    Dim Response
    Dim sFolders
    
    Set flds = fso.GetFolder("C:\").SubFolders
    
    For Each f In flds
        sFolders = f.SubFolders.Count
        Response = MsgBox(f.Path & " - Subfolders: " _
        & sFolders, vbOKCancel, "Find Sub Folders")
        If Response = vbCancel Then Exit For
    Next
    
    Exit Sub
    
ErrorHandler:
    If Err.Number <> 0 Then
        Msg = "Error # " & Str(Err.Number) & " was generated by " _
            & Err.Source & vbLf & Err.Description
    End If
    
    On Error GoTo 0
 
End Sub
 
Last edited:
Upvote 0
Thanks for the response, but is there a way of doing this without turning
on Microsoft scripting runtime

Tom :)
 
Upvote 0
Thanks all, found something else

directoryname = "C:\chemkin36\alkanes\Output\rop\" ' change folder name as needed
Set fso = CreateObject("Scripting.FileSystemObject")
Set mainfolder = fso.GetFolder(directoryname)
m = mainfolder.subfolders.Count

:)
 
Upvote 0

Forum statistics

Threads
1,213,546
Messages
6,114,256
Members
448,558
Latest member
aivin

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