VBA to delete rows where text is not present

Regular7

New Member
Joined
Oct 2, 2018
Messages
4
Hi,

I am pulling my hair out over this one. I basically want a macro to delete all the rows where 'Fox' appears in a cell (i.e IF Fox exists in the text in Column B, or Column C, or Column D, then delete the entire row. The number of rows will be variable. I can't work out how to use ifs in vba without getting a 'if without block if' error (this is a bit beyond my ability).

The example file is attached. Many thanks in advance.

 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Your title reads "VBA to delete rows where text is not present " but your question wants to delete rows where the text is present.

this will delete the rows that the text is present.

Code:
Sub SelectA1()
    Dim FrstRng As Range
    Dim UnionRng As Range
    Dim c As Range
    Set FrstRng = Range("B1:D" & Cells(Rows.Count, "D").End(xlUp).Row)

    For Each c In FrstRng.Cells
        If InStr(1, c.Text, "fox", vbTextCompare) > 0 Then
            If Not UnionRng Is Nothing Then
                Set UnionRng = Union(UnionRng, c)    'adds to the range
            Else
                Set UnionRng = c
            End If
        End If
    Next c

    UnionRng.EntireRow.Delete
End Sub
 
Upvote 0
Give this macro a try...
Code:
[table="width: 500"]
[tr]
	[td]Sub DeleteRowsContainFox()
  With ActiveSheet.UsedRange
    .Replace "*Fox*", "#N/A", xlWhole, , False, , False, False
    On Error GoTo NoFoxes
    Intersect(.EntireColumn, .SpecialCells(xlConstants, xlErrors).EntireRow).Delete
  End With
NoFoxes:
End Sub[/td]
[/tr]
[/table]
 
Upvote 0

Forum statistics

Threads
1,224,827
Messages
6,181,198
Members
453,022
Latest member
RobertV1609

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top