1
\$\begingroup\$

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 & "\"
 search = Dir(folderName & "\*", vbDirectory)
 While Len(search) > 0
 If Not search = "." And Not search = ".." Then
 If GetAttr(folderName & search) = 16 Then
 dirList.Add folderName & search
 Else
 If LCase(search) = LCase(FileName) Then
 FoundFile = folderName & FileName
 FindFile = FoundFile
 Exit Function
 End If
 End If
 End If
 search = Dir()
 Wend
 Dim fld
 For Each fld In dirList
 If Len(FoundFile) > 0 Then
 FindFile = FoundFile
 Exit Function
 Else
 FindFile = FindFile(CStr(fld), FileName, FoundFile)
 End If
 Next
End Function
asked Apr 17, 2019 at 1:54
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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 & "\"
 search = Dir(folderName & "\*", vbDirectory)
 While Len(search) > 0
 If Not search = "." And Not search = ".." Then
 If GetAttr(folderName & search) = 16 Then
 dirList.Add folderName & search
 Else
 If LCase(search) = LCase(FileName) Then
 FindFile = folderName & 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) > 0 Then
 FindFile = FoundFile
 Exit Function
 End If
 Next
End Function
answered May 20, 2019 at 5:30
\$\endgroup\$
1
  • \$\begingroup\$ Very nice. Why didn't I think of that? \$\endgroup\$ Commented May 22, 2019 at 15:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.