Home » excel » excel – Copy argument does not work with Range object

excel – Copy argument does not work with Range object

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to copy a table and paste it somewhere else (the target cell selected by the user) on the sheet:

enter image description here

But I get an error on the table.copy part:

Wrong number of arguments or invalid property assignment

   Sub PasteMacro()
     Dim target As Variant
     Dim i As Long
     Dim table As Range
     Dim weight As Double
     Dim thickness As Double
     Dim Stiff As Double

     Set shA = ActiveWorkbook.Worksheets("User sheet comp data")

     ' searh for the first non 0 ligne in the table

     i = 19
     Do Until Range("M" & i) <> 0
     i = i - 1
     Loop

     MsgBox Cells(i, 13).Address

     'the table to copy
     Set table = shA.Range(Cells(1, 2), Cells(i, 15))

     weight = shA.Range("O20")
     thickness = shA.Range("M20")
     Stiff = shA.Range("M21")


     On Error Resume Next
    ' ask the user to select the cell to paste table
    Set target = Application.InputBox(Prompt:="Please select a destination Cell where you want to 
    paste", Type:=8)

    On Error GoTo 0

    If Not answ Is Nothing Then
    'copy the table and paste it
    table.Copy , shA.target
    End If

  End Sub
How to&Answers:
table.Copy , shA.target

should be
:

table.Copy target

since:

  • the Destination parameter is the first one of the Copy() method, while commas are needed to delimit subsequent (if any) parameters

  • target is a Range object, hence it’s already fully qualifed up to its parent sheet and workbook object

Furthermore, I guess

If Not answ Is Nothing Then

should be
:

If Not Target Is Nothing Then

so here’s the revised code

Sub PasteMacro()

    Dim target As Range
    Dim table As Range
    Dim i As Long
    Dim weight As Double
    Dim thickness As Double
    Dim Stiff As Double

    Dim shA As Worksheet

    With ActiveWorkbook.Worksheets("User sheet comp data")

        ' search for the first non 0 ligne in the table
        i = 19
        Do Until .Range("M" & i) <> 0
            i = i - 1
        Loop

        MsgBox .Cells(i, 13).Address

        'the table to copy
        Set table = .Range(Cells(1, 2), Cells(i, 15))

        weight = .Range("O20").Value2
        thickness = .Range("M20").Value2
        Stiff = .Range("M21").Value2


        On Error Resume Next
        Set target = Application.InputBox(Prompt:="Please select a destination Cell where you want to Paste ", Type:=8)
        On Error GoTo 0

        If Not target Is Nothing Then table.Copy target  'copy the table and paste it

    End With

End Sub

As you can see all range objects (Range, Cells) are referencing ActiveWorkbook.Worksheets("User sheet comp data")
("MilestoneDueDate")
through that dot (.) in front of them

this way you are sue you’r not loosing control over what range is being considered in what sheet