How to traverse subdirectories

B

Ben

Hi all,

I need to go to a particular directory then from there I would like to
traverse all the subdirectories beneath it. can you show me how?

I would also like to use a debug.print statement print out the paths.
Thanks for share your thoughts.

Ben
 
C

Chip Pearson

You can use the following code. Sub AAAA is the starting point where you
specify the starting folder. The ListSubFolders procedure recursively lists
all the subfolders (and subfolders of subfolders etc).

Sub AAAA()
Dim FSO As Scripting.FileSystemObject
Dim StartFolderName As String
Dim StartFolder As Scripting.Folder

StartFolderName = "C:\FrontPage Webs" '<<<<<<<<< CHANGE
Set FSO = New Scripting.FileSystemObject
Set StartFolder = FSO.GetFolder(StartFolderName)
Debug.Print "Start: " & StartFolder.Path
ListSubFolders StartFolder
End Sub

Sub ListSubFolders(OfFolder As Scripting.Folder)
Dim SubFolder As Scripting.Folder
For Each SubFolder In OfFolder.SubFolders
Debug.Print SubFolder.Path
If SubFolder.SubFolders.Count > 0 Then
ListSubFolders SubFolder
End If
Next SubFolder
End Sub

See also http://www.cpearson.com/Excel/FolderTree.aspx for example code for
many ways to list subfolders and/or files.


--
Cordially,
Chip Pearson
Microsoft Most Valuable Professional
Excel Product Group
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top