|
- Dim strFileDir() As String
- Dim lngCurDirID As Long
- Dim lDirCount As Long, lFileCount As Long
- '测试用例
- Sub Test()
- Dim sPath As String, strFiles() As String
- sPath = ThisWorkbook.Path
-
- lDirCount = 0: lFileCount = 0: lngCurDirID = 0
- '查找当前目录及子目录下,后缀为【xls*】的文件
- If search(sPath, strFiles, "xls") = True Then
- MsgBox "共找到 " & UBound(strFiles) & " 个文件 "
- 'strFiles 就是储存 文件路径及名称的 数组
- Else
- MsgBox "没有找到文件或搜索失败"
- End If
- End Sub
- '查找指定路径及其子文件下 的所有文件,可指定特定的后缀
- Public Function search(ByVal strPath As String, ByRef strFileName() As String, Optional strExtName As String = "") As Boolean
- Dim strFile As String, blIsFind As Boolean
- On Error GoTo MyErr
- If Right(strPath, 1) <> "" Then strPath = strPath + ""
- strFile = Dir(strPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)
- While strFile <> "" '搜索当前目录
- DoEvents
- If (GetAttr(strPath + strFile) And vbDirectory) = vbDirectory Then '如果找到的是目录
- If strFile <> "." And strFile <> ".." Then '排除掉父目录(..)和当前目录(.)
- lDirCount = lDirCount + 1 '将目录数增1
- ReDim Preserve strFileDir(1 To lDirCount) As String
- strFileDir(lDirCount) = strPath & strFile '用动态数组保存当前目录名
- End If
- Else
- '判断后缀是否相同
- blIsFind = False
- If strExtName = "" Then
- blIsFind = True
- ElseIf LCase(GetExtName(strPath + strFile)) Like LCase(strExtName) Then
- blIsFind = True
- End If
- If blIsFind Then '后缀相同
- lFileCount = lFileCount + 1 '将文件数增1
- ReDim Preserve strFileName(1 To lFileCount) As String
- strFileName(lFileCount) = strPath + strFile '用动态数组保存当前文件名
- End If
- End If
- strFile = Dir
- Wend
-
- lngCurDirID = lngCurDirID + 1
- If lngCurDirID <= lDirCount Then Call search(strFileDir(lngCurDirID), strFileName, strExtName) '递归搜索子目录
- search = True '搜索成功
- Exit Function
- MyErr:
- search = False '搜索失败
- End Function
- '获取后缀
- Public Function GetExtName(strFileName As String) As String
- Dim strTmp As String
- Dim strByte As String
- Dim i As Long
- For i = Len(strFileName) To 1 Step -1
- strByte = Mid(strFileName, i, 1)
- If strByte <> "." Then
- strTmp = strByte + strTmp
- Else
- Exit For
- End If
- Next i
- GetExtName = strTmp
- End Function
复制代码 |
|