Search code examples
excelvbarangecopy-paste

Copy a row from one sheet to another sheet if the row contains certain values based on a range of numbers


I would like to copy and paste a row if the row contains a certain value. HOWEVER, I have approx. 2500 values out of 100.000 that I need to obtain (copy and paste into separate rows). Thus, is there any possibility to create a VBA that allows me to create a loop or some sort, where I can specify these values?

E.g. instead of

For Each cell In Sheets(1).Range("A:A")
If cell.Value = "1" Then
    matchRow = cell.Row
    Rows(matchRow & ":" & matchRow).Select
    Selection.Copy

    Sheets("Sheet2").Select
    ActiveSheet.Rows(matchRow).Select
    ActiveSheet.Paste
    Sheets("Sheet1").Select
End If

I NEED:

For Each cell In Sheets(1).Range("A:A")
If cell.Value = "1 OR 3 OR 5 OR 10 OR 15, etc." Then
    matchRow = cell.Row
    Rows(matchRow & ":" & matchRow).Select
    Selection.Copy

    Sheets("Sheet2").Select
    ActiveSheet.Rows(matchRow).Select
    ActiveSheet.Paste
    Sheets("Sheet1").Select
End If

I am new to VBA and any help would be greatly appreciated...

Best,

Lisa


Solution

  • Use Select Case:

    For Each cell In Sheets(1).Range("A:A")
    Select Case cell.Value 
      Case "1","3","5","10","15"
        matchRow = cell.Row
        Sheets("Sheet1").Rows(matchRow).Copy  Sheets("Sheet2").Rows(matchRow)
    End Select