Alternate Row Colors in Range

2020-02-04 20:21发布

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

标签: excel vba
8条回答
时光不老,我们不散
2楼-- · 2020-02-04 21:01

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.

Sub Color_Alt_Rows(Rng As Range)
    Application.ScreenUpdating = False

    Rng.Interior.ColorIndex = xlNone
    Rng = Rng.SpecialCells(xlCellTypeVisible)
    Rng.FormatConditions.Add Type:=xlExpression, Formula1:="=mod(row()+1,2)"
    Rng.FormatConditions(1).Interior.ColorIndex = 34
End Sub

Try it out with Color_Alt_Rows Range("a2:d5")

查看更多
看我几分像从前
3楼-- · 2020-02-04 21:06

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. Excel Table

查看更多
男人必须洒脱
4楼-- · 2020-02-04 21:13

Well, you can delete the else part, since you will leave it in the default color

查看更多
劫难
5楼-- · 2020-02-04 21:15

Alternating row colors can be done using conditional formatting:

screen capture

查看更多
家丑人穷心不美
6楼-- · 2020-02-04 21:16

set these up initialized somewhere:

Dim arr_Lng_Row_Color(1) As Long
arr_Lng_Row_Color(0) = RGB(int_Color_1_R, int_Color_1_G, int_Color_1_B)
arr_Lng_Row_Color(1) = RGB(int_Color_2_R, int_Color_2_G, int_Color_2_B)

On any row you wish this will set the color

ws_SomeSheet.Rows(int_Target_Row).EntireRow.Interior.Color = arr_Lng_Row_Color(int_Target_Row Mod 2)

查看更多
在下西门庆
7楼-- · 2020-02-04 21:17

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
查看更多
登录 后发表回答