Home » excel » Excel COUNTIF with strings, separated by comma

# Excel COUNTIF with strings, separated by comma

Questions:

I am trying to write a simple formula to count how many times a particular name appears in a column. I am using COUNTIF as it is a pretty straight forward process but I cannot work out how to make it happen for a name in particular. This is the case:

The column named Age will display cells with one or more names, separated by commas in case there are more than one value. Putting “Young” as an example is easy to tell the COUNTIF formula to give me the number representing how many times this word appears, either being the only value in cell or as a part of a cell with a longer string value by giving the formula the “Young” statement.

The problem comes when I want the formula to count how many times “Mature” appears in my column. I cannot work out the way to make it count only when it says “Mature” without also taking all the “Early_Mature” or “Semi_Mature”

I know this is easy for whoever knows the basics of Excel so I don’t think there is need to give more details.

Thanks

To get the number of occurrences of Mature excluding those that have prefix you can use this array formula:

=SUM(((LEN(A2:A7)-LEN(SUBSTITUTE(A2:A7,"Mature",""))) / LEN("Mature"))-((LEN(A2:A7)-LEN(SUBSTITUTE(A2:A7,"_Mature",""))) / LEN("_Mature")))

Please take note that this formula is applied with Ctrl + Shift + Enter.

Given that your range is in Y:Y column, just change the range to one you need.

Most of the times I succeed solving such problems by adding the same delimiter (of our string) at the beginning and end of the main string.

So since your data is at COL:Y, you may create a new helper COL:Z and enter this formula:

="," & Y1 & ","

I did not use any spaces before or after comma since your data seems not having any space. Depending on your case, you may have to use spaces.

Now your string is wrapped with commas, which you may alter COUNTIF formula to such:

=COUNTIF(Z:Z,"*,"&B1&",*")

* characters are jokers which stand for “anything” in this context.

With an UDF. Code goes in a standard module added by opening the VBE with Alt + F11 then right-click in project explorer and add module.

Code

Option Explicit

Public Function GetCount(ByRef selectRange As Range, ByVal searchTerm As String) As Long
Application.Volatile
With selectRange

Dim arr(), joinedString As String, i As Long, outputCount As Long
arr = .Value

joinedString = Join(Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Index(arr, 0, 1)), ",")

Dim arr2() As String
arr2 = Split(joinedString, ",")

For i = LBound(arr2) To UBound(arr2)
If Trim\$(arr2(i)) = "Mature" Then
outputCount = outputCount + 1
End If
Next i
End With

GetCount = outputCount

End Function

Usage in sheet