Search code examples
excelvbacopy-paste

VBA Paste Value into new sheet below last row


I want to paste the rows of one sheet into another sheet (below the last used row) if the cell value in column 30 of a row is equal to 1.

I can do this with a regular paste but I have been unable to paste values. Every time i edit

Worksheets("ARF Data Table").Cells(b + 1, 1).Select
ActiveSheet.Paste

to

Worksheets("ARF Data Table").Cells(b + 1, 1).Select
ActiveSheet.PasteSpecial xlPasteValues

I get the error

Run-time error '1004': PasteSpecial Method of worksheet class failed.

I think I need to create a range for the paste special method to paste into, but I don't know how to do this as the range begins on the row after the last row with previously pasted data on it. Apologies if there is a thread already explaining this.

The code I'm using is below.

Sub MoveCopyRowsColumns()

a = Worksheets("ARF Form Working Data").Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To a

If Worksheets("ARF Form Working Data").Cells(i, 30).Value = 1 Then

Worksheets("ARF Form Working Data").Rows(i).Copy
Worksheets("ARF Data Table").Activate
b = Worksheets("ARF Data Table").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("ARF Data Table").Cells(b + 1, 1).Select
ActiveSheet.PasteSpecial xlPasteValues
Worksheets("ARF Form Working Data").Activate

End If
Next

Application.CutCopyMode = False

ThisWorkbook.Worksheets("ARF Form Working Data").Cells(b, 1).Select
End Sub

Solution

  • Try a direct value transfer.

    option explicit
    
    Sub MoveCopyRowsColumns()
    
        dim b as long
    
        with Worksheets("ARF Form Working Data")
    
            For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
    
                If .Cells(i, 30).Value = 1 Then
                    with .range(.cells(i, "A"), .cells(i, .columns.count).end(xltoleft))
                        b = Worksheets("ARF Data Table").Cells(Rows.Count, 1).End(xlUp).Row
                        Worksheets("ARF Data Table").Cells(b + 1, 1).resize(.rows.count, .columns.count) = .value
                    end with
                end if
    
            next i
    
        end with
    
    End Sub
    

    Or Range.PasteSpecial xlPasteValues into the destination cell, not the parent worksheet.

    option explicit
    
    Sub MoveCopyRowsColumns()
    
        dim b as long
    
        with Worksheets("ARF Form Working Data")
    
            For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
    
                If .Cells(i, 30).Value = 1 Then
                    b = Worksheets("ARF Data Table").Cells(Rows.Count, 1).End(xlUp).Row
                    .range(.cells(i, "A"), .cells(i, .columns.count).end(xltoleft)).copy
                    Worksheets("ARF Data Table").Cells(b + 1, "A").PasteSpecial paste:=xlPasteValues
                    end with
                end if
    
            next i
    
        end with
    
    End Sub