Recursive File Search Using the Dir() Function There are plenty of examples of using the FileSystemObject to recursively search for a file in subfolders.  I thought that it would be interesting to write one using the Dir() function. 

I was wondering if there is a way to return the found file without using the extra FoundFile parameter?



Function FindFile(ByVal folderName As String, ByVal FileName As String, Optional ByRef FoundFile As String) As String
    Dim search As String
    Dim dirList As New Collection

    If Not Right(folderName, 1) = "\" Then folderName = folderName &amp; "\"
    search = Dir(folderName &amp; "\*", vbDirectory)
    While Len(search) &gt; 0
        If Not search = "." And Not search = ".." Then
            If GetAttr(folderName &amp; search) = 16 Then
                dirList.Add folderName &amp; search
            Else
                If LCase(search) = LCase(FileName) Then
                    FoundFile = folderName &amp; FileName
                    FindFile = FoundFile
                    Exit Function
                End If
            End If

        End If
        search = Dir()
    Wend

    Dim fld
    For Each fld In dirList
        If Len(FoundFile) &gt; 0 Then
            FindFile = FoundFile
            Exit Function
        Else
            FindFile = FindFile(CStr(fld), FileName, FoundFile)
        End If
    Next

End Function
Just remove it from parameter,
and make it a variable. 

Function FindFile(ByVal folderName As String, ByVal FileName As String) As String
    Dim search As String
    Dim dirList As New Collection

    If Not Right(folderName, 1) = "\" Then folderName = folderName &amp; "\"
    search = Dir(folderName &amp; "\*", vbDirectory)
    While Len(search) &gt; 0
        If Not search = "." And Not search = ".." Then
            If GetAttr(folderName &amp; search) = 16 Then
                dirList.Add folderName &amp; search
            Else
                If LCase(search) = LCase(FileName) Then
                    FindFile = folderName &amp; FileName
                    Exit Function
                End If
            End If

        End If
        search = Dir()
    Wend

    Dim fld
    Dim FoundFile As String
    For Each fld In dirList

        FoundFile = FindFile(CStr(fld), FileName)
        If Len(FoundFile) &gt; 0 Then
            FindFile = FoundFile
            Exit Function
        End If
    Next


End Function