Home

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

%3CLINGO-SUB%20id%3D%22lingo-sub-433535%22%20slang%3D%22en-US%22%3EMS%20Excel%20VBA%20function%20doesn't%20work%20with%20a%20range%20in%20another%20sheet%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-433535%22%20slang%3D%22en-US%22%3E%3CP%3EI%20have%20a%20VBA%20function%20in%20Excel%20that%20looks%20at%20a%20range%20myRange%20and%20counts%20the%20cells%20that%20match%20a%20colour%20in%20a%20cell%20myCriteria.%26nbsp%3B%26nbsp%3BIt%20works%20when%20the%20myRange%20is%20in%20the%20current%20sheet%20but%20doesn't%20work%20if%20the%20range%20is%20in%20another%20sheet%3F%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EFunction%20CountColors(myRange%20As%20Range%2C%20myCriteria%20As%20Range)%20As%20Long%3C%2FP%3E%3CP%3E%26nbsp%3B%20%26nbsp%3B%20Dim%20myCell%20As%20Range%2C%20myCellColor%20As%20Long%3C%2FP%3E%3CP%3E%26nbsp%3B%20%26nbsp%3B%20myCellColor%20%3D%20myCriteria.Interior.ColorIndex%3C%2FP%3E%3CP%3E%26nbsp%3B%20%26nbsp%3B%20For%20Each%20myCell%20In%20myRange%3C%2FP%3E%3CP%3E%26nbsp%3B%20%26nbsp%3B%20%26nbsp%3B%20%26nbsp%3B%20If%20myCell.Interior.ColorIndex%20%3D%20myCellColor%20Then%3C%2FP%3E%3CP%3E%26nbsp%3B%20%26nbsp%3B%20%26nbsp%3B%20%26nbsp%3B%20CountColors%20%3D%20CountColors%20%2B%201%3C%2FP%3E%3CP%3E%26nbsp%3B%20%26nbsp%3B%20%26nbsp%3B%20%26nbsp%3B%20End%20If%3C%2FP%3E%3CP%3E%26nbsp%3B%20%26nbsp%3B%20Next%20myCell%3C%2FP%3E%3CP%3EEnd%20Function%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3ECan%20anyone%20suggest%20what%20is%20wrong%20with%20myRange%3F%3C%2FP%3E%3CP%20class%3D%22%22%3EThanks%20in%20advance%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-LABS%20id%3D%22lingo-labs-433535%22%20slang%3D%22en-US%22%3E%3CLINGO-LABEL%3EMacros%20and%20VBA%3C%2FLINGO-LABEL%3E%3C%2FLINGO-LABS%3E
Cathi69
Occasional 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

Related Conversations
Tabs and Dark Mode
cjc2112 in Discussions on
50 Replies
Extentions Synchronization
Deleted in Discussions on
3 Replies
Stable version of Edge insider browser
HotCakeX in Discussions on
35 Replies
How to Prevent Teams from Auto-Launch
chenrylee in Microsoft Teams on
32 Replies
Security Community Webinars
Valon_Kolica in Security, Privacy & Compliance on
15 Replies
Dev channel update to 80.0.355.1 is live
josh_bodner in Discussions on
67 Replies