简体   繁体   中英

Trying to copy a range from one sheet and paste it to the next empty cell in a column on another sheet

I am trying to copy a range from one sheet ("H2:H200") or can be Range("H2").End(xlDown) (neither of these works) and paste it to the next empty cell on another cell. (basically putting two columns under each other). I have the following code, but I get "Worksheet Object Failed" error. What am I doing wrong?

Sub Mergescript()
Dim ssaw_p As Worksheet
Dim oqs As Worksheet

Set ssaw_p = Sheets("SSAW_EXPORT")
Set oqs = Sheets("SQL_IMPORT")

ssaw_p.Range("H2:H200").Copy Destination:=oqs.Range("G").End(xlDown).Offset(1, 0)

End Sub
Sub Mergescript()
Dim ssaw_p As Worksheet
Dim oqs As Worksheet

Set ssaw_p = ThisWorkbook.Sheets("SSAW_EXPORT")
Set oqs = ThisWorkbook.Sheets("SQL_IMPORT")

With ssaw_p
    .Range("H2:H200").Copy Destination:=oqs.Range("G1").End(xlDown).Offset(1, 0)
End With

End Sub

this works

the oqs.range, is not correct try this :

ssaw_p.Range("H2:H200").Copy Destination:=oqs.Range("G1").End(xlDown).Offset(1, 0)

this will copy your ssaw range after the first empty cell in column G

To avoid trying to go off the end of the sheet (if nothing in G ) use the following.

Option Explicit

Sub Mergescript()
    Dim ssaw_p As Worksheet
    Dim oqs As Worksheet

    Set ssaw_p = Sheets("SSAW_EXPORT")
    Set oqs = Sheets("SQL_IMPORT")

    Dim lastRow As Long
    Dim nextRow As Long

    With oqs

      lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row

    End With

    If lastRow = 1 Then
        nextRow = 1
    Else
       nextRow = lastRow + 1
    End If

     ssaw_p.Range("H2:H200").Copy Destination:=oqs.Range("G" & nextRow)

End Sub

Try with

ssaw_p.Range("H2:H" & Range("H2").End(xlDown).Row).Copy oqs.Range("G" & oqs.Range("G2").End(xlDown).Row + 1)

This code will always copy all data in sheet EXPORT Range H2: to last cell in Column H and paste it into the first blank column found in column G on sheet IMPORT

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