VBA自函数返回#VALUE! 单元格错误,而在函数窗口中正确返回实际值

函数我写下面是采取一个范围,我有一些条件格式(字体颜色),另一个单元格范围比较颜色。 函数计算大范围内具有与单元格范围相同字体颜色的单元格的数量。

Function CountColor(rng As Range, clr As Range) As Integer Dim c As Range Dim a As Integer a = 0 For Each c In rng If c.DisplayFormat.Font.Color = clr.Font.Color Then a = a + 1 End If Next CountColor = a End Function 

现在,问题是 – 在函数窗口中,实际的结果是正确的,而在单元格本身,我得到#VALUE! 错误。

以下代码适用于我,但不适用于条件格式:

 Option Explicit Function CountColor(rng As Range, clr As Variant) As Variant Dim c As Range Dim a As Integer a = 0 For Each c In rng If c.Font.color = clr.Font.color Then a = a + 1 End If Next c CountColor = a End Function 

如果我简单地改变字体颜色除条件格式之外,它的作品。 但是,由于某种原因,它不会工作,否则。

正如多个人在评论中提到的 – DisplayFormat属性在用户定义的函数中不起作用。 因此,如果删除.DisplayFormat. 从你的function,它应该按预期工作。

 Function CountColor(rng As Range, clr As Range) As Integer Dim c As Range Dim a As Integer a = 0 For Each c In rng If c.Font.Color = clr.Font.Color Then a = a + 1 End If Next CountColor = a End Function