PURPOSE: Returns Number of occurrences of a character or
or a character sequencence within a string

OrigString: String to Search in
Chars: Character(s) to search for
CaseSensitive (Optional): Do a case sensitive search
Defaults to false

Number of Occurrences of Chars in OrigString

Public Function CharCount(OrigString As String, _
Chars As String, Optional CaseSensitive As Boolean = False) _
As Long

Dim lLen As Long
Dim lCharLen As Long
Dim lAns As Long
Dim sInput As String
Dim sChar As String
Dim lCtr As Long
Dim lEndOfLoop As Long
Dim bytCompareType As Byte

sInput = OrigString
If sInput = "" Then Exit Function
lLen = Len(sInput)
lCharLen = Len(Chars)
lEndOfLoop = (lLen - lCharLen) + 1
bytCompareType = IIf(CaseSensitive, vbBinaryCompare, _

For lCtr = 1 To lEndOfLoop
sChar = Mid(sInput, lCtr, lCharLen)
If StrComp(sChar, Chars, bytCompareType) = 0 Then _
lAns = lAns + 1

CharCount = lAns

End Function

CharCount("Dotnetspider", "E") -- returns 2
CharCount("Dotnetspider", "E", True) -- returns 0

0 Responses to Number of occurances of a character or character sequence in a string

Post a Comment