For each skipping rows

Luke777

Board Regular
Joined
Aug 10, 2020
Messages
246
Office Version
  1. 365
Platform
  1. Windows
Hi all,

I'm using the following code to delete rows.

VBA Code:
For Each cell in sTasks.Range("C3:C" & sRange)
If cell.value = "Completed" then cell.entirerow.delete
next

In practice the range is something like C3:C50, but my problem is that only every other row is being delete. I understand why, because the row gets delete, next row moves up so 15 becomes 14 and gets skipped assuming it is also "complete".

So I understand what's going on, but I don't know what the best way to fix it is... maybe store the ranges to be deleted and do them all at once? or is there a way of telling the For Each to go back a step? Like the opposite of Next?

Thanks
 

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.
The best way to do this is to loop through the rows backwards. You can do that like this:
VBA Code:
Dim lr as Long, r as Long

'Find last row in column C with data
lr = sTasks.Cells(sTasks.Rows.Count, "C").End(xlUp).Row

'Loop through rows backwards
For r = lr to 3 Step -1
   If sTasks.Cells(r, "C").Value = "Completed" then sTasks.Cells(r, "C").EntireRow.Delete
next
 
Upvote 0

Forum statistics

Threads
1,215,095
Messages
6,123,073
Members
449,093
Latest member
ripvw

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