【发布时间】:2020-05-15 03:21:59
【问题描述】:
我使用以下代码循环浏览文件夹中的文件,打开文件,然后等待数据加载并保存并停止。但是,它不断重复循环。也就是说,在最后一个文件之后,它再次从第一个文件开始并不断循环。怎么了?
Sub morningstar_open_and_save_only_VBA()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
Dim StartTime As Double
Dim SecondsElapsed As Double
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
Application.ScreenUpdating = False
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 = "*.xlsx*"
'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)
Set cmd = Application.CommandBars("Cell").Controls("Refresh All")
cmd.Execute
'Ensure Workbook has opened before moving on to next line of code
wb.Close savechanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
SecondsElapsed = Round(Timer - StartTime, 2)
'Message Box when tasks are completed
MsgBox "Task Complete! in " & SecondsElapsed & " seconds"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
我是否将 "Do While myFile "" " 替换为 "Do While Len(myFile) > 0" ?为什么我的原始代码会出现这个错误?
-
@urdearboy 问题依然存在
-
Dir(不带参数)如果发出任何Dir(...)(带参数)将变得无效。是否执行了任何可以发出此类命令的代码(例如通过Open-event)?您是否尝试过改用FileSystemObject? -
@FunThomas 我不知道任何开放事件代码。上面的代码就是我跑的全部。所以我的代码“myFile = Dir(myPath & myExtension)”导致后面的任何 Dir 出现问题?