VB6 recursion

pancholefty used Ask the Experts™
Can someone explain why this code works correctly when the starting folder is relatively shallow but it gets stuck in the loop listing the files after it reaches a certain point?

Unfortunately I can't define "certain point". If there are a lot of folders and/or files under the starting folder (szFolder), it will get stuck in the loop and output the same files in the same folder forever.

Unfortunately I can't define "a lot" either. The folder depth where the infinite loop starts seems to be in the 3-8 range but I'm guessing that the file count is involved.

-- If I remove the loop that lists the files, it will succeed
-- Removing the Debug.Print statement has no effect
-- Adding an error handler has no effect because no error is raised.
-- Compiling to exe has no effect
-- The dev machine is Win7 x64
-- Running the exe on an XP x32 machine produces the same results

I'm using On Error Resume Next for testing so it will ignore "access denied" errors, which I don't care about at this point.

To watch it fail, call the proc with szFolder="C:\". To see it succeed, call it with a folder that doesn't have many child folders & files.

I'd like to understand what is causing the infinite loop and how to handle it.

Public Sub ListFiles(szFolder As String)

    Dim fso         As FileSystemObject
    Dim fldr        As Folder
    Dim fldrSub     As Folder
    Dim fil         As File
    Set fso = New FileSystemObject
    Set fldr = fso.GetFolder(szFolder)
    On Error Resume Next
    For Each fldrSub In fldr.SubFolders
        For Each fil In fldrSub.Files

            With fil
                Debug.Print .Path, .DateCreated
            End With
            ListFiles fldrSub.Path
    Set fil = Nothing
    Set fldr = Nothing
    Set fldrSub = Nothing
    Set fso = Nothing
End Sub

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012

Tru removing the 'On Error Resume Next' line, in case it is covering up a problem.


Removing Resume Next result's in a flood of access/permission denied errors, especially starting at "C:\"

Adding a handler that ignores those type of errors followed by Resume Next will still result in the infinite loop because no error is raised.

The question is why is it not breaking out of the inner loop at a "certain point"

Try it.
Because you've got your files and folders cross-wired.  Try this:

For each fil in fldr.files
    debug.print fil.path, fil.datecreated

For Each fldrSub In fldr.SubFolders
     ListFiles fldrSub.Path      


Good job. Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial