【引用地址】https://blog.csdn.net/bigheadsheep/article/details/46653031
<span style="font-size:14px;">VBA遍歷文件夾常用有三種方法,這三種方法中,filesearch不適合2007和2010版本磷账,而且速度比較慢鲜棠,遞歸法速度也慢载慈。只有用DIR加循環(huán)的方法,速度飛快。下面是三種方法的代碼:
1署惯、filesearch法
Sub test3()
Dim wb As Workbook
Dim i As Long
Dim t
t = Timer
With Application.FileSearch '調(diào)用fileserch對象
.NewSearch '開始新的搜索
.LookIn = ThisWorkbook.path '設(shè)置搜索的路徑
.SearchSubFolders = True '搜索范圍包括 LookIn 屬性指定的文件夾中的所有子文件夾
.Filename = "*.xls" '設(shè)置搜索的文件類型
' .FileType = msoFileTypeExcelWorkbooks
If .Execute() > 0 Then '如果找到文件
For i = 1 To .FoundFiles.Count
'On Error Resume Next
Cells(i, 1) = .FoundFiles(i) '把找到的文件放在單元格里
Next i
Else
MsgBox "沒找到文件"
End If
End With
MsgBox Timer - t
End Sub
2又官、遞歸法
Sub Test()
Dim iPath As String, i As Long
Dim t
t = Timer
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "請選擇要查找的文件夾"
If .Show Then
iPath = .SelectedItems(1)
End If
End With
If iPath = "False" Or Len(iPath) = 0 Then Exit Sub
i = 1
Call GetFolderFile(iPath, i)
MsgBox Timer - t
MsgBox "文件名鏈接獲取完畢延刘。", vbOKOnly, "提示"
End Sub
Private Sub GetFolderFile(ByVal nPath As String, ByRef iCount As Long)
Dim iFileSys
'Dim iFile As Files, gFile As File
'Dim iFolder As Folder, sFolder As Folders, nFolder As Folder
Set iFileSys = CreateObject("Scripting.FileSystemObject")
Set iFolder = iFileSys.GetFolder(nPath)
Set sFolder = iFolder.SubFolders
Set iFile = iFolder.Files
With ActiveSheet
For Each gFile In iFile
' .Hyperlinks.Add anchor:=.Cells(iCount, 1), Address:=gFile.path, TextToDisplay:=gFile.Name
iCount = iCount + 1
Next
End With
'遞歸遍歷所有子文件夾
For Each nFolder In sFolder
Call GetFolderFile(nFolder.path, iCount)
Next
End Sub
3、dir循環(huán)法
Sub Test() '使用雙字典六敬,旨在提高速度
Dim MyName, Dic, Did, i, t, F, TT, MyFileName
'On Error Resume Next
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "選擇文件夾", 0, 0)
If Not objFolder Is Nothing Then lj = objFolder.self.path & ""
Set objFolder = Nothing
Set objShell = Nothing
t = Time
Set Dic = CreateObject("Scripting.Dictionary") '創(chuàng)建一個字典對象
Set Did = CreateObject("Scripting.Dictionary")
Dic.Add (lj), ""
i = 0
Do While i < Dic.Count
Ke = Dic.keys '開始遍歷字典
MyName = Dir(Ke(i), vbDirectory) '查找目錄
Do While MyName <> ""
If MyName <> "." And MyName <> ".." Then
If (GetAttr(Ke(i) & MyName) And vbDirectory) = vbDirectory Then '如果是次級目錄
Dic.Add (Ke(i) & MyName & "\"), "" '就往字典中添加這個次級目錄名作為一個條目
End If
End If
MyName = Dir '繼續(xù)遍歷尋找
Loop
i = i + 1
Loop
Did.Add ("文件清單"), "" '以查找D盤下所有EXCEL文件為例
For Each Ke In Dic.keys
MyFileName = Dir(Ke & "*.xls")
Do While MyFileName <> ""
Did.Add (Ke & MyFileName), ""
MyFileName = Dir
Loop
Next
For Each Sh In ThisWorkbook.Worksheets
If Sh.Name = "XLS文件清單" Then
Sheets("XLS文件清單").Cells.Delete
F = True
Exit For
Else
F = False
End If
Next
If Not F Then
Sheets.Add.Name = "XLS文件清單"
End If
Sheets("XLS文件清單").[A1].Resize(Did.Count, 1) = WorksheetFunction.Transpose(Did.keys)
TT = Time - t
MsgBox Minute(TT) & "分" & Second(TT) & "秒"
End Sub
</span>