简体   繁体   中英

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! 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. Therefore, if you remove .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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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