Alternating coloring groups of rows in Excel

Based on Jason Z's answer, which from my tests seems to be wrong (at least on Excel 2010), here's a bit of code that happens to work for me :

Public Sub HighLightRows()
    Dim i As Integer
    i = 2 'start at 2, cause there's nothing to compare the first row with
    Dim c As Integer
    c = 2       'Color 1. Check http://dmcritchie.mvps.org/excel/colors.htm for color indexes

    Do While (Cells(i, 1) <> "")
        If (Cells(i, 1) <> Cells(i - 1, 1)) Then 'check for different value in cell A (index=1)
            If c = 2 Then
                c = 34   'color 2
            Else
                c = 2   'color 1
            End If
        End If

        Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.ColorIndex = c
        i = i + 1
    Loop
End Sub

Do you have to use code? if the table is static, then why not use the auto formatting capability?

enter image description here

It may also help if you "merge cells" of the same data. so maybe if you merge the cells of the "data, more data, even more data" into one cell, you can more easily deal with classic "each row is a row" case.


I think this does what you are looking for. Flips color when the cell in column A changes value. Runs until there is no value in column B.

Public Sub HighLightRows()
    Dim i As Integer
    i = 1
    Dim c As Integer
    c = 3       'red

    Do While (Cells(i, 2) <> "")
        If (Cells(i, 1) <> "") Then    'check for new ID
            If c = 3 Then
                c = 4   'green
            Else
                c = 3   'red
            End If
        End If

        Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.ColorIndex = c
        i = i + 1
    Loop
End Sub

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

=IF(B2=B1,E1,1-E1))    [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 1 minus that content (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

Tags:

Colors

Excel

Vba