我有一个宏,它将宏从所选工作簿的Sheet1复制数据到最后一行的主工作簿的Sheet1中。对于少量文件,速度很快,但是当我选择更多文件(例如20个)时,它会中断并且甚至崩溃。在我已经在使用Application.EnableEvents和ScreenUpdating的情况下,如何提高效率?
Sub Copy_From_Workbooks()
Dim numberOfFilesChosen, i As Integer
Dim tempFileDialog As FileDialog
Dim sourceWorkbook As Workbook
Dim loLastRow As Long
Application.EnableEvents = False
Application.ScreenUpdating = False
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)
tempFileDialog.Filters.Add "Excel Files", "*.xlsx?", 1
tempFileDialog.AllowMultiSelect = True
numberOfFilesChosen = tempFileDialog.Show
For i = 1 To tempFileDialog.SelectedItems.Count
Workbooks.Open tempFileDialog.SelectedItems(i)
Set sourceWorkbook = ActiveWorkbook
If ActiveWorkbook.Worksheets(1).Range("A1") <> "" Then
With ActiveWorkbook.Worksheets(1)
With .Cells(1).CurrentRegion
.Offset(1).Resize(.Rows.Count - 1, .Columns.Count - 1).Copy
End With
End With
End If
With ThisWorkbook.Worksheets("Sheet1")
loLastRow = .Cells(Rows.Count, 1).End(xlUp).Row + 1
.Range("A" & loLastRow).PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
'ThisWorkbook.Save
End With
sourceWorkbook.Close
Next i
Application.EnableEvents = False
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
+----------------+
| Name Age DOB |
+----------------+
| John 31 06/09 |
| Bill 32 07/10 |
| Bob 34 08/11 |
+----------------+
,这样您就不会一遍又一遍地调用引用对象。直接写入值,而不是使用较慢的复制/粘贴。
With blocks