下面的代码在我选择的文件夹中的excel工作簿中进行了循环,但是由于某种原因,每次我运行该代码时,它都会跳过一个随机文件。例如,我在选定的文件夹中有8个文件-它仅执行我对其中7个文件的代码中的复制粘贴任务。它还没有按顺序循环-例如,它首先循环浏览第三个文件,然后循环浏览第二个第五文件...等等。.HALP
'Retrieve Target Folder Path 'Opens folder picker and prompts user to navigate to current month's templates location Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode 'If OK is selected
myPath = .SelectedItems(1) & "\" 'Assigns selected folder to myPath
End With
'If user does not select folder and hits Cancel NextCode: myPath = myPath If myPath = "" Then GoTo ResetSettings
'Target File Extension myExtension = "*.xls*"
'DIR function gets first file name in the folder 'with appropriate file
myFile = Dir(myPath & myExtension) 'Loop through each excel file in folder until DIR 'cannot find anymore
Do While myFile <> ""
'Opens the file and assigns to wb variable for future use
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Copy the balance worksheet(Sheet2)from each workbook
'in the specified folder and paste to master
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then
'Copy entire worksheet
wb.Worksheets(2).Cells.Copy
'PasteSpecial Values Only
wb.Worksheets(2).Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False 'Clears Clipboard
'Copy the values pasted in workbook
'and paste to the Master file
wb.Worksheets(2).Copy Before:=ThisWorkbook.Sheets(1)
'Set the name of the newly pasted values
'in the master file to the name of the workbook the values were copied from
ActiveSheet.Name = wb.Name
End If
Next Set wb = Nothing 'Close Workbook
Workbooks(myFile).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!"
End Sub
它应该循环遍历文件夹中的所有文件,但不是。每次我运行代码时,跳过的文件都是零星的。