简体   繁体   English

EXCEL VBA:将行从工作表A复制到工作表B的末尾

[英]EXCEL VBA: Copy Rows from Sheet A to end of Sheet B

I am trying to Copy rows from Sheet A to the end of Sheet B which already has a list of data in it. 我试图将行从工作表A复制到工作表B的末尾,工作表B中已有数据列表。 I used the code shown below. 我使用了下面显示的代码。 The problem is every time I try to run this particular code the whole program crashes. 问题是每次我尝试运行此特定代码时,整个程序都会崩溃。

Sub test()
Dim i As Integer
Dim j As Integer

i = ActiveSheet.Range("A1").End(xlDown).Row - 1  


    For j = 1 To 50
        On Error GoTo Err_Execute
        Sheets("A").Rows(j).Copy
        Sheets("B").Rows(i).Insert Shift:=xlDown
        i = i + 1
    Next j

Err_Execute:
        If Err.Number = 0 Then MsgBox "All have been copied!" Else _
        MsgBox Err.Description
End Sub

Below works. 下面的作品。 I have added a lastrow for sheet A just so that it is slightly more dynamic. 我为工作表A添加了一个lastrow,以便它更具动态性。 I have moved on error too, you dont need to set this every loop only at the beginning 我也犯了错误,您不必只在开始时就设置每个循环

Sub test()
Dim i As Integer
Dim j As Integer
Dim Last_row as Integer

i = Sheets("B").Range("A1").End(xlDown).Row + 1
last_row = Sheets("A").Range("A1").End(xlDown).Row

On Error GoTo Err_Execute
For j = 1 To last_row
    Sheets("A").Rows(j).EntireRow.Copy
    Sheets("B").Rows(i).PasteSpecial
    i = i + 1
Next j

Err_Execute:
        If Err.Number = 0 Then MsgBox "All have been copied!" Else _
        MsgBox Err.Description
End Sub

Actually why are you looping at all? 实际上,为什么要循环播放? The below just selects all the rows and copies them in one action. 下面仅选择所有行并将其复制到一个动作中。 Should be much quicker 应该更快

Sub test()
On Error GoTo Err_Execute
With Sheets("A")
    .Rows("1:" & .Range("A1").End(xlDown).Row).EntireRow.Copy
End With
With Sheets("B")
    .Rows(.Range("A1").End(xlDown).Row + 1).PasteSpecial
End With

Err_Execute:
        If Err.Number = 0 Then MsgBox "All have been copied!" Else _
        MsgBox Err.Description
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM