在 VBA 中,如何获取特定目录中具有特定扩展名的所有文件的列表?
我做不到Application.FileSearch
,因为我使用的是 excel 2007
在 VBA 中,如何获取特定目录中具有特定扩展名的所有文件的列表?
我做不到Application.FileSearch
,因为我使用的是 excel 2007
回应您的评论“那么我知道运行多少次?” ,此示例将一直运行,直到列出名称与strPattern匹配的所有文件。更改strFolder常量。
Public Sub ListESY()
Const strFolder As String = "C:\SomeFolder\"
Const strPattern As String = "*.ESY"
Dim strFile As String
strFile = Dir(strFolder & strPattern, vbNormal)
Do While Len(strFile) > 0
Debug.Print strFile '<- view this in Immediate window; Ctrl+g will take you there
strFile = Dir
Loop
End Sub
Dir("C:\yourPath\*.ESY", vbNormal) 返回第一个扩展名为 esy 的文件。对 Dir() 的每个后续调用都返回下一个。
替代选项:对 FileSystemObject 系列对象使用“Microsoft Scripting Runtime”库(在工具...参考中检查它)。可能类似于以下内容:
Public Function ESYFileCount(dir_path as String) as Long
Dim fil As File
With New FileSystemObject
With .GetFolder(dir_path)
For Each fil In .Files
If LCase(Right(fil.Name, 4)) = ".esy" Then
ESYFileCount = ESYFileCount + 1
End If
Next
End With
End With
End Function
以下代码的运行速度比使用 FileSystemObject 快大约 19 倍。在我的机器上,使用 FileSystemObject 在三个不同的目录中查找 4000 个文件需要 1.57 秒,但使用此代码只需 0.08 秒。
Public Function CountFilesWithGivenExtension( _
i_strFolderWithTerminalBackslant As String, _
i_strExtensionIncludingPeriod As String _
) As Long
If Len(Dir$(i_strFolderWithTerminalBackslant & "*" _
& i_strExtensionIncludingPeriod)) > 0 Then
CountFilesWithGivenExtension = 1
While Len(Dir$) > 0
CountFilesWithGivenExtension = _
CountFilesWithGivenExtension + 1
DoEvents
Wend
Else
CountFilesWithGivenExtension = 0
End If
End Function
示例用法:
Debug.Print CountFilesWithGivenExtension("C:\", ".ex*")
(“DoEvents”不是必需的,但允许您在需要时使用 Pause/Break。)