Alternating coloring groups of rows in Excel

calendar_today Asked Aug 25, 2008
thumb_up 29 upvotes
history Updated April 16, 2026

Question posted 2008 · +9 upvotes

I have an Excel Spreadsheet like this

id | data for id
   | more data for id
id | data for id
id | data for id
   | more data for id
   | even more data for id
id | data for id
   | more data for id
id | data for id
id | data for id
   | more data for id

Now I want to group the data of one id by alternating the background color of the rows

var color = white
for each row
    if the first cell is not empty and color is white
        set color to green
    if the first cell is not empty and color is green
        set color to white
    set background of row to color

Can anyone help me with a macro or some VBA code

Thanks

Accepted answer +29 upvotes

I use this formula to get the input for a conditional formatting:

=IF(B2=B1,E1,MOD(E1+1,2))    [content of cell E2]

Where column B contains the item that needs to be grouped and E is an auxiliary column. Every time that the upper cell (B1 on this case) is the same as the current one (B2), the upper row content from column E is returned. Otherwise, it will return that content plus 1 MOD 2 (that is, the outupt will be 0 or 1, depending on the value of the upper cell).

enter image description here

enter image description here

enter image description here

Top excel-vba Q&A (6)

+29 upvotes ranks this answer #11 out of 136 excel-vba solutions on this site — top 8%.