0
Function CountColor(rColor As Range, rSumRange As Range)
    Dim rCell As Range
    Dim iCol As Integer
    Dim vResult As Integer
    iCol = rColor.Interior.ColorIndex

    For Each rCell In rSumRange
        If rCell.Interior.ColorIndex = iCol Then
            vResult = 1
        Else 
            vResult =  0
        End If
    Next rCell 
    CountColor = vResult
End Function

I try typing "=CountColor(A1, A2)" but I always get the error "Sub or function not defined" Why is this? I've been stuck on this for hours.

13
  • 4
    Is this in a workbook module, or worksheet module? It works for me if I place in a Workbook module. Commented Mar 8, 2016 at 23:49
  • 1
    I think this is a duplicate of: stackoverflow.com/questions/12351339/… Commented Mar 8, 2016 at 23:50
  • 1
    Sorry, what is the difference between the two? I just inserted a module by right clicking on the project and creating a new module. Commented Mar 8, 2016 at 23:51
  • worksheet UDFs should be created in a standard code module in the same workbook. Failing that, try giving your UDF an explicit return data type Commented Mar 8, 2016 at 23:52
  • That is where it should be. It should be in a module attached to the workbook in which it is being called. Commented Mar 8, 2016 at 23:52

1 Answer 1

1

I could not reproduce the error that you are experiencing.

If you use the code as you have it, the result will not be accurate, for example: =CountColor(A1,B1:B20) will only give you a result of 1 or 0 because you are not adding the results together.

If you are just comparing the interior colors, you don't really need to use interior.colorindex, just interior.color should work, so I changed iCol as string

else is not required in your if statement.

I also added Application.volatile to the code, so it will calculate when the sheet calculates.

Function CountColor(rColor As Range, rSumRange As Range)
    Dim rCell As Range
    Dim iCol As String
    Dim vResult As Integer

    iCol = rColor.Interior.Color
    Application.Volatile

    For Each rCell In rSumRange
        If rCell.Interior.Color = iCol Then
            vResult = 1 + vResult
            '        Else
            '            vResult = 0
        End If
    Next rCell

    CountColor = vResult

End Function
Sign up to request clarification or add additional context in comments.

2 Comments

I guess that APplication.volatile did the trick? Not sure, but once I added that, the error stopped being produced. Thanks!
@user3002486 String is the wrong data type for iCol. .Color returns numeric, casting it to String is pointless. Better to use Long

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.