使用VBA从现有数据向下偏移目标数据

时间:2017-09-19 19:17:26

标签: excel-vba vba excel

我正在尝试将数据从一个工作簿复制到另一个工作簿。我已经可以这样做,但我无法将数据偏移到某些行。我的代码的最后一部分是我的问题所在。

Sub T1()
Dim sourceTitle As Range, targetTitle As Range

Set sourceTitle = Workbooks("Data to Copy.xlsm").Worksheets(2).Columns("B")
Set targetTitle = Workbooks("Data 
Destination.xlsm").Worksheets(1).Columns("A")

sourceTitle.Copy Destination:=targetTitle.Cells(Rows.Count, 1).End(xlUp).Offset(2, 0)
End Sub

1 个答案:

答案 0 :(得分:2)

编写的代码尝试将整列数据复制到少于整列的数据范围内,这将超出Excel中的行限制。

很少需要复制整个列(如果是,则转移到数据库解决方案)。

试试这个:

Sub T1()


    Dim wsSource as Worksheet, wsTitle as Worksheet
    Set wsSource = Workbooks("Data to Copy.xlsm").Worksheets(2)
    Set wsTarget = Workbooks("Data Destination.xlsm").Worksheets(1)

    Dim sourceTitle as Range
    Set sourceTitle = wsSource.Range(wsSource.Range("B1"),wsSource.Cells(Rows.Count,2).End(xlUp))

    sourceTitle.Copy Destination:=wsTarget.Cells(Rows.Count,1).End(xlUp).Offset(2)

End Sub