VBA List all files (fast way) in subfolders withou

2019-01-27 00:57发布

问题:

I'm searching for a way for fast listing all files from subfolders of folder. Approach based on FileSystemObject is too slow - it takes ~6 minutes for listing 416 filenames from a network drive (intranet), as I understand Dir() function doesn't allow for looping throught subfolders.

回答1:

Use CMD instead:

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