简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM