Reputation: 79
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:
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
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
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