Dim FolderArray(), FileArray() As String ‘全名
Dim FolderCount, FileCount As Integer
Dim I, J As Integer
SearchFiles “E:\”, “*”, True ‘查找所有文件
If IsEmptyArray(FileArray) Then Exit Sub
For I = LBound(FolderArray) To UBound(FolderArray)
Debug.Print FolderArray(I)
Next I
Debug.Print FolderCount; “Folders”
For I = LBound(FileArray) To UBound(FileArray)
Debug.Print FileArray(I)
Next I
Debug.Print FileCount; “Files”
‘调用示例(支持通配符)
‘SearchFiles “C:\Program Files\WinRAR\”, “” ‘查找所有文件 ‘SearchFiles “C:\Program Files\WinRAR\”, “.exe” ‘查找所有exe文件
‘SearchFiles “C:\Program Files\WinRAR\”, “in.exe” ‘查找文件名中包含有 in 的exe文件
Private Function SearchFiles(sTargetPath As String, sPartialName As String, Optional bAllPaths As Boolean = True)
Dim I, J As Integer
Dim SubFolderCount As Long
Dim SubFolderArray() As String ‘子文件夹全名
Dim sPath As String ‘文件名或子文件夹短名
If Right(sTargetPath, 1) <> “\” Then sTargetPath = sTargetPath & “\”
FolderCount = FolderCount + 1
ReDim Preserve FolderArray(1 To FolderCount)
FolderArray(FolderCount) = sTargetPath
sPath = Dir(GetFullName(sTargetPath, sPartialName)) ‘查找第一个文件
Do While Len(sPath) ‘循环到没有文件为止
FileCount = FileCount + 1
ReDim Preserve FileArray(1 To FileCount)
FileArray(FileCount) = sTargetPath & sPath ‘将文件目录和文件名组合,并存放到数组中
sPath = Dir ‘查找下一个文件
DoEvents ‘让出控制权
Loop
If Not bAllPaths Then Exit Function
sPath = Dir(sTargetPath, vbDirectory) ‘查找第一个文件夹
Do While Len(sPath) ‘循环到没有文件夹为止
If Left(sPath, 1) <> “.” Then ‘为了防止重复查找
If GetAttr(GetFullName(sTargetPath, sPath)) And vbDirectory Then ‘如果是文件夹则… …
SubFolderCount = SubFolderCount + 1
ReDim Preserve SubFolderArray(1 To SubFolderCount)
SubFolderArray(SubFolderCount) = GetFullName(sTargetPath, sPath) & “\” ‘将目录和文件夹名称组合形成新的目录,并存放到数组中
End If
End If
sPath = Dir ‘查找下一个文件夹
DoEvents ‘让出控制权
Loop
For I = 1 To SubFolderCount ‘使用递归方法,遍历所有目录
SearchFiles SubFolderArray(I), sPartialName
Next
End Function