\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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
-
\$\begingroup\$ Very nice. Why didn't I think of that? \$\endgroup\$TinMan– TinMan2019年05月22日 15:57:37 +00:00Commented May 22, 2019 at 15:57
lang-vb