VBA logic issue with deleting certain rows

sirN

Board Regular
Joined
Jul 20, 2010
Messages
64
Howdy,

I'm running a module to format some data and have run into an issue with my logic. The piece that's giving me trouble is looping though a sheet, row by row and checking for a 0 balance. If it finds a 0 (in cell "G" & row), then it deletes the entire row. The problem is I have adjacent rows with 0 balances, so when my loop deletes one row, the other one shifts up, but my counter (row) moves forward one. So it misses the adjacent 0. I'm sure you fine folks probably have a fix for this. Help. thanks (as always).

Code:
'delete zero qty rows
    mylastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
        
        For R = 2 To mylastrow
        Range("G" & R).Select
        If Range("G" & R) = "0" Then Rows(R).EntireRow.Delete
        Next R
 

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
When deleting rows you need to loop backwards, otherwise some may be missed:

Code:
For R = mylastrow To 2 Step -1
 
Upvote 0
You need to work backwards when deleting...

Code:
For R = mylastrow To 2 Step -1
    If Range("G" & R) = "0" Then Rows(R).EntireRow.Delete
Next R
 
Upvote 0

Forum statistics

Threads
1,213,522
Messages
6,114,112
Members
448,549
Latest member
brianhfield

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