【问题标题】:VBA List all files (fast way) in subfolders without FileSystemObjectVBA列出没有FileSystemObject的子文件夹中的所有文件(快速方式)
【发布时间】:2015-09-16 22:12:40
【问题描述】:

我正在寻找一种方法来快速列出文件夹子文件夹中的所有文件。基于 FileSystemObject 的方法太慢了 - 列出来自网络驱动器(内联网)的 416 个文件名大约需要 6 分钟,因为我理解 Dir() 函数不允许循环遍历子文件夹。

【问题讨论】:

    标签: vba subdirectory dir


    【解决方案1】:

    改用 CMD:

    Sub SO()
    
    Const parentFolder As String = "C:\Users\bloggsj\folder\" '// change as required, keep trailing slash
    
    Dim results As String
    
    results = CreateObject("WScript.Shell").Exec("CMD /C DIR """ & parentFolder & "*.*"" /S /B /A:-D").StdOut.ReadAll
    
    Debug.Print results
    
    '// uncomment to dump results into column A of spreadsheet instead:
    '// Range("A1").Resize(UBound(Split(results, vbCrLf)), 1).Value = WorksheetFunction.Transpose(Split(results, vbCrLf))
    '//-----------------------------------------------------------------
    '// uncomment to filter certain files from results.
    '// Const filterType As String = "*.exe"
    '// Dim filterResults As String
    '// 
    '// filterResults = Join(Filter(Split(results, vbCrLf), filterType), vbCrLf)
    '//
    '// Debug.Print filterResults
    End Sub
    

    【讨论】:

    • 它只是复制打开的 cmd.exe 并运行 DIR 命令——不过在我看来它比 FSO 快得多。
    • 是否可以修改上述调用以一次仅搜索特定文件扩展名:.exe 和 .com?
    • 是的,例如将"*.*"" 更改为"*.exe"""*.com""。或者,您可以过滤结果。我将编辑帖子以显示如何。
    • 如果我将“.”更改为“*.xls”,它还会找到“.xlsm”文件,因此它意识到包含不相等的调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2018-08-06
    相关资源
    最近更新 更多