在子文件夹中打开具有部分名称的所有文件 – 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循环中,以尽量减less处理时间?

谢谢

而不是For each循环,尝试如果下面的lop更快:

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