MS Excel VBA function doesn't work with a range in another sheet

Copper Contributor

I have a VBA function in Excel that looks at a range myRange and counts the cells that match a colour in a cell myCriteria.  It works when the myRange is in the current sheet but doesn't work if the range is in another sheet?

 

Function CountColors(myRange As Range, myCriteria As Range) As Long

    Dim myCell As Range, myCellColor As Long

    myCellColor = myCriteria.Interior.ColorIndex

    For Each myCell In myRange

        If myCell.Interior.ColorIndex = myCellColor Then

        CountColors = CountColors + 1

        End If

    Next myCell

End Function

 

Can anyone suggest what is wrong with myRange?

Thanks in advance

0 Replies