每隔一行格式化颜色

时间:2016-12-13 21:42:18

标签: excel vba formatting

我能够在堆栈溢出时找到两个代码,但是不能让它给出一个浅灰色格式的行,然后是白色行,帮助将不胜感激,尝试了两个代码

Sub Colour(rng As Range, firstColor As Long, secondColor As Long)
    rng.Interior.ColorIndex = xlAutomatic
    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 ColourFormatting()
    Dim rng As Range
    Dim firstColor As Long
    Dim secondColor As Long

    Set rng = Range("A1:E10")
    firstColor = Pattern = xlSolid: PatternColorIndex = xlAutomatic: ThemeColor = xlThemeColorDark1: TintAndShade = -0.149998474074526: PatternTintAndShade = 0
    secondColor = TintAndShade = 0: PatternTintAndShade = 0
'
    Call Colour(rng, firstColor, secondColor)
End Sub

Sub ShadeEveryOtherRow()
    Dim Counter As Integer

    'For every row in the current selection...
    For Counter = 1 To Range("A1:E30").Rows.Count
        'If the row is an odd number (within the selection)...
        If Counter Mod 2 = 1 Then
            'Set the pattern to xlGray16.
            Range("A1:E30").Rows(Counter).Interior.Pattern = xlSolid: PatternColorIndex = xlAutomatic: ThemeColor = xlThemeColorDark1: TintAndShade = -0.149998474074526: PatternTintAndShade = 0

        End If
    Next

End Sub

1 个答案:

答案 0 :(得分:1)

您不需要VBA - 您可以使用带公式的条件格式:

=MOD(ROW(),2)=1

并将格式设置为浅灰色。对第一行执行此操作,然后将该行复制为格式(粘贴特殊)。

您的代码在参数中使用了错误的分隔符,VBA中的冒号表示新行,因此您的语句

Range("A1:E30").Rows(Counter).Interior.Pattern = xlSolid: PatternColorIndex = xlAutomatic

相同
Range("A1:E30").Rows(Counter).Interior.Pattern = xlSolid 
PatternColorIndex = xlAutomatic

我认为VBA正在使用你最新选择的第二行。

尝试:

Range("A1:E30").Rows(Counter).Interior.Pattern = xlSolid, PatternColorIndex = xlAutomatic