Search code examples
vbasearchrecursionvb6filesystemobject

Terminate Recursive Directory Search using good ol' FSO


Cross posted here: http://www.vbforums.com/showthread.php?721189-Terminate-Recursive-Directory-Search-using-good-ol-FSO&p=4411543#post4411543

We have a recurring problem of folders getting moved around at my office, and I want a simple method of tracking them down. I have the following function which performs as expected except that I can't figure out how to get it to terminate once the folder is found. It's modeled after a recursive directory search, which finds ALL instances. The problem is I want to find ONE instance, and terminate.

Is it possible to get this thing to stop calling itself without putting in a class module and hooking into events and a state monitor? If so, how can I accomplish that?

Function FindFolder(CurrentDirectory As Scripting.Folder, FolderName As String) As Scripting.Folder

On Error GoTo errHandler

Dim fold As Scripting.Folder

If CurrentDirectory.SubFolders.Count > 0 Then
For Each fold In CurrentDirectory.SubFolders
    Debug.Print fold.Path
    If fold.Name = FolderName Then
        Set FindFolder = fold: Exit Function
    Else
        Set FindFolder = FindFolder(fold, FolderName)
    End If
Next fold
End If


Exit Function

errHandler:

If Err.Number = 70 Then Resume Next 'Dont have permission to check this directory

End Function

Here is a sample usage

Sub FindEm()

Dim FSO As Scripting.FileSystemObject
Set FSO = New Scripting.FileSystemObject

Dim startFold As Scripting.Folder
Set startFold = FSO.GetFolder("C:\")

Dim searchFold As Scripting.Folder
Set searchFold = FindFolder(startFold, "SomeExactFolderName")

Debug.Print searchFold.Path


End Sub

Any ideas?


Solution

  • Modify your function to just test the current folder:

    Function FindFolder(CurrentDirectory As Scripting.Folder, FolderName As String) As Scripting.Folder
    
    On Error GoTo errHandler
    
    If CurrentDirectory .Name = FolderName Then _
       Set FindFolder = CurrentDirectory : Exit Function
    
    Set FindFolder = Nothing
    
    Dim fold As Scripting.Folder
    
    If CurrentDirectory.SubFolders.Count > 0 Then
    For Each fold In CurrentDirectory.SubFolders
        Debug.Print fold.Path
        Set FindFolder = FindFolder(fold, FolderName)
        If not(FindFolder Is Nothing) Then
          Exit For ' this one
        End If
    Next fold
    End If