Removing extra rows based on cell contents

JR1412

Board Regular
Joined
Jan 29, 2005
Messages
62
This is the macro that I have been using. Initially I had it just removing the rows if the cell was blank or zero. Since then I changed it to delete the row for other values.

Application.ScreenUpdating = False
Dim Rng As Range
Dim c As Range

Set Rng = Range("A9:A509")
For Each c In Rng
If c.Value = 0# Then
c.EntireRow.Delete xlShiftUp
End If
Next c

For Each c In Rng
If c.Value = "1" Then
c.EntireRow.Delete xlShiftUp
End If
Next c

For Each c In Rng
If c.Value = "BR1" Then
c.EntireRow.Delete xlShiftUp
End If
Next c


So two questions:

First, it does not remove all the rows the first time. If there are multiple rows with a cell containing BR1, it may remove the first six, but leave the last one or two. Running the macro once or twice more will remove these extra rows. Why is this occurring?

The second question, since the purpose has change, I would rather the macro remove all rows when the cells A9 through A509 contain a value other than PR1. Is there a quicker way than what I have above?

Thanks
 

Some videos you may like

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).

GaryAtWork

Board Regular
Joined
Dec 19, 2005
Messages
83
To answer the second question first, just using 1 loop your if statement could be...
If c.Value <> "PR1"

My guess at the first one, and it is a guess because I'm not sure exactly how For...Each works, is that say for example you are checking cell A100 and then remove it. The next check would now be on cell A101 but what was A101 is now A100 so the rows directly underneath rows that get deleted don't get checked.
I'd try taking 1 from c each time a row is deleted although I don't know if it's as simple as c=c-1 because c is a range.
 

Watch MrExcel Video

Forum statistics

Threads
1,118,327
Messages
5,571,560
Members
412,405
Latest member
DutchMonkey
Top