Macro to delete rows based on cell color

ultracyclist

Active Member
Joined
Oct 6, 2010
Messages
271
Office Version
  1. 365
Platform
  1. Windows
I created the following macro to delete all rows that have a cell background color of Yellow in Column D

Code:
Sub deleterow()
     Dim myRange as Range
     Dim cell As Range

     Application.Calculation = xlCalculationManual
     Set myRange = Worksheets(1).Range("D2:D1200") 
  For Each cell In myRange
        If cell.Interior.ColorIndex = 6 Then
          cell.EntireRow.Delete
        End If
     Next cell

     Application.Calculation = xlCalculationAutomatic
End Sub
</SPAN>


When I run the code some rows that are in Yellow do not get deleted.

Any thoughts?

Thanks,

Allen</SPAN>
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
You need to delete from bottom to top. Your code is using a For Each - Next loop which proceeds from top to bottom. Try:
Code:
For i = myRange.rows.count  to 1 Step -1
If myRange(i).Interior.ColorIndex = 6 then
myRange(i).EntireRow.Delete
End If
Next i
 
Upvote 0
Should I replace the following code

Code:
For Each cell In myRange
        If cell.Interior.ColorIndex = 6 Then
          cell.EntireRow.Delete
        End If
     Next cell

with

Code:
For i = myRange.rows.count  to 1 Step -1
If myRange(i).Interior.ColorIndex = 6 then
myRange(i).EntireRow.Delete
End If
Next I
 
Upvote 0
That's the idea. But Next I should be Next i as in my post.
 
Upvote 0
Thank you for the clarification. I tested the code and everything works as expected.

Thank you again for your help.

Regards,

Allen
 
Upvote 0

Forum statistics

Threads
1,215,459
Messages
6,124,948
Members
449,198
Latest member
MhammadishaqKhan

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