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
I needed a macro that would color every second row in a range, using only those rows that were visible. This is what I came up with. You don't have to loop through the rows.
Try it out with
Color_Alt_Rows Range("a2:d5")
In my Excel 2010, there is an option to format as table, where you can also select a range and headers. No need for scripting.
Well, you can delete the
else
part, since you will leave it in the default colorAlternating row colors can be done using conditional formatting:
set these up initialized somewhere:
On any row you wish this will set the color
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:
Usage: