通過單個文件的我的循環腳本工作正常,但我現在需要它也查看/查看多個目錄。我堅持....循環訪問用戶指定的根目錄中的子文件夾和文件
事情需要發生的順序:
- 提示用戶選擇他們所需要
- 我需要劇本來尋找那個根的任何文件夾的根目錄目錄
- 如果腳本找到一個,它會打開第一個(所有文件夾,因此沒有針對該文件夾的特定搜索過濾器)
- 一旦打開,我的腳本將遍歷文件夾中的所有文件並執行所需的操作做
- 它的完成後,關閉該文件,關閉該目錄,並移動到下一個,等等。
- 循環,直到所有的文件夾都被打開/掃描
這是我,這不工作,我知道是錯誤的:
MsgBox "Please choose the folder."
Application.DisplayAlerts = False
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = "\\blah\test\"
.AllowMultiSelect = False
If .Show <> -1 Then MsgBox "No folder selected! Exiting script.": Exit Sub
CSRootDir = .SelectedItems(1)
End With
folderPath = Dir(CSRootDir, "\*")
Do While Len(folderPath) > 0
Debug.Print folderPath
fileName = Dir(folderPath & "*.xls")
If folderPath <> "False" Then
Do While fileName <> ""
Application.ScreenUpdating = False
Set wbkCS = Workbooks.Open(folderPath & fileName)
--file loop scripts here
Loop 'back to the Do
Loop 'back to the Do
最終代碼。它遍歷每個子目錄中的所有子目錄和文件。
Dim FSO As Object, fld As Object, Fil As Object
Dim fsoFile As Object
Dim fsoFol As Object
Dim fileName As String
MsgBox "Please choose the folder."
Application.DisplayAlerts = False
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = "\\blah\test\"
.AllowMultiSelect = False
If .Show <> -1 Then MsgBox "No folder selected! Exiting script.": Exit Sub
folderPath = .SelectedItems(1)
End With
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set fld = FSO.getfolder(folderPath)
If FSO.folderExists(fld) Then
For Each fsoFol In FSO.getfolder(folderPath).subfolders
For Each fsoFile In fsoFol.Files
If Mid(fsoFile.Name, InStrRev(fsoFile.Name, ".") + 1) = "xls" Then
fileName = fsoFile.Name
Application.ScreenUpdating = False
Set wbkCS = Workbooks.Open(fsoFile.Path)
'My file handling code
End If
Next
Next
End If
我會堅持'Dir'而不是'FSO',因爲它需要通配符,它會停止冗長的文件類型檢查來處理非Excel文件。見http://stackoverflow.com/questions/9827715/get-list-of-subdirs-in-vba – brettdj