如何将行从工作簿复制并粘贴到具有非连续行的另一行

时间:2015-01-16 17:46:04

标签: excel vba excel-vba

Private Sub CommandButton21_Click()

Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open("Name of Copied Document")
Set y = Workbooks.Open("Name of Pasted Document")

'Now, copoy what you want from x:
x.Sheets("Report Data").Range("A7:ax7").Copy

'Now, paste to y worksheet:
y.Sheets("Jan").Range("A7:ax7").PasteSpecial

'Close x:
x.Close

End Sub

我正在使用此代码将现有数据中的行复制并粘贴到同一行中的另一个工作簿中。我想复制从A7:AX7和A23:ax23,但不希望它们之间的行。最终结果是复制的数据与从X表到Y表的行相同。

1 个答案:

答案 0 :(得分:1)

简单的方法就是使用循环迭代你的操作范围。这样您就不必复制粘贴代码:

Private Sub CommandButton21_Click()

    Dim x As Workbook
    Dim y As Workbook

    '## Open both workbooks first:
    Set x = Workbooks.Open("Name of Copied Document")
    Set y = Workbooks.Open("Name of Pasted Document")

    Dim rangeCells As Variant
    For Each rangeCells In Split("A7:AX7,A23:AX23", ",")
        'Now, copy what you want from x:
        x.Sheets("Report Data").Range(rangeCells).Copy

        'Now, paste to y worksheet:
        y.Sheets("Jan").Range(rangeCells).PasteSpecial
    Next

    'Close x:
    x.Close

End Sub

注意我是如何通过在Split语句中使用逗号分隔的字符串标识范围地址来重用复制粘贴代码。例如,如果您想添加另一个副本范围,则可以将其添加到最后。

例如:

    ' Also add A50:AX50 to the copy-paste operation.
    For Each rangeCells In Split("A7:AX7,A23:AX23,A50:AX50", ",")