[英]Excel VBA: Search for a directory
In vba, I would like to search through directories for a specific directory name. 在vba中,我想在目录中搜索特定的目录名称。 Ideally the searching time would be fast (similar from a windows search). 理想情况下,搜索时间会很快(类似于Windows搜索)。
from different sources, I could build a script (given bellow) with a recursive sub program. 从不同的来源,我可以使用递归子程序构建脚本(如下所示)。 The script works but it is very slow as soon as the hierarchy is a little complex. 该脚本可以工作,但是一旦层次结构有点复杂,它就会非常慢。
Is there a way to make the search faster? 有没有办法使搜索更快?
Sub GetFolder(Folder As String, searchF As String, colFolder As Collection)
Dim SubFolder, subF As New Collection, sf As String
If Right(Folder, 1) <> "\" Then Folder = Folder & "\"
If Dir(Folder & searchF, vbDirectory) <> "" Then colFolder.Add Folder & searchF & "\"
sf = Dir(Folder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(Folder & sf) And vbDirectory) <> 0 Then
subF.Add Folder & sf
End If
End If
sf = Dir()
Loop
For Each SubFolder In subF
GetFolder CStr(SubFolder), searchF, colFolder
Next
End Sub
I think you are underestimating the hierarchy size. 我认为您低估了层次结构的大小。 Change your code to this one to see how many folders you are recursing through. 将代码更改为此代码,以查看要递归的文件夹数量。
Option Explicit
Sub GetFolder(Folder As String, searchF As String, colFolder As Collection, ByRef counter As Long)
Dim SubFolder, subF As New Collection, sf As String
If Right(Folder, 1) <> "\" Then Folder = Folder & "\"
If Dir(Folder & searchF, vbDirectory) <> "" Then colFolder.Add Folder & searchF & "\"
sf = Dir(Folder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(Folder & sf) And vbDirectory) <> 0 Then
Debug.Print Folder & sf
counter = counter + 1
subF.Add Folder & sf
End If
End If
sf = Dir()
Loop
For Each SubFolder In subF
GetFolder CStr(SubFolder), searchF, colFolder, counter
Next
End Sub
Public Sub TestMe()
Dim newC As New Collection
Dim colChecked As New Collection
Dim counter As Long
GetFolder "C:\Users\<username>\Desktop\BA Tools", "v", newC, counter
Debug.Print counter
End Sub
What is the number that you get at the end of the code, when you run it? 运行代码时,在代码末尾得到的数字是多少?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.