Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate Row Colors in Range

Tags:

excel

vba

I've come up with the following to alternate row colors within a specified range:

Sub AlternateRowColors()
Dim lastRow as Long

lastRow = Range("A1").End(xlDown).Row

For Each Cell In Range("A1:A" & lastRow) ''change range accordingly
    If Cell.Row Mod 2 = 1 Then ''highlights row 2,4,6 etc|= 0 highlights 1,3,5
        Cell.Interior.ColorIndex = 15 ''color to preference
    Else
        Cell.Interior.ColorIndex = xlNone ''color to preference or remove
    End If
Next Cell

End Sub

That works, but is there a simpler method?

The following lines of code may be removed if your data contains no pre-exisiting colors:

    Else
        Cell.Interior.ColorIndex = xlNone
like image 396
Kurt Avatar asked Jan 07 '11 18:01

Kurt


People also ask

How do I change the color of my alternate rows?

To change the alternate row color:Select the Home tab, locate the Text Formatting group, and click the Alternate Row Color drop-down arrow. Select a color from the drop-down menu, or select No Color to remove the alternate row color. The alternate row color will be updated.

How do I alternate row colors in Excel without a table?

Fill the first and second rows with the different colors you want. Go to the Home tab > Fill Color (in the font group) and choose the color you want (you can also use the shortcut key). With the first and second rows selected, press Ctrl+C at the same time to copy these 2 rows.

How do I color alternate rows in Tableau?

Go to Format > Shading and configure your alternating colors in the "Row Banding" and "Column Banding" sections. You can adjust the colors as well as how many rows to include before alternating (band size) and at what level in your table the banding should be applied.


1 Answers

I need to do this frequently and like to be able to easily modify the colors I'm using for the banding. The following sub makes it very easy:

Sub GreenBarMe(rng As Range, firstColor As Long, secondColor As Long)
    rng.Interior.ColorIndex = xlNone
    rng.FormatConditions.Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)=0"
    rng.FormatConditions(1).Interior.Color = firstColor
    rng.FormatConditions.Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)<>0"
    rng.FormatConditions(2).Interior.Color = secondColor
End Sub

Usage:

Sub TestGreenBarFormatting()
    Dim rng As Range
    Dim firstColor As Long
    Dim secondColor As Long

    Set rng = Range("A1:D12")
    firstColor = vbGreen
    secondColor = vbYellow

    Call GreenBarMe(rng, firstColor, secondColor)
End Sub
like image 85
Jon Crowell Avatar answered Nov 03 '22 00:11

Jon Crowell