Search code examples
excelvba

Copy Range and Paste to Another Sheet if Condition is Met


My source Sheet1 has columns A to V. My conditions are in column U.

I'm trying to copy and paste the data from row A2 and from columns A to P only if under column U, the text "Manual" is found.

In the below code everything is being copied to Sheet2 and not just the rows that contain the text "Manual".

Also, how do I add another If condition, to copy and paste rows from columns A to P that has the text "Auto" to Sheet3?

Private Sub CommandButton1_Click()

Sheets("Paste Data").Select

LR = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
For i = 2 To LR
    If Sheets("Paste Data").Cells(i, 21).Value = "Manual" Then
        Sheets("Paste Data").Range("A2:P" & LR).Rows(i).Copy
        Sheets("Sheet2").Activate
        Sheets("Sheet2").Range("A2").Select
        ActiveSheet.Paste
        Columns("A:P").AutoFit
    End If
Next

Application.CutCopyMode = False

Sheets("Paste Data").Activate
Sheets("Paste Data").Cells(1.1).Select

End Sub

Solution

  • As stated above, try to avoid using Select, Activate and ActiveSheet.

    The modified code below will copy columns "A:P" only if "<anual" is found in column U of each row.

    Private Sub CommandButton1_Click()
    
    With Sheets("Paste Data")
    
        LR = .Cells.Find("*", .Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
        For i = 2 To LR
            If .Range("U" & i).Value = "Manual" Then
                .Range("A" & i & ":P" & i).Copy Sheets("Sheet2").Range("A" & i)
            End If
        Next i
        
    End With
    
    Application.CutCopyMode = False    
    
    End Sub
    

    Note: if you only need to copy the values without the cell's formatting, a quicker way will be:

    Sheets("Sheet2").Range("A" & i & ":P" & i).Value = .Range("A" & i & ":P" & i).Value