在VBA中使用通配符进行条件格式设置(Excel 2003)
我使用下面的VBA向Excel2003中的工作表中添加了一组条件格式(除此之外只允许3个条件),但它不能正确使用通配符。如果我用通配符替换精确的值,它将正确运行。我怀疑关于的最后一句话可能需要调整,但我不知道如何在结尾处使用类似的“通配符”。VBA代码如下:在VBA中使用通配符进行条件格式设置(Excel 2003),vba,excel,wildcard,conditional-formatting,Vba,Excel,Wildcard,Conditional Formatting,我使用下面的VBA向Excel2003中的工作表中添加了一组条件格式(除此之外只允许3个条件),但它不能正确使用通配符。如果我用通配符替换精确的值,它将正确运行。我怀疑关于的最后一句话可能需要调整,但我不知道如何在结尾处使用类似的“通配符”。VBA代码如下: Private Sub Worksheet_Change (ByVal Target As Range) Set MyPlage = Range(“C3:I11,C13:I34”) For Each Cell
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
Private子工作表\u更改(ByVal目标作为范围)
设置MyPlage=范围(“C3:I11,C13:I34”)
对于MyPlage中的每个细胞
如果单元格.Value像“A*”那么
Cell.Interior.ColorIndex=38
如果结束
如果单元格的值像“B*”那么
Cell.Interior.ColorIndex=35
如果结束
如果单元格的值像“C*”那么
Cell.Interior.ColorIndex=34
如果结束
如果单元格.Value像“D*”那么
Cell.Interior.ColorIndex=40
如果结束
如果单元格数值“A*”和单元格数值“B*”以及单元格数值“C*”和单元格数值“D*”,则
Cell.Interior.ColorIndex=xlNone
如果结束
下一个
端接头
您实际上不需要通配符,因为它只是一个基本的If…ElseIf…End If结构:
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
谢谢Rory,这很有效!如果我想格式化整行,而不仅仅是行中的相对单元格,那么要混合一点吗?我可以在以后的Excel中这样做,但在Excel 2003中使用VBA无法解决。应该没有任何版本差异:`Cell.Entirerow.Interior.ColorIndex=40`