0
votes

I have the following macro CountCellsByColor (ORIGNAL BELOW) however I want to amend it so that it counts cells by color AND the specific text of the cell.

eg: The range has 5 different names all colored a different colour. I want the macro to only count the cells with the same name and color as the reference cell. ie Number of "Fred" 'yellow'cells

ORIGINAL FORMULA BELOW:

Function CountCellsByColor(rData As Range, cellRefColor As Range) As Long
    Dim indRefColor As Long
    Dim cellCurrent As Range
    Dim cntRes As Long

    Application.Volatile
    cntRes = 0
    indRefColor = cellRefColor.Cells(1, 1).Interior.Color
    For Each cellCurrent In rData
        If indRefColor = cellCurrent.Interior.Color Then
            cntRes = cntRes + 1
        End If
    Next cellCurrent

    CountCellsByColor = cntRes
End Function
2
Thanks Jeremy, your original comment worked ie - If indRefColor = cellCurrent.Interior.Color And cellCurrent.Value = searchtext Then - I just didnt enter it write initially. Thank you muchly for your assistance. Really appreciate itd735

2 Answers

1
votes

It should suffice to change

If indRefColor = cellCurrent.Interior.Color Then

to

If (indRefColor = cellCurrent.Interior.Color) AND (cellRefColor.cells(1,1).value=cellCurrent.value) Then
-1
votes

hope you are looking for this.

Function CountCellsByColor(rData As Range, cellRefColor As Range, searchtext As String) As Long
    Dim indRefColor As Long
    Dim cellCurrent As Range
    Dim cntRes As Long
    Application.Volatile
    cntRes = 0
    indRefColor = cellRefColor.Cells(1, 1).Interior.Color
    For Each cellCurrent In rData
        If indRefColor = cellCurrent.Interior.Color And cellCurrent.Value = searchtext Then
            cntRes = cntRes + 1
        End If
    Next cellCurrent
    CountCellsByColor = cntRes
End Function

Working Sample

enter image description here