Search code examples
excelvba

How to find Number of Occurences of Slash from a strings


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


Solution

  • 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