将复制粘贴VBA宏从逐行更改为批量复制粘贴

时间:2015-10-16 17:28:01

标签: excel vba excel-vba copy-paste

我目前有一个VB宏,它会将值从一个表复制到另一个表。然而,目前,VB的编写方式是它将逐行执行,并且由于它经历了几千行,因此运行速度非常慢。我想知道如何更好地改变我的VB来进行批量复制粘贴以减少等待时间。代码是:

Sub copypaste_settlement_rows()

Dim LastRow As Long

Application.ScreenUpdating = False

Sheets("Settlement Template").Select
'find last row in column A
LastRow = Cells(Rows.Count, "A").End(xlUp).Row

For x = 2 To LastRow
    Cells(x, 1).Resize(1, 42).Copy
    Sheets("PIVOT DATA").Select
    NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
    Cells(NextRow, 1).Select
    Selection.PasteSpecial Paste:=xlPasteValues
    Sheets("Settlement Template").Select
Next x

Sheets(">> START HERE <<").Select

Application.CutCopyMode = False

Application.ScreenUpdating = True

End Sub

2 个答案:

答案 0 :(得分:6)

这应该是即时的,不使用剪贴板:

Sub copypaste_settlement_rows()
    Dim v
    With Sheets("Settlement Template")
        v = .Cells(2, 1).Resize(.Cells(.Rows.Count, "A").End(xlUp).Row, 42)
    End With
    With Sheets("PIVOT DATA")
        .Cells(.Rows.Count, "A").End(xlUp).Resize(UBound(v), UBound(v, 2)) = v
    End With
End Sub

答案 1 :(得分:1)

一种非常简单的方式(我在自己的代码中看到的最快)是:

ThisWorkbook.Worksheets("PIVOT DATA").Range("A2:A" & lastRow) = ThisWorkbook.Worksheets("Settlement Template").Range("A2:A" & lastRow).Value