在子文件夹中打开部分名称的所有文件 - VBA

时间:2015-06-22 13:45:59

标签: excel vba

我正在尝试打开名称以ToDo.xlsx结尾的所有文件,方法是执行遍历所有子文件夹的循环。

我在StackOverflow的另一篇文章中发现了这个循环,但是当有很多文件时(在我的情况下约为35k)需要花费太多时间:

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop
End Sub

我的处理代码是:

If InStr(oFile.Name,"ToDo"= <> 0 Then Workbooks.Open Filename:=oSubfolder & oFile

有没有办法将这个条件放在for循环中,以便最小化处理时间?

谢谢

1 个答案:

答案 0 :(得分:0)

代替For each循环,尝试以下lop更快:

filename = Dir(oFolder.Name & "\*ToDo.xlsx")
While (filename <> "")
    ' processing... Full name is oFolder.Name & "\" & filename
    filename = Dir
Wend