Private Function SearchFiles(Path As String, FileType As String)
Dim Files() As String '文件路徑
Dim Folder() As String '文件夾路徑
Dim a, b, c As Long
Dim sPath As String
If Right(Path, 1) <> "\" Then Path = Path & "\"
sPath = Dir(Path & FileType) '查找第一個(gè)文件
Do While Len(sPath) '循環(huán)到?jīng)]有文件為止
a = a + 1
ReDim Preserve Files(1 To a)
Files(a) = Path & sPath '將文件目錄和文件名組合,并存放到數(shù)組中
List1.AddItem Files(a) '加入list控件中
'****************************************************
Open App.Path & "\ml.txt" For Append As #1
Write #1, Files(a)
Close #1
'*******************************************************
sPath = Dir '查找下一個(gè)文件
DoEvents '讓出控制權(quán)
Loop
sPath = Dir(Path & "\", vbDirectory) '查找第一個(gè)文件夾
Do While Len(sPath) '循環(huán)到?jīng)]有文件夾為止
If Left(sPath, 1) <> "." Then '為了防止重復(fù)查找
If GetAttr(Path & "\" & sPath) And vbDirectory Then '如果是文件夾則。。。。。。
b = b + 1
ReDim Preserve Folder(1 To b)
Folder(b) = Path & sPath & "\" '將目錄和文件夾名稱組合形成新的目錄,并存放到數(shù)組中
End If
End If
sPath = Dir '查找下一個(gè)文件夾
DoEvents '讓出控制權(quán)
Loop
For c = 1 To b '使用遞歸方法,遍歷所有目錄
SearchFiles Folder(c), FileType
Next
End Function
'調(diào)用示例
Private Sub Form_Load()
' * 星號(hào)表示多個(gè)任意字符
' SearchFiles "C:\Program Files\WinRAR\", "*" '查找所有文件
SearchFiles App.Path & "\", "*.mid" '查找所有exe文件
SearchFiles App.Path & "\", "*.mp3" '查找所有exe文件
' SearchFiles "C:\Program Files\WinRAR\", "*in*.exe" '查找文件名中包含有 in 的exe文件
End Sub