Delete rows that doe not match

mecerrato

Board Regular
Joined
Oct 5, 2015
Messages
184
Office Version
  1. 365
Platform
  1. Windows
I have this code that I modified from another user on this forum and retrofitted for my need. However, although it works perfectly the first time, every time I re-run it it keeps deleting one additional row when it should not delete any as the first time it was run it removed all rows that matched my criteria.

Can someone help me tweak this code?

VBA Code:
Sub DelAllButAlvaro()

For j = 1 To 1
With Sheets("Pipeline")
    .AutoFilterMode = False
    .Range("$a$11:$cq$500").AutoFilter Field:=2, Criteria1:="<>" & "Alvaro Molinares"
    .Range("B11:B" & .Cells(Rows.Count, "B").End(xlUp).Row).EntireRow.Delete
End With

Next j
Call Show_Realdeals
End Sub
 

Excel Facts

Repeat Last Command
Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.
A few things.

This line serves no purpose in your code:
VBA Code:
For j = 1 To 1

That is telling your loop to run exactly once, which is what would happen without the loop!

The issue is if you have no matching entries, you are still telling it to delete row 11!
So you need to check/confirm you have entries to delete.
I am not sure if you have headers in your data, and what row they are on (10 or 11), but you need to do something like this:
VBA Code:
Sub DelAllButAlvaro()

Dim lr As Long

With Sheets("Pipeline")
    .AutoFilterMode = False
    .Range("$a$11:$cq$500").AutoFilter Field:=2, Criteria1:="<>" & "Alvaro Molinares"
    lr = .Cells(.Rows.Count, "B").End(xlUp).Row
    If (lr > 11) Or (Range("B11") <> "Alvaro Molinares") Then .Range("B11:B" & lr).EntireRow.Delete
End With

Call Show_Realdeals

End Sub
The code may have to change slightly depending on if and where you have headers.
 
Upvote 0

Forum statistics

Threads
1,223,886
Messages
6,175,195
Members
452,616
Latest member
intern444

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