Best? Certainly not, I wrote this about a hundred years ago (don't laugh). Abuse as you see fit.
Option Explicit
[color=red]Public[/color] Sub Test ( )
Dim foldername As String, _
filespec As String, _
var As Variant
foldername = "c:\windows\temp"
[color=green] '' you could use this to reduce the initial scan results[/color]
filespec = "*.*"
[color=green] '' in a real world app you'd want to set the result to a collection
'' and then test the count before attempting to iterate it[/color]
For Each var In GetAllFiles(foldername, filespec, True)
Debug.Print var
[color=green] '' do your final file matching code here if filespec doesn't nail it[/color]
Next var
End Sub
[color=blue]Public[/color] Function GetAllFiles(foldername As String, filespec As String, recurse As Boolean) As Collection
Dim result As New Collection
Call GetAllFilesEx(foldername, filespec, recurse, result)
Set GetAllFiles = result
End Function
[color=red]Private[/color] Sub GetAllFilesEx(foldername As String, _
filespec As String, _
recurse As Boolean, _
ByRef result As Collection)
DoEvents
Dim filename As String, _
fullname As String, _
folder As Variant, _
folders As New Collection
If recurse Then
[color=green] '' get any folders[/color]
filename = Dir$(foldername & "\*.*", vbDirectory)
Do While filename <> ""
If filename = "." Then GoTo Iterate
If filename = ".." Then GoTo Iterate
fullname = foldername & "\" & filename
If GetAttr(fullname) And vbDirectory Then
folders.Add fullname
End If
Iterate:
filename = Dir$
Loop
End If
[color=green] '' get the files[/color]
filename = Dir$(foldername & "\" & filespec, vbHidden)
Do While filename <> ""
fullname = foldername & "\" & filename
result.Add fullname
filename = Dir$
Loop
For Each folder In folders
Call GetAllFilesEx(CStr(folder), filespec, recurse, result)
Next folder
End Sub
Edit: fixed a typo.