连接两列并粘贴到新工作簿

时间:2015-10-15 22:22:44

标签: excel vba excel-vba

我正在尝试连接两个列并将它们粘贴到同一工作簿中的另一个工作表中。有一个复杂因素,我必须为预定义的行范围而不是整列执行此操作。我已设法按如下方式复制一列,但我不知道如何将其扩展到两列的串联。

Sub Write_Rows(StartRow As Integer, EndRow As Integer)

Dim CopySheet As Worksheet, PasteSheet As Worksheet
Set CopySheet = Sheets("Sheet1")
Set PasteSheet = Sheets("Master") 'I already made this sheet

CopySheet.Range("B" & StartRow, "B" & EndRow).Copy PasteSheet.Range("A2")

End Sub

我要做的事情与this question中接受的答案完全相同,但在Excel中不是Google Spreadsheets。

1 个答案:

答案 0 :(得分:1)

您可以通过数组公式执行此操作,然后删除公式并修复值。假设您要连接列B和C:

Sub Write_Rows(StartRow As Integer, EndRow As Integer)

    Dim dest As Range: Set dest = Sheets("Master").Range("A2:A" & 2 + EndRow - StartRow)
    Dim src1 As Range: Set src1 = Sheet1.Range("B" & StartRow & ":B" & EndRow)
    Dim src2 As Range: Set src2 = src1.Offset(0, 1)

    dest.FormulaArray = "=" & src1.Address(External:=True) & "&" & src2.Address(External:=True)
    dest.Value = dest.Value

End Sub