Search code examples
vbaexcelcopy-paste

Excel: How to copy a row if it contains certain text to another worksheet (VBA)


I'm looking to use a marco that would be able to search a column in said sheet and if certain text is found - in my case the word "FAIL" - copy that entire rows data/formatting and paste it into another sheet - sheet 4 in my case - along with any other rows that contained that specific text.

pic1 pic2

i have been using this code but it only copy pastes one row then stops rather than going through and copying any rows with "FAIL"

Sub Test()
For Each Cell In Sheets(1).Range("H:H")
  If Cell.Value = "FAIL" Then
    matchRow = Cell.Row
    Rows(matchRow & ":" & matchRow).Select
    Rows(matchRow & ":" & matchRow).Select
    Selection.Copy

    Sheets(4).Select
    ActiveSheet.Rows(matchRow).Select
    ActiveSheet.Paste
    Sheets(4).Select
   End If
Next 
End Sub

First post and brand new to VBA so apologies if too vague.


Solution

  • Try the code below (explanation inside the code as comments):

    Option Explicit
    
    Sub Test()
    
    Dim Cell As Range
    
    With Sheets(1)
        ' loop column H untill last cell with value (not entire column)
        For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
            If Cell.Value = "FAIL" Then
                 ' Copy>>Paste in 1-line (no need to use Select)
                .Rows(Cell.Row).Copy Destination:=Sheets(4).Rows(Cell.Row)
            End If
        Next Cell
    End With
    
    End Sub