Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

excel - Alternate Row Colors in Range

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...