【发布时间】:2018-01-03 00:19:55
【问题描述】:
我想访问我当前文件夹的每个子文件夹(每个子文件夹中的子文件夹数量可能会有所不同),然后想在所有这些子文件夹的每个 excel 工作簿中执行一些操作。
下面提到的是代码,代码不会引发编译时错误但无法正常工作。请帮帮我
option explicit
Sub LoopFolders()
Dim strFolder As String
Dim strSubFolder As String
Dim strFile As String
Dim colSubFolders As New Collection
Dim varItem As Variant
Dim wbk As Workbook
' Parent folder including trailing backslash
strFolder = "C:\Users\Yashika Vaish\Desktop\yashika\"
' Loop through the subfolders and fill Collection object
strSubFolder = Dir(strFolder & "*", vbDirectory)
Do While Not strSubFolder = ""
Select Case strSubFolder
Case ".", ".."
' Current folder or parent folder - ignore
Case Else
' Add to collection
colSubFolders.Add Item:=strSubFolder, Key:=strSubFolder
End Select
' On to the next one
strSubFolder = Dir
Loop
' Loop through the collection
For Each varItem In colSubFolders
' Loop through Excel workbooks in subfolder
strFile = Dir(strFolder & varItem & "\*.xls*")
Do While strFile <> ""
' Open workbook
Set wbk = Workbooks.Open(FileName:=strFolder & _
varItem & "\" & strFile, AddToMRU:=False)
MsgBox "I am open"
strFile = Dir
Loop
Next varItem
End Sub
工具设置中所有必需的引用都已添加到此 VBA 项目中。请帮我处理这段代码。
【问题讨论】:
-
您到底想对子文件夹中的文件做什么?
-
我需要打开这些文件并导入一些宏并运行它们,但是在访问所有子文件夹时会出现问题。请帮我解决这个问题
-
“不工作”没有帮助。代码的作用与预期的不同?您应该进行一些
Debug.Print调用,以找出正在找到的目录与应该找到的目录。没有明显的原因上述代码不起作用。我假设你只会深入一层?上面的代码对于任意深度都不是递归的。通常,搜索文件/文件夹的问题归结为缺少路径分隔符或在验证代码后搜索错误的目录。