7,765
社区成员
发帖
与我相关
我的任务
分享
Option Explicit
'*************************************************************************
'**模 块 名:ModSearchFile
'**说 明:搜索文件
'**创 建 人:嗷嗷叫的老马
'**日 期:2004年10月27日
'**版 本:V1.0
'*************************************************************************
Private FoundFile() As String '存放传回值的字串阵列
Private Ntx As Long
Public Function SearchFileInPath(ByVal thePath As String, ByVal theFileName As String, Optional ByVal mStop As Boolean = False) As String()
'使用递归方式搜索文件
'thePath - 要搜索的目录
'theFileName - 文件名,支持通配符
'mStop - T=找到一个就返回,F=返回所有找到的文件
'返回值:
' 搜索到的文件
If Right(thePath, 1) <> "\" Then thePath = thePath & "\"
Call GetFileLoop(thePath, theFileName, mStop)
SearchFileInPath = FoundFile
End Function
Private Function GetFileLoop(CurrentPath As String, ByVal SearFile As String, Optional ByVal mStop As Boolean = False) As String
Dim nI As Integer, nDirectory As Integer, I As Long
Dim sFileName As String, sDirectoryList() As String
On Error Resume Next
sFileName = Dir(CurrentPath, vbHidden Or vbDirectory Or vbReadOnly Or vbSystem)
Do While sFileName <> ""
If UCase(sFileName) Like UCase(SearFile) Then
I = GetAttr(CurrentPath + sFileName)
If (I And vbDirectory) = 0 Then
If mStop = False Then
ReDim Preserve FoundFile(Ntx)
FoundFile(Ntx) = CurrentPath + sFileName
Ntx = Ntx + 1
Else
GetFileLoop = CurrentPath + sFileName
Exit Function
End If
End If
End If
If sFileName <> "." And sFileName <> ".." Then
If GetAttr(CurrentPath & sFileName) _
And vbDirectory Then
nDirectory = nDirectory + 1
ReDim Preserve sDirectoryList(nDirectory)
sDirectoryList(nDirectory) = CurrentPath & sFileName
End If
End If
sFileName = Dir
Loop
For nI = 1 To nDirectory
GetFileLoop = GetFileLoop(sDirectoryList(nI) & "\", SearFile)
If GetFileLoop <> "" And mStop = True Then Exit For
Next nI
End Function
Sub Test()
'搜索文件模块测试过程
'BY 嗷嗷叫的老马
'紫水晶工作室
'http://www.m5home.com/
Dim I() As String, J As Long
I = SearchFileInPath("c:\windows\web", "*.*")
For J = 0 To UBound(I)
Debug.Print I(J) '打印所有文件
Next
End Sub