0

I am trying to loop through an array and, when it finds a cell which is not equal a specific value, it deletes the entire row. Here is the code:

Sub DeleteTest()

Dim crr()

crr = Range("A3:A1000")

For i = LBound(crr, 1) To UBound(crr, 1)
    If (crr(i, 1) <> "One" And crr(i, 1) <> "Two") Then
       ' Line to delete the row in which the value of the cell is not One or Two

    End If
Next

End Sub

I know I can also do it with an Autofilter, but I would like to know the way to do it with the array.

1
  • Create a union of the row numbers then delete all the rows at once after the loop. Commented Apr 4, 2020 at 21:03

2 Answers 2

1

Here's one way:

Sub DeleteTest()

    Dim rng As Range, crr(), i As Long

    Set rng = Range("A3:A1000")
    crr = rng.Value

    For i = UBound(crr, 1) To LBound(crr, 1) Step -1 '<<< loop backwards
        If (crr(i, 1) <> "One" And crr(i, 1) <> "Two") Then
           rng.Cells(i).EntireRow.Delete
        End If
    Next

End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! The code worked. What would be the reason to loop backwards? Is it the same as introducing "For i = LBound(crr, 1) To UBound(crr, 1)"?
If you start by deleting row 1, then where does row 2 go?
0

Try this code

Sub Test()
Dim x, r As Range
With ThisWorkbook.Sheets("Sheet1")
    Set r = .Range("A3:A1000")
    x = Filter(.Evaluate("TRANSPOSE(IF((" & r.Address & "=""One"")+(" & r.Address & "=""Two""),""A"" & ROW(" & r.Address & ")))"), False, False)
    If UBound(x) = -1 Then Exit Sub
    .Range(Join(x, ",")).EntireRow.Hidden = True
    On Error Resume Next
        r.SpecialCells(xlCellTypeVisible).EntireRow.Delete
    On Error GoTo 0
    .Rows.Hidden = False
End With
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.