在VBA中使用通配符进行条件格式设置(Excel 2003)

时间:2014-07-19 05:15:07

标签: excel vba excel-vba wildcard conditional-formatting

我编写了以下VBA,为Excel 2003中的工作表添加了一堆条件格式(否则只允许3个条件),但它不能正确使用通配符。如果我用通配符替换确切的值,它会正确运行。我怀疑关于<>的最后陈述可能需要调整,但我不知道如何jike​​ LIKE"通配符"与<>在末尾。以下VBA代码:

    Private Sub Worksheet_Change (ByVal Target As Range)
    Set MyPlage = Range(“C3:I11,C13:I34”)
        For Each Cell in MyPlage

    If Cell.Value Like “A*” Then
            Cell.Interior.ColorIndex = 38
    End If
    If Cell.Value Like “B*” Then
            Cell.Interior.ColorIndex = 35
    End If
    If Cell.Value Like “C*” Then
            Cell.Interior.ColorIndex = 34
    End If
    If Cell.Value Like “D*” Then
            Cell.Interior.ColorIndex = 40
    End If
    If Cell.Value <> “A*” And Cell.Value <> “B*” And Cell.Value <> “C*” And Cell.Value <> “D*” Then
    Cell.Interior.ColorIndex = xlNone
    End If

    Next
End Sub

1 个答案:

答案 0 :(得分:1)

你真的不需要通配符,因为它只是一个基本的If ... ElseIf ...结束如果结构:

   Private Sub Worksheet_Change (ByVal Target As Range)
    Set MyPlage = Range(“C3:I11,C13:I34”)
        For Each Cell in MyPlage

    If Cell.Value Like “A*” Then
            Cell.Interior.ColorIndex = 38
    ElseIf Cell.Value Like “B*” Then
            Cell.Interior.ColorIndex = 35
    ElseIf Cell.Value Like “C*” Then
            Cell.Interior.ColorIndex = 34
    ElseIf Cell.Value Like “D*” Then
            Cell.Interior.ColorIndex = 40
    Else
        Cell.Interior.ColorIndex = xlNone
    End If

    Next
End Sub