首页 > 解决方案 > VBA 将动态范围从一个工作表复制/粘贴到另一个工作表

问题描述

我正在尝试从wsCL2Column中复制数据,A从单元格开始A2到数据结束时;行数可以变化。

我想从该列中的下一个空单元格粘贴到A,coSummary列中。

Sub Test()
    Dim wb As Workbook
    Dim wsCL2 As Worksheet
    Dim summary As Worksheet
    Dim colLastRow As Long
    Dim summaryLastRow As Long

    Set wb = ActiveWorkbook
    Set wsCL2 = wb.Sheets("Tocopyfrom")
    Set summary = wb.Sheets("Summary")

    'Defining last row of data in Colliers
    summaryLastRow = summary.Cells(Rows.Count, 1).End(xlUp).Row
    colLastRow = wsCL2.Cells(Rows.Count, 1).End(xlUp).Row

    summary.Cells(10, 10).Value = colLastRow
    summary.Cells(11, 10).Value = summaryLastRow

    'Copying range from Colliers to Summary Page  (***ERROR HERE***)
    wsCL2.Range(Cells(2, "A").Address(), Cells(colLastRow, "A")) _
        .Copy summary.Cells(summaryLastRow + 1, "A")

    colLastRow = summary.Cells(Rows.Count, 1).End(xlUp).Row
End Sub

尝试该Copy方法时有时会抛出错误;其他时候它会正确执行。

我怀疑这与刷新 value 的summaryLastRow值或与D

谢谢!

标签: vbaexcelcopy-paste

解决方案


您在这行代码中遇到问题:

wsCL2.Range(Cells(2, "A").Address(), Cells(colLastRow, "A")).Copy summary.Cells(summaryLastRow + 1, "A")

您使用了很多“单元”,它们不引用 wsCL2 而是引用您的 ActiveSheet,这可能不是您想要的。这是正确的方法:

wsCL2.Range(wsCL2.Cells(2, "A").Address(), wsCL2.Cells(colLastRow, "A")).Copy summary.Cells(summaryLastRow + 1, "A")

为了更好地理解,这就是您的代码实际所说的:

wsCL2.Range(ActiveSheet.Cells(2, "A").Address(), ActiveSheet.Cells(colLastRow, "A")).Copy summary.Cells(summaryLastRow + 1, "A")

编辑:我也不确定你如何使用这些引用一次 .Address: Cells(2, "A").Address() 和下一个没有: Cells(colLastRow, "A") 更好的方法我认为参考范围是仅使用数字:

wsCL2.Range( wsCL2.Cells(2,1), wsCL2.Cells(colLastRow,1) )

最终编辑: 另一件事,如果您厌倦了编写 wsCL2。

with wsCl2
  .Range( .Cells(2,1), .Cells(colLastRow,1) )
end with

推荐阅读