如果不能越过障碍

时间:2019-07-02 14:34:49

标签: excel vba

我正在尝试根据单元格的值来设置具有内部颜色的单元格

尝试添加结束(如果添加)和更改结束(如果使用Else)。只是无法摆脱过去的问题。如果有问题则阻止,否则则无问题。

Sub Colorcell()
    For Each cel In Range(a2, a5)
    If cel.Value = "Red" Then
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 5296274
        .TintAndShade = 0
        .PatternTintAndShade = 0
    ElseIf cel.Value = "blue" Then
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 12611584
        .TintAndShade = 0
        .PatternTintAndShade = 0

接收

  

编译错误,否则为If。

匹配颜色字词时,期望用代码中的指定颜色为单元格着色

2 个答案:

答案 0 :(得分:2)

您需要关闭WithIf语句:

Sub Colorcell()
    ' I assume the range below is what you mean by `Range(a2,a5)`...
    For Each cel In Range("A2:A5")
    If cel.Value = "Red" Then
        With cel.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = 5296274
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
    ElseIf cel.Value = "blue" Then
        With cel.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = 12611584
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
    End If
    Next cel
End Sub

还有一个想法-为什么不只使用条件格式而不是宏?

答案 1 :(得分:1)

更简单:

Sub Colorcell()
    For Each cel In Range("A2:A5")
        If cel.Value = "Red" Then
            cel.Interior.Color = vbRed
        ElseIf cel.Value = "blue" Then
            cel.Interior.Color = vbBlue
        End If
    Next cel
End Sub

注意,这是区分大小写的。