Excel VBA:根据下拉列表的值突出显示/更改某些单元格的颜色(不是条件格式)

时间:2018-04-19 09:17:37

标签: excel vba if-statement

我想在单元格L10和L12中创建一个带有一些下拉选项的表单。根据这些单元格的值,我接着想要突出显示某些单元格,以帮助用户知道必须填写哪些字段。这将是Excel 2003所以我不能使用条件格式,因为它只能有3个,因此它需要在VBA中。

我处于绊脚石,可能会过度思考,但有人可以帮助我吗?

以下要求:

If L10 = yes
Then L12 = yellow

If L12 = yes OR no OR maybe
Then L16, L18, L20, L24, L26 = yellow

If L12 = progress
Then L14, L16, L18, L20, L24, L26 = yellow

If L12 = fail
Then L16, L18 = yellow

If L12 = assess
Then L14, L16, L18, L20, L24, L26 = yellow

If L10 = no
Then L16, L18, L20, L24, L26 = yellow

1 个答案:

答案 0 :(得分:1)

在VBA编辑器中,选择您的工作表,然后在Worksheet_Change sub中添加以下代码(作为示例附加屏幕打印。还要确保选择您正在使用的工作表):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Range("L10,L12"), Target) Is Nothing Then
        SetCellColour Target
    End If
End Sub

enter image description here

现在在Module中,添加以下子项:

Sub SetCellColour(ByVal oTarget As Range)
    Dim oW As Worksheet: Set oW = ThisWorkbook.Worksheets("Sheet8")     ' Change the sheet name

    Select Case oTarget.Address
        Case "$L$10"
            Select Case LCase(Trim(oTarget.Value))
                Case "yes"
                    oW.Range("L12").Interior.Color = 65535
                Case Is = "no"
                    oW.Range("L16, L18, L20, L24, L26").Interior.Color = 65535
            End Select
        Case "$L$12"
            Select Case LCase(Trim(oTarget.Value))
                Case "yes", "no", "maybe"
                    oW.Range("L16, L18, L20, L24, L26").Interior.Color = 65535
                Case "progress", "assess"
                    oW.Range("L14, L16, L18, L20, L24, L26").Interior.Color = 65535
                Case "fail"
                    oW.Range("L16, L18").Interior.Color = 65535
            End Select
    End Select

End Sub