我的遍历单个文件的脚本运行良好,但现在我需要让它也能够遍历多个目录。我被卡住了...
需要按顺序进行以下操作:
- 提示用户选择需要的根目录
- 我需要让脚本查找该根目录中的所有文件夹
- 如果脚本找到一个文件夹,就打开第一个文件夹(所有文件夹都没有特定的搜索过滤器)
- 打开后,我的脚本将循环遍历文件夹中的所有文件并执行其所需操作
- 完成后,关闭文件,关闭目录,然后移动到下一个文件夹等等
- 循环直到所有文件夹都被打开/扫描完
这是我拥有的代码,它不起作用,我知道它是错误的:
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 文件。请参见 https://dev59.com/HWkw5IYBdhLWcg3wirCs - brettdj