简体   繁体   中英

Copy and Paste Dynamic Range from One Worksheet to Another

I am attempting to copy column A starting in row 2 on "Sheet1" and paste it in Column C on sheet "ABC" starting at row 5. The number of rows in Column A is variable so I cannot use a fixed range.

The code below does what I need, but I am trying to avoid using .Select and .Activate

LastRow = Range("A" & Rows.Count).End(xlUp).Row
Sheets("Sheet1").Range("A2:A" & LastRow).Copy
Sheets("ABC").Activate
Sheets("ABC").Range("C5:C" & LastRow).Select
Selection.PasteSpecial xlPasteValues

I tried setting the columns equal to one another using this code:

  Sheets("ABC").Range("C5").End(xlDown).Value=Sheets("Sheet1").Range("A2:A" & LastRow).Value

This runs without error but it "does nothing" -- No data appears on worksheet "ABC"

I also tried to following:

    Dim WS As Worksheet
    Dim wsABC As worksheet


    Set WS = Sheets("Sheet1")
    Set wsABC = Sheets("ABC")
    LastRow = Range("A" & Rows.Count).End(xlUp).Row

    WS.Range("A2:A" & LastRow).Copy
    wsABC.Range("C5").End(xlDown).Paste

This produces a "Run-time error #438 Object doesn't support this property or method" Error on this line:

 wsABC.Range("C5").End(xlDown).Paste

Another method I tried was as follows:

Dim WS As Worksheet

    Set WS = Sheets("Sheet1")
    Set wsABC = Sheets("ABC")


  With WS
  LastRow = Range("A" & Rows.Count).End(xlUp).Row
  WS.Range("A2:A" & LastRow).value = wsABC.Range("C5:C & LastRow").Value

End With

This produces a "Run-time error '1004' Application-defined or object defined error.

I am open to corrections / comments on any of my attempts, I just want to avoid using .Select and .Activate.

Thank you in advance for your time and assistance!

Coding styles can vary greatly. Here's one way to do what you're looking for:

Sub tgr()

    Dim wb As Workbook
    Dim wsData As Worksheet
    Dim wsDest As Worksheet

    Set wb = ActiveWorkbook
    Set wsData = wb.Sheets("Sheet1")
    Set wsDest = wb.Sheets("ABC")

    With wsData.Range("A2", wsData.Cells(wsData.Rows.Count, "A").End(xlUp))
        wsDest.Range("C5").Resize(.Rows.Count).Value = .Value
    End With

End Sub
With Worksheets("Sheet 1")
    With .Range("A2", .Cells(.Rows.Count, 1).End(xlUp))
        Worksheets("ABC").Range("C5").Resize(.Rows.Count).Value = .Value
    End With
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM