条件格式单元格的颜色索引

Color index of conditionally formatted cell

我有一个 sheet,其中有一些条件格式的单元格。对于红色和蓝色,每个单元格有 2 条规则。还有另一个 sheet,我在宏中有一个 If 公式,用于检查那些条件格式单元格中的颜色:

If Range("Q10").End(xlDown).Interior.ColorIndex = 33 Then
code
End If

但似乎这段代码无法正常工作,因为单元格是有条件格式化的。宏在不输入 If 公式的情况下运行,并直接转到 End If。我如何确保它有效?

谢谢

有一种方法可以获取使用条件格式设置的单元格的 Interior.ColorInterior.ColorIndex

通用子代码

Option Explicit

Sub GetFormatColor()

Dim CColor As Long
Dim CColorIndex As Long

' get the Color value of the first conditional formatting rule
CColor = Sheets("Sheet1").Range("Q10").FormatConditions(1).Interior.color

' get the ColorIndex value of the first conditional formatting rule
CColorIndex = Sheets("Sheet1").Range("Q10").FormatConditions(1).Interior.ColorIndex

End Sub

因此,在您的情况下,您需要找出您要查看的条件格式规则。例如,假设我们要检查 Range("Q10")Cell.ColorIndex,并且颜色是条件格式中规则集中的第一个规则。

此post的代码示例:

' modify "Sheet1" to your sheet's name, where you set-up the conditional formatting
If Sheets("Sheet1").Range("Q10").FormatConditions(1).Interior.ColorIndex = 33 Then
    MsgBox "ColorIndex is : " & Sheets("Sheet1").Range("Q10").FormatConditions(1).Interior.ColorIndex
End If

如果您使用的是 Excel 2010(或更高版本),则可以使用范围的 DisplyFormat 属性,因此您可以使用下面的代码:

If Sheets("Sheet1").Range("Q10").DisplayFormat.Interior.ColorIndex = 33 Then
    MsgBox "ColorIndex is : " & Sheets("Sheet1").Range("Q10").DisplayFormat.Interior.ColorIndex
End If