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

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.

TAPS_MikeDion

Well-known Member
Joined
Aug 14, 2009
Messages
549
Office Version
  1. 2011
Platform
  1. MacOS
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:

wickitom

New Member
Joined
May 21, 2010
Messages
16
Thanks for the response, but is there a way of doing this without turning
on Microsoft scripting runtime

Tom :)
 

wickitom

New Member
Joined
May 21, 2010
Messages
16
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

:)
 

Forum statistics

Threads
1,136,341
Messages
5,675,207
Members
419,553
Latest member
hanahass

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
Top