所以基本上意图是在目录中使用VBA目录函数,获取该目录中的文件名,但避免/过滤掉获得某个扩展名。例如,我想要获取目录中不是“* .txt”或其他任何内容的所有文件。我更倾向于使用dir函数而不是其他解决方案,因为它似乎在获取文件列表和我尝试过的任何其他内容时非常有效/快速。
例如,像Dir(“Path”&“”&<>“ .txt”)。但你知道......有用的东西。哈哈。
我当然可以事后检查跳过任何扩展名为.txt的东西(拆分字符串或其他),但我想知道是否有更优雅/资源有效的东西,我可以使用语法一个Dir函数,以避免某个扩展名的文件。
提前致谢!
答案 0 :(得分:1)
Dim Files As Collection
Set Files = GetFilesIn("C:\") 'gets all the files
Set Files = GetFilesIn("C:\", "*.txt") 'gets all the txt files
Set Files = GetFilesIn("C:\", , "*.txt") 'gets all but the txt files
Function GetFilesIn(Folder As String, Optional Matching As String, Optional Unmatching As String) As Collection
Dim FName As String
Set GetFilesIn = New Collection
If Matching = "" Then
FName = Dir(Folder)
Else
FName = Dir(Folder & Matching)
End If
Do While FName <> ""
If Unmatching = "" Then
GetFilesIn.Add Folder & FName
Else
If Not FName Like Unmatching Then GetFilesIn.Add Folder & FName
End If
FName = Dir
Loop
End Function