我試圖迭代地打開選定檔案夾中的每個 Excel 檔案,然后在每個檔案上運行一系列子例程。我最初開發了一個宏(懶惰地命名為 Main),它打開一個檔案并執行適當的操作——據我所知,這個子作業得很好。
我現在正在構建一個名為 FolderPicker 的子程式,它將打開選定檔案夾中的每個檔案,然后運行 ??Main 子程式。
目前,我有這段代碼,改編自https://www.thespreadsheetguru.com/the-code-vault/2014/4/23/loop-through-all-excel-files-in-a-given-folder
Sub FolderPicker()
Dim wb As Workbook
Dim myPath As String
Dim MyFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
MyFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While MyFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & MyFile)
vFileName = myPath & MyFile
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Run main sub
main
'Ensure main has completed
DoEvents
'Save and Close Workbook
wb.Activate
wb.Close savechanges:=False
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
MyFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
這個宏的開頭運行得很好,檔案夾對話框作業,它打開了第一個檔案。但是,直接進行 Loop 的 MyFile = Dir 行似乎不起作用 - 它評估為空值,然后 sub 結束。我已驗證該檔案夾中有多個檔案。
作為參考,vFileName 是在 Main 中使用的公開宣告的變體。
有什么建議?
uj5u.com熱心網友回復:
您不能使用嵌套Dir()回圈,因此如果main還使用了Dir()then 您將需要采用不同的方法,例如將所有匹配項從外部添加Dir()到集合中,然后回圈遍歷它以呼叫main每個匹配項。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/409599.html
標籤:
上一篇:在接下來的n列中重復值
