如何在Excel中复制和粘贴动态范围?

时间:2019-05-02 14:25:29

标签: excel vba

我试图从表中复制动态范围并将其复制到另一个工作簿,但是复制创建的动态矩阵时遇到问题。

我尝试了多行代码,但结果相似。我一次只完成了一行代码,lastRow和lastColumn函数返回了预期的值。当我尝试选择矩阵并将其复制时,就会出现问题。我觉得这里有一个简单的修复程序,我想念一些东西。

Workbooks.Open Filename:=OOBmap

'Copies AM open order book and pastes it into master spreadsheet

Set startCell = ActiveSheet.Range("A1")
lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
ActiveSheet.Range(Cells(1, lastRow), Cells(1, lastColumn)).Select
Selection.Copy

2 个答案:

答案 0 :(得分:1)

如果要从A1到右下角的整个范围,请使用此

ActiveSheet.Range(Cells(1, 1), Cells(lastrow, lastColumn)).Copy

如果您只想使用最后一列

ActiveSheet.Range(Cells(1, lastColumn), Cells(lastrow, lastColumn)).Copy

Cells的语法是行然后列,您将它们混在一起。

此外,您无需Select即可进行复制。

很显然,单独复制不会做任何事情,然后需要粘贴到某个地方。

答案 1 :(得分:0)

您需要粘贴目标范围:

Option Explicit
Sub CopyPaste()

    Dim wsSource As Worksheet, wbDestination As Workbook, wsDestination As Worksheet, LastRow As Long, lastColumn As Long

    Set wbDestination = Workbooks.Open(Filename:=OOBmap, ReadOnly:=True)
    Set wsSource = ThisWorkbook.Sheets("Name") 'change Name for the name of the worksheet you are copying from
    Set wsDestination = wbDestination.Sheets("Name") 'change Name for the name of the worksheet you are copying to

'Copies AM open order book and pastes it into master spreadsheet
    With wsSource
        LastRow = .Cells(.Count, 1).End(xlUp).Row
        lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        .Range(Cells(1, LastRow), Cells(1, lastColumn)).Copy wsDestination.Range("A1") 'here the range were u want to paste
    End With

End Sub