VBA 根据字体颜色计算值

VBA Count values based on font color

当内容为某种字体颜色(例如黑色)时,我需要添加范围值。我有一个 table ,我在其中有条件地格式化值的颜色。例如,如果 "Status =Carry Over" 那么我将行着色为红色。 (见附件)

现在,在条件格式设置之后,我想将特定列下 NOT 的所有数字值相加并显示为红色。

我有一段 vba 代码可以添加这样的值,但问题是,条件着色使代码失效。只要我手动为行着色,代码就会忽略红色行。如果我使用条件着色选项,那么即使是彩色行也会被考虑在内。

我正在使用这个公式调用下面的 UDF =ConditionalColorSum(C2:C30)

Public Function ConditionalColorSum(rnge As Range) As Double
' Total only cells with red font numbers
    Application.Volatile
    Dim Total As Double, cl As Range
    Total = 0
        For Each cl In rnge.Cells
            If cl.Font.Color = vbRed Then    'Change 'vbRed' to the color you want
            Total = Total + cl.Value
            End If
        Next
    ConditionalColorSum = Total
End Function

条件格式公式如上所示:

根据THIS

Actions such as changing the conditional formatting or table style of a range can cause what is displayed in the current user interface to be inconsistent with the values in the corresponding properties of the Range object. Use the properties of the DisplayFormat object to return the values as they are displayed in the current user interface.

根据条件格式获取颜色的唯一方法是使用 DisplayFormat

If cl.DisplayFormat.Font.Color = vbRed Then

但根据 THIS

Note that the DisplayFormat property does not work in user-defined functions.

因此不能使用 UDF 直接从 sheet 计算颜色。可以使用 SUB,但使用自定义格式用于计数的相同标准会更容易:

=COUNTIF(E2:E30,"Carry Over")

或者统计不红的地方:

=COUNTIF(E2:E30,"<>Carry Over")