Delete row based on criteria - Whats wrong in my macro?

ORoxo

Board Regular
Joined
Oct 30, 2016
Messages
149
Hello, everyone,
I am trying to create a macro which is supposed to delete every line which contains the number 5 in column B and I'm almost there - or at least, that's what I think.

This is what I have to far:

Code:
Sub brincar()
Dim r As Integer, c As Integer, lc As Integer, lr As Integer


For r = 2 To 9


    If Cells(r, 2) = 5 Then


        ActiveCell.EntireRow.Delete
    
    End If


Next


End Sub

Nonetheless, this code has a problem. Let's say I have titles on row 1 and then both row 2 and 3 have a 5 in column B. The macro would delete the second row so the 5 which was previously in column 3 would go to column 3. However, the For...next would then follow to row 3 ignoring the 5 in row 2.

This might be a bit confusing, but do you understand the problem? How can I write the code so it goes through until the last row which has data and deletes the ones with a 5 in column B?

Thanks,
ORoxo
 
Last edited:

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.
You need to loop in reverse like
Code:
Sub brincar()
Dim r As Integer, c As Integer, lc As Integer, lr As Integer


For r = 9 To 2 Step -1


    If Cells(r, 2) = 5 Then


        Rows(r).Delete
    
    End If


Next r


End Sub
 
Upvote 0
You need to loop in reverse like
Code:
Sub brincar()
Dim r As Integer, c As Integer, lc As Integer, lr As Integer


For r = 9 To 2 Step -1


    If Cells(r, 2) = 5 Then


        Rows(r).Delete
    
    End If


Next r


End Sub

CoordinatedSomberDouglasfirbarkbeetle.gif


Didn't think about this. Thank you so much, Fluff!!
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,599
Messages
6,120,453
Members
448,967
Latest member
grijken

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