VBA - Copy variable range from one sheet to another

偶尔善良 提交于 2019-12-11 17:07:42

问题


I would like to copy data from a sheet "Inv_Headers", Column C, from 2nd row until the last row to a sheet "Customers", Column U, from 4th row.

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

My code is giving me error msg '91' - Object variable or With block variable not set. But the code should work without With statement as well, shouldn't it?

Could I ask you for your advices, please?

Many thanks!


回答1:


Based on check from @Absinthe, I've corrected the typo and here is the correct code:

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



回答2:


In addition to Srpic's offering, I can remember not getting this part to work: ws.Range("C2:C" & lastrow).Copy

you can fix it with ws.Range("C2", "C" & lastrow).Copy

If you start typing in Range() you will see that , is an acceptable separator, whereas : for an incomplete range assingment is not.

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



来源:https://stackoverflow.com/questions/46771730/vba-copy-variable-range-from-one-sheet-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!