Abhishek Singh
Abhishek Singh

Reputation: 79

VBA script to search for a string in a column and delete an entire row containing that string?

I have some 100 rows with some 10 columns.I want to delete the entire row if the cell in column B(or 2) contains a specific string "XYZ" (say)

The below code works perfect if the string is present in the beginning. But I want it to work for below cases as well:

  1. "XYZadjsaoda" (Case 1: Beginning of the string)
  2. "asdsalXYZasdsa" (Case 2: Middle of the string )
  3. "dsadsad32XYZ" (Case 3: End of the string)

If the string is present it should delete the entire row.

Sub DeleteRowBasedOnCriteria()
    Dim RowToTest As Long
    Sheets("Jira").Select
    For RowToTest = Cells(Rows.Count, 2).End(xlUp).Row To 2 Step -1
        With Cells(RowToTest, 2)
            If .Value = "XYZ" _        
            Then _
            Rows(RowToTest).EntireRow.Delete
        End With
    Next RowToTest
End Sub

The function should match XYZ irrespective of the location inside a cell and delete entire row.

Upvotes: 0

Views: 845

Answers (2)

Pᴇʜ
Pᴇʜ

Reputation: 57683

Alternatively to the Like operator you can use the InStr function:

If InStr(1, "XYZ", .Value, vbTextCompare) > 0 Then

You can use …

  • vbTextCompare to make it not case sensitive.
  • vbBinaryCompare to make it case sensitive.

Upvotes: 3

SJR
SJR

Reputation: 23081

Use the Like operator with wildcards (possibly with a case qualification too).

AutoFilter might be a better option though.

Sub DeleteRowBasedOnCriteria()
Dim RowToTest As Long
Sheets("Jira").Select
For RowToTest = Cells(Rows.Count, 2).End(xlUp).Row To 2 Step -1
    With Cells(RowToTest, 2)
        If .Value Like "*XYZ*" Then Rows(RowToTest).EntireRow.Delete
        'If ucase(.Value) Like "*XYZ*" Then Rows(RowToTest).EntireRow.Delete  CASE INSENSITIVE 
    End With
Next RowToTest
End Sub

Upvotes: 3

Related Questions