Loop & If & Delete row

UberFrank

Board Regular
Joined
Jul 8, 2010
Messages
51
Hey guys ive taken a secion out of my code as below

Code:
Sub FindFormat()
    
    Dim varMassRange As Range, varCell As Range
    Set varMassRange = Range("D2:D500")
    
    For Each varCell In varMassRange
    varCell.Select
    
    If Selection.Value = "Y" Then
    ActiveCell.EntireRow.Delete
    End If
        Next varCell
End Sub

Now, when there are to rows together both containing a Y the second is ignored and not deleted, i believe this is because the second row then takes on the old row number and excel acts as if it has already checked that cell. I have tryed adding a (-1,0) offset after the delete command but excel still skips to the next row.

Any ideas?

Thanks
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
I suggest and most user do when you are deleing row(s) starts to the last one upto the first.

Code:
For i = cells(rows.count, 2).end(xlup).row to 1 step -1
cells(i ,2).entirerow.delete
next i
 
Upvote 0
you could loop from the maxrow to minrow with step -1
Code:
Sub Delete_rows()
For i = 500 To 2 Step -1
If Cells(i, 4).Value = "Y" Then
Rows(i).Delete
End If
Next i
End Sub

this way after it deletes the 500th row, row 501 becomes row 500, but since it has already checked row 500, it wont check the row again

If you loop increasing order

After deleting row 2, row 3 will become row 2 and since it has already checked row 2(which is actually row 3), the macro would ignore it.
 
Upvote 0
Thanks guys i had been looking for a way to reverse the loop as suggested, this should resolve the issue.

Many thanks

Best regards
 
Upvote 0

Forum statistics

Threads
1,224,590
Messages
6,179,762
Members
452,940
Latest member
rootytrip

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