Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Iterate through ALL subfolders 1

Status
Not open for further replies.

shavon

Programmer
Jun 18, 2001
102
CA
Hello:

I am using the following code to iterate through subfolders.The problem is that the depth of folders may change and this code only processes to the first level. How do i change it to process the folders regardless of the depth of folders? Thank you.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If txtFileName.Text = "" Then
txtFileName.SetFocus
Exit Sub
End If
Dim fs, f, f1, s, sf
Dim r As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(Dir1.Path)
Set sf = f.SubFolders
For Each f1 In sf
s = f1.Path & "\00000001.TIF"
s = s & vbCrLf & f1.Path & "\00000002.TIF"
AppendToFile r, s
s = ""
Next
MsgBox "Done..."
 
One word: recursion

Here's a little code to get you going:

Code:
Private Sub ListFolders(ByVal Path As String)
    Dim fs As New Scripting.FileSystemObject
    Dim f As Folder
    Dim sf, s
    Dim f1 As Folder
    
    Set fld = fs.GetFolder(Path)
    
    Set sf = fld.SubFolders
    
    For Each f1 In sf
        If f1.SubFolders.Count > 0 Then
            ListFolders (f1.Path) '<--Here's the recursion part
        End If
        
        s = f1.Path & "\00000001.TIF"
        s = s & vbCrLf & f1.Path & "\00000002.TIF"
        AppendToFile r, s
        s = ""
    Next
End Sub

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson
 
As a general observation, I wouldn't dim fs, f, f1, s, and sf all as variant, since that uses unnecessary space and it's kind of hard to keep track of what the variables are being used for.

That said, since the subfolders property returns a collection of folder objects, in your example, sf is a collection of folder objects. Your f1 variable therefore has a subfolders collection. You can use that to drill down recursively until you don't find any more folders.

HTH

Bob
 
The odd Dimming is probably because the sample code is straight out of VBHelp!

________________________________________________________________
If you want to get the best response to a question, please check out FAQ222-2244 first

'If we're supposed to work in Hex, why have we only got A fingers?'

for steam enthusiasts
 
Yeah, thanks Jeb, that's exactly what I mean, put more concisely and with an excellent example. :)

Bob
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top