[英]Copy Data from Workbooks Sheet1 to Master Sheet
I have macro, which copies data from selected workbooks' Sheet1 to this main workbook's Sheet1 in last row.我有宏,它将数据从选定工作簿的 Sheet1 复制到最后一行的主工作簿的 Sheet1 中。 For small number of files, it is fast, but when I select more files (say 20), it breaks and excel even crashes.
对于少量文件,它很快,但是当我 select 更多文件(比如 20 个)时,它会中断并且 excel 甚至崩溃。 How to make this more efficient as I am already using Application.EnableEvents and ScreenUpdating?
由于我已经在使用 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
With blocks
so you don't call the referencing object over and over and over.With blocks
,这样您就不会一遍又一遍地调用引用 object。 Write the values directly as opposed to using the slower copy/paste.直接写入值,而不是使用较慢的复制/粘贴。
For i = 1 To tempFileDialog.SelectedItems.Count Set sourceWorkbook = Workbooks.Open(tempFileDialog.SelectedItems(i)) With sourceWorkbook.Worksheets(1) If.Range("A1") <> "" Then Dim valRange as Range With.Cells(1).CurrentRegion Set valRange =.Offset(1).Resize(.Rows.Count - 1, .Columns.Count - 1) End With End With End If With ThisWorkbook.Worksheets("Sheet1") loLastRow =.Cells(Rows.Count, 1).End(xlUp).Row + 1.Range("A" & loLastRow).Resize(valRange.Rows.Count,valRange.Columns.Count).Value = valRange.Value 'ThisWorkbook.Save End With sourceWorkbook.Close Next i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.