Explanation Needed – How Code that Recursively Search Works
I have a function that uses the FSO to recursively search folders looking for files. The code is included at the bottom of the posts (mind the typos!) I can use this function and modify it suit my needs, but I do not have a full understanding how the function works. I understand the comments in the function (which describe what the function is doing), but I cannot grasp how the function can call itself to do a recursively search. Is this what one calls a “call back” function? Can someone explain the recursive behavior of this function step-by-step? for example, what is going on when this line executes?
funFindFile = funFindFile + funFindFile(fldSubFolder.Path, strFilePattern, intFolderCount, intFileCount)
I interpret this code as: the return of the function = the return of the function + return of the function. To me, this does not make any sense- but, it works! how is this so?
Thanks you!
–Llyal
Private Function funFindFile(ByVal strFolderPathname As String, strFilePattern As String, intFolderCount As Integer, intFileCount As Integer) As Long
Dim objFSO As New FileSystemObject
Dim fldFolder as Folder
Dim fldSubFolder As Folder
Dim strFileName as String
‘ set FSO to folder specified by strFolderPathname
Set fldFolder = objFSO.GetFolder(strFolderPathname)
‘ get file in folder that matches strFilePattern
strFileName = Dir(objFSO.BuildPath(fldFolder.Path, strFilePattern), vbNormal Or vbHidden Or vbSystem Or vbReadOnly)
‘ if file exists
While Len(strFileName) 0
‘ get complete pathname for matched file
funFindFile = funFindFile + FileLen(objFSO.BuildPath(fldFolder.Path,, strFileName))
‘ increment file count
intFileCount = intFileCount + 1
‘ add matched file pathname to files found listbox
lstFoundFiles.AddItem objFSO.BuildPath(fldFolder.Path, strFileName)
‘ get next file
strFileName = Dir()
‘ yield control back to user
DoEvents
Wend
lblSearchPathname = “Searching ” & vbCrLf & fldFolder.Path & “…”
intFolderCount = intFolderCount + 1
If (fldFolder.SubFolders.Count > 0) Then
For Each fldSubFolder In fldFolder.SubFolders
DoEvents
funFindFile = funFindFile + funFindFile(fldSubFolder.Path, strFilePattern, intFolderCount, intFileCount)
Next
End If
End Function