1

I want to delete rows from Excel if Column A contains "string1" as shown in the following table:

A1 B1
string1 string2 string3 string4
string5 string6 string7 string8

I'm using the below code:

 Sub DeleteRows()

    Dim rng As Range
    Dim pos As Integer
    Set rng = ActiveSheet.UsedRange
    
    For i = rng.Cells.Count To 1 Step -1
        pos = InStr(LCase(rng.Item(i).Value), LCase("string1"))
        If pos > 0 Then
            rng.Item(i).EntireRow.Delete
        End If
    Next i
End Sub

The problem is that if the Column A contains "string11" not "string1" it's also deleting the row. Any advice, please? Thanks

mg g
  • 21
  • 4

3 Answers3

3

With Split() (tested; not optimized):

Sub DeleteRows()
    Dim rng As Range
    Set rng = ActiveSheet.UsedRange
    
    For i = rng.Cells.Count To 1 Step -1
        For Each w In Split(LCase(rng(i).Value))
            If w = "string1" Then
                rng(i).EntireRow.Delete
                Exit For
            End If
        Next
    Next i
End Sub

Edit 2

Sub DeleteRows()
    Dim rng As Range, i As Long, w, arr
    arr = Array("string1", "string2", "string3")
    Set rng = ActiveSheet.UsedRange
    
    For i = rng.Cells.Count To 1 Step -1
        For Each w In Split(LCase(rng(i).Value))
            If IsNumeric(Application.Match(w, arr, 0)) Then
                rng(i).EntireRow.Delete
                Exit For
            End If
        Next
    Next i
End Sub
Алексей Р
  • 7,507
  • 2
  • 7
  • 18
1

Try combining the "found in string" with "string is same length". Like this:

Sub DeleteRows()

   Dim rng As Range
   Set rng = ActiveSheet.UsedRange
   
   For i = rng.Cells.Count To 1 Step -1
       pos = InStr(LCase(rng.Item(i).Value), LCase("delete"))
       If pos > 0 And (Len(rng.Item(i).Value) = Len(Lcase("delete"))) Then
           rng.Item(i).EntireRow.Delete
       End If
   Next i
End Sub

Or if you wanted to compare the entire cell contents you could just simplify it to:

Sub DeleteRows()

   Dim rng As Range
   Dim pos As Integer
   Set rng = ActiveSheet.UsedRange
   
   For i = rng.Cells.Count To 1 Step -1
       If LCase(rng.Item(i).Value) = LCase("delete") Then rng.Item(i).EntireRow.Delete
   Next i
End Sub
ed2
  • 1,457
  • 1
  • 9
  • 26
  • Why not simply use `=` or `StrComp` instead of `InStr`? – FunThomas Aug 05 '21 at 13:43
  • Because original solution (retained) was created with minimal changes to the OP's original code. Also now edited to add a simpler solution for if the OP wants to compare to entire cell contents instead of a word. – ed2 Aug 05 '21 at 13:57
0

You don't need the pos variable, just compare the values in If statement!

Sub DeleteRows()

    Dim rng As Range
    Dim pos As Integer
    Set rng = ActiveSheet.UsedRange
    
    For i = rng.Cells.Count To 1 Step -1
        If rng.Item(i).Value = "delete" Then
            rng.Item(i).EntireRow.Delete
        End If
    Next i
End Sub
Dominique
  • 16,450
  • 15
  • 56
  • 112