Excel count substring in string or text

This Excel tutorial explains how to count substring in string (text).

Excel count substring in string (text)

Excel does not have a buit-in Function to count substring in string (text), instead you need to work around to get the job done. Alternatively, I have made a Macro solution for your reference.

Excel count substring in string using Len and Substitute Function

Excel Len Function is to measure the length of text.

Excel Substitute Function is to replace a substring in a text.

To count substring in string, simply replace the target substring with nothing (removing the substring), and then measure the difference of text length before and after substitute, and then divide the difference by length of substring.

For example, A1 contains the string, while B1 is the substring.

=(LEN(A1)-LEN(SUBSTITUTE(A1,B1,””)))/LEN(B1)

Excel VBA custom Function to count substring in string

I created this custom Function long time ago before I knew the Len and Substitute trick, now this is for your reference.

Public Function wCountSubStr(str As String, substr As String) As Integer
    lenstr = Len(str)
    lensubstr = Len(substr)
    
    For i = 1 To lenstr
        tempString = Mid(str, i, lensubstr)
        If tempString = substr Then
            count = count + 1
        End If
    Next i
    wCountSubStr = count
End Function

Syntax of Custom Function – count substring in string

wCountSubStr(str, substr)

str String to be evaluated
substr Substring that you want to count

Example of Custom Function – count substring in string

Formula Result
=wCountSubStr(“123412″,”12”) 2
=wCountSubStr(“#**$”,”1″) 0

 

Wyman W
Wyman is a Business Analyst based in Hong Kong, specialized in creating custom Function and Sub solutions, and is proficient in report automation with Access.

He is also a:
- Microsoft Most Valuable Professional (Excel)
- Microsoft Community Contributor
- Microsoft Office Specialist
- Microsoft Specialist
- Microsoft Technical Associate
- Microsoft Certified Professional
- IBM SPSS Specialist

Leave a Reply

Your email address will not be published. Required fields are marked *