【发布时间】:2020-06-07 22:37:42
【问题描述】:
首先,我不得不说我对 VBA 还是很陌生。我已经使用 Excel 几年了,并且非常了解它,但是 VBA 编辑器对我来说是一种新事物。
我需要创建一个宏来设法找到具有特定名称的文件夹所在的父文件夹并打开它。我设法做到了(见下面的代码)。但是,搜索速度太慢了。该脚本的整个建议是为了节省时间和准确,目前,在 Windows 资源管理器中查找文件夹更快。宏大约需要 1-2 分钟,而资源管理器需要 10 秒。
我想知道是否有办法加快速度。任何帮助将不胜感激。
Option Explicit
Dim FileSystem As Object
Dim S As Boolean
Dim HostFolder As String
Sub FindFolder()
HostFolder = "W:\Branches\City\Name\NAME QUOTING"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
S = False
DoFolder FileSystem.GetFolder(HostFolder)
If S = False Then
MsgBox "Folder not found"
End If
End Sub
Sub DoFolder(Folder)
Dim SubFolder
Dim StockCode As String
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
StockCode = Selection.Value
If SubFolder.Name Like "*" & StockCode & "*" Then
Call Shell("explorer.exe " & SubFolder.ParentFolder, vbNormalFocus)
S = True
Exit For
End If
Next SubFolder
End Sub
【问题讨论】:
-
当你找到你的文件时,你需要退出整个递归。也许将
Exit For更改为Exit Sub并在DoFolder SubFolder之后添加一行If S Then Exit Sub