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

When did Power Query debut in Excel?
Although it was an add-in in Excel 2010 & Excel 2013, Power Query became a part of Excel in 2016, in Data, Get & Transform Data.
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,223,238
Messages
6,170,939
Members
452,368
Latest member
jayp2104

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