2015年3月28日 星期六

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)






strString to be evaluated
substrSubstring that you want to count

Example of Custom Function – count substring in string








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

 



Excel count substring in string or text

沒有留言:

張貼留言