【问题标题】:VBA, Dir Function, Filtering to avoid filesVBA,Dir 函数,过滤以避免文件
【发布时间】:2013-06-15 03:23:38
【问题描述】:

所以基本上意图是在目录中使用 VBA dir 函数,获取该目录中的文件名,但避免/过滤掉获得某个扩展名。例如,我想获取目录中不是“* .txt”或其他任何文件的所有文件。与其他解决方案相比,我更喜欢使用 dir 函数,因为与我尝试过的任何其他方法相比,它似乎在获取文件列表方面效率更高/速度更快。

例如,类似 Dir("Path" & "" & ".txt")。但是你知道……一些有效的东西。哈哈。

我当然可以在事后检查以跳过任何带有 .txt 扩展名的内容(拆分字符串或其他任何内容),但我想知道是否有更优雅/资源效率更高的东西可以与语法一起使用一个 Dir 函数来避免具有特定扩展名的文件。

提前致谢!

【问题讨论】:

  • 我认为没有任何方法可以将“反模式”传递给Dir()。但是,您可以轻松跳过lcase(fName) Like "*.txt"

标签: excel function vba dir


【解决方案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

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2018-10-29
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多