在VBA中,我如何获取特定目录中特定扩展名的所有文件列表?
因为我使用的是Excel 2007,所以无法使用Application.FileSearch
。
在VBA中,我如何获取特定目录中特定扩展名的所有文件列表?
因为我使用的是Excel 2007,所以无法使用Application.FileSearch
。
回应您的评论“那我需要运行多少次?”,此示例会一直运行,直到列出所有文件名与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()函数都会返回下一个。
另一种选择是使用“Microsoft Scripting Runtime”库(在工具...引用中检查),用于FileSystemObject对象系列。可能会像以下内容:
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
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*")
Debug.Print
是做什么的,请查看这个链接:https://dev59.com/Q3E85IYBdhLWcg3wKwKD - ecoe