简体   繁体   English

VBA自我功能返回#VALUE! 单元格出错,而在“函数”窗口中正确返回实际值

[英]VBA Self-Function returns #VALUE! Error on cell, while in Function window returns the actual value correctly

function i wrote below is taking one range which i have some conditional formatting on (for font color), and another one cell range for comparing color. 我在下面写的函数是一个范围,我有一些条件格式(对于字体颜色),另一个单元格范围用于比较颜色。 Function is counting how many cells in the big range having the same font color as the one cell range. 功能是计算大范围内具有与一个单元格范围相同的字体颜色的单元格数。

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

Now, problem is - in the function window, the actual result is coming correctly, while in the cell itself, i'm getting #VALUE! 现在,问题是 - 在函数窗口中,实际结果是正确的,而在单元格本身,我得到#VALUE! error. 错误。

The following code worked for me but not with conditional formatting: 以下代码适用于我,但不适用于条件格式:

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

If I simply change the font color apart from conditional formatting it works. 如果我只是改变字体颜色,除了条件格式,它的工作原理。 But for some reason it won't work, otherwise. 但由于某种原因它不起作用,否则。

As multiple people have mentioned in the comments - The DisplayFormat property doesn't work in user defined functions. 正如多个人在评论中提到的那样 - DisplayFormat属性在用户定义的函数中不起作用。 Therefore, if you remove .DisplayFormat. 因此,如果您删除.DisplayFormat. from your function it should work as expected. 从你的功能它应该按预期工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM