1
votes

I am trying to copy data from my 'main' sheet and then paste it into my 'csv' sheet. However, I get a run-time error "'1004': PasteSpecial method of Range class failed" when I try this.

Please review my code below. It is the '.Cells(1, 2).PasteSpecial xlPasteValues' that bugs out. Thanks.

    With main
        n = 1

        For Each c In .Range("C1:C200")
            If c.Value = "x" Then
                c1 = Cells(c.Row, Columns.Count).End(xlToLeft).Column
                If c1 > 2 Then c.Offset(0, 2).Resize(, c1 - 4).Copy

                With csv
                    If n = 1 Then
                        .Cells(1, 1) = "ID"
                        .Cells(1, 2).PasteSpecial xlPasteValues
                    Else
                        .Cells(n, 1) = n - 1
                        .Cells(n, 2).PasteSpecial xlPasteValues
                    End If
                End With

                n = n + 1
            End If
        Next c
    End With
1

1 Answers

1
votes

Put the Copy and the paste in the same condition:

If c1 > 2 Then 
    c.Offset(0, 2).Resize(, c1 - 4).Copy
    With csv
        If n = 1 Then
            .Cells(1, 1) = "ID"
            .Cells(1, 2).PasteSpecial xlPasteValues
        Else
            .Cells(n, 1) = n - 1
            .Cells(n, 2).PasteSpecial xlPasteValues
        End If
    End With
End If

And change this line:

c1 = Cells(c.Row, Columns.Count).End(xlToLeft).Column

to exactly this (dots are important):

c1 = .Cells(c.Row, .Columns.Count).End(xlToLeft).Column