VBA - 将变量范围从一个工作表复制到另一个工作表

时间:2017-10-16 13:38:44

标签: excel vba excel-vba copy

我想将数据从表格“Inv_Headers”,C列,从第2行,直到最后一行,复制到第4行的“客户”,第U列。

Private Sub Invoice_C()
    Dim ws As Worksheet, ws1 As Worksheet
    Dim lastrow As Long

    Set ws = Worksheets("Inv_Headers")
    Set ws2 = Worksheets("CUSTOMERS")


        lastrow = ws.Cells(Rows.Count, 3).End(xlUp).Row ' last row in column C
        ws.Range("C2:C" & lastrow).Copy
        ws1.Range("U4").PasteSpecial xlPasteValues
        ws1.Activate


End Sub

我的代码给了我错误信息'91' - 对象变量或没有设置块变量。但代码应该在没有With语句的情况下工作,不应该吗?

我可以请你提出建议吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

基于来自@Absinthe的支票,我已经纠正了错字,这里是正确的代码:

Private Sub Invoice_C()
    Dim ws As Worksheet, ws1 As Worksheet
    Dim lastrow As Long

    Set ws = Worksheets("Inv_Headers")
    Set ws1 = Worksheets("CUSTOMERS")


        lastrow = ws.Cells(Rows.Count, 3).End(xlUp).Row ' last row in column C
        ws.Range("C2:C" & lastrow).Copy
        ws1.Range("U4").PasteSpecial xlPasteValues
        ws1.Activate


End Sub

答案 1 :(得分:0)

除了Srpic的产品,我还记得没有让这部分工作: ws.Range("C2:C" & lastrow).Copy

您可以使用ws.Range("C2", "C" & lastrow).Copy

进行修复

如果您开始输入Range(),您会看到,是可接受的分隔符,而:则表示不完整的范围分配。

Private Sub Invoice_C()
Dim ws As Worksheet, ws1 As Worksheet
Dim lastrow As Long

Set ws = Worksheets("Inv_Headers")
Set ws1 = Worksheets("CUSTOMERS")


    lastrow = ws.Cells(Rows.Count, 3).End(xlUp).Row ' last row in column C
    ws.Range("C2", "C" & lastrow).Copy
    ws1.Range("U4").PasteSpecial xlPasteValues
    ws1.Activate

End Sub