Warm tip: This article is reproduced from serverfault.com, please click

How to find Number of Occurences of Slash from a strings

发布于 2012-02-13 13:02:44

How can I find the number of occurrences of the forward slash character ( / ) within a string using an Excel VBA macro?

Questioner
Code Hungry
Viewed
11
20.8k 2012-02-13 22:09:45

Use the below function, as in count = CountChrInString(yourString, "/").

'''
''' Returns the count of the specified character in the specified string.
'''
Public Function CountChrInString(Expression As String, Character As String) As Long
'
' ? CountChrInString("a/b/c", "/")
'  2
' ? CountChrInString("a/b/c", "\")
'  0
' ? CountChrInString("//////", "/")
'  6
' ? CountChrInString(" a / b / c ", "/")
'  2
' ? CountChrInString("a/b/c", " / ")
'  0
'
    Dim iResult As Long
    Dim sParts() As String

    sParts = Split(Expression, Character)

    iResult = UBound(sParts, 1)

    If (iResult = -1) Then
    iResult = 0
    End If

    CountChrInString = iResult

End Function