我有一个名为AT5321.xlsx
的文件(此名称将不断更改),该文件是我要从中调用该宏的地方:
转到地址:C:\Atul\Data
搜索包含与原始文件相同名称的文件夹(例如:AT5321
)。文件夹的实际名称类似于:F-003-106-AT5321.M
现在,在打开上述子文件夹后,它具有一个名为report.xls
的文件,必须打开。
停止宏
正如您所必须拥有的,我是新手。 我希望减轻日常的Excel任务。
任何小小的帮助对我来说都是很有价值的。
答案 0 :(得分:0)
借助Cor_Blimey的帖子。(Loop Through All Subfolders Using VBA)
这将循环遍历子文件夹中的所有子文件夹和子文件夹(理论上是无限期的)。
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Dim FoundFolder as Boolean
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("C:\Atul\Data")
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder
If oSubfolder Like "*" & ThisWorkbook.Name & "*" Then 'Replace workbook name if necessary
Workbooks.Open Filename:=oSubfolder & "\report.xls"
FoundFolder = True
Exit For
End If
Next oSubfolder
Loop
If FoundFolder = False Then MsgBox "Error: Folder '" & ThisWorkbook.Name & "' could not be found", vbExclamation, "Error"
End Sub
或者,您可以只从主文件夹中查看子文件夹
Sub SubFoldersinMainFolder()
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("C:\Atul\Data")
Set subfolders = folder.subfolders
For Each subfolders In subfolders
If subfolders Like "*" & ThisWorkbook.Name & "*" Then 'Replace workbook name if necessary
Workbooks.Open Filename:= subfolders & "\report.xls"
FoundFolder = True
Exit For
End If
Next subfolders
If FoundFolder = False Then MsgBox "Error: Folder '" & ThisWorkbook.Name & "' could not be found", vbExclamation, "Error"
End Sub
我必须补充一点,“文件夹”一词现在开始看起来很奇怪