如何使用VBA根据单元格值应用填充颜色

时间:2016-07-07 10:52:19

标签: excel vba excel-vba

我目前在下面有这个代码。如果单元格为空白,则填充将为绿色(4)。当单元格不是空白时,将没有填充。但是如果我希望我的单元格 (0,3) 填充黄色,如果单元格值="是&#34 ;?目前有一个下拉菜单,用于" YES"或"否"。

Private Sub worksheet_change(ByVal Target As Range)


    If Not Intersect(Target, Range("A:A")) Is Nothing Then


        ActiveSheet.Unprotect
        If Target = "YES" Then
            For i = 1 To 9
                With Target.Offset(0, i)
                    .Locked = False
                    .FormatConditions.Add Type:=xlExpression, Formula1:="=ISBLANK(" & Target.Offset(0, i).Address & ")"
                    With .FormatConditions(.FormatConditions.Count)
                        .SetFirstPriority
                        .Interior.ColorIndex = 4
                    End With
                End With
            Next i

       '==============================================================================================================
       '==============================================================================================================

        ElseIf Target = "NO" Then

                For i = 10 To 15
                With Target.Offset(0, i)
                    .Locked = False
                    .FormatConditions.Add Type:=xlExpression, Formula1:="=ISBLANK(" & Target.Offset(0, i).Address & ")"
                    With .FormatConditions(.FormatConditions.Count)
                        .SetFirstPriority
                        .Interior.ColorIndex = 4
                    End With
                End With
            Next i

        Else

                For i = 1 To 15
                    With Target.Offset(0, i)
                        .Value = ""
                       .Locked = True
                        .FormatConditions.Delete
                    End With
                Next i

        End If

        ActiveSheet.Protect

    End If


End Sub

2 个答案:

答案 0 :(得分:1)

见下面的补充

    For i = 26 To 28

        With Target.Offset(0, i)
            .Locked = False
            .FormatConditions.Add Type:=xlExpression, Formula1:="=ISBLANK(" & Target.Offset(0, i).Address & ")"
            With .FormatConditions(.FormatConditions.Count)
                .SetFirstPriority
                .Interior.ColorIndex = 45
            End With
        End With
        If i = 27 AND UCase(Target.Offset(0,i).value) = "YES" Then Target.Offset(0,i).Interior.Color = RGB(255,255,0)
    Next i

答案 1 :(得分:0)

如果range.value =" YES"

,则使用Color = 65535