如果有颜色,计算有条件格式化的单元格

Count Conditionally Formatted Cells if Colored

我正在尝试编写一个函数来计算由于条件格式而被着色的单元格。 UDF 不能使用 DisplayFormat 属性,所以 Tim Williams 在下面写了这个绝妙的解决方案。当我最初将函数输入单元格时效果很好。但是,当我更改它指向的其中一个单元格中的值时,该函数会报告 0。然后我必须重新输入该函数才能使其正确回答。

有人知道为什么会这样吗?以及如何修复它?

Function DFColor(addr As String)
    DFColor = Range(addr).DisplayFormat.Interior.color
End Function


Function CountColoredCells(rng As Range) As Long
    Dim count As Long, color As Long, cell As Range
    count = 0
    For Each cell In rng.Cells
        color = rng.Parent.Evaluate("DFColor(""" & cell.Address() & """)")
        If color <> 16777215 Then       '16777215 is the blank color value
            count = count + 1
        End If
    Next cell
    CountColoredCells = count
End Function

这是 link 他 post 的解决方案 -

这个设计有一个错误:

Function DFColor(addr As String)
    DFColor = Range(addr).DisplayFormat.Interior.color
End Function

单元格地址作为字符串传递,然后使用 Range() 转换为范围对象,但由于 Range()(在常规代码模块中)默认为 ActiveSheet,如果 sheet 条件格式不是 ActiveSheet 你会得到错误的结果(因此你看到的是零)。

这更稳健 - 传入实际范围并直接使用:

Function DFColor(c As Range)
    DFColor = c.DisplayFormat.Interior.color
End Function

Function CountColoredCells(rng As Range) As Long
    Dim count As Long, color As Long, cell As Range
    count = 0
    For Each cell In rng.Cells
        color = rng.Parent.Evaluate("DFColor(" & cell.Address() & ")") '<<EDITED
        If color <> 16777215 Then       '16777215 is the blank color value
            count = count + 1
        End If
    Next cell
    CountColoredCells = count
End Function

我已经在链接 post

编辑了版本