我想要訪問我當前文件夾的每個子文件夾(每個子文件夾中的子文件夾數可能不同),然後希望在每個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項目中。請幫助我使用此代碼。
你究竟想要處理子文件夾中的文件? – ThatOneGuy
我需要打開這些文件並導入一些宏並運行這些文件,但在訪問所有子文件夾時會出現問題。請幫助我解決這個問題 –
「不工作」對您沒有幫助。代碼與預期的結果是什麼?你應該拋出一些'Debug.Print'調用來找出正在被發現的目錄和應該找到的目錄。上面的代碼沒有明顯的理由不起作用。我假設你只會深入一層?上面的代碼對於任意深度不是遞歸的。通常,搜索文件/文件夾的問題歸結爲缺少路徑分隔符或在驗證代碼後搜索錯誤的目錄。 –