How can I find the number of occurrences of the forward slash character ( / ) within a string using an Excel VBA macro?
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
Not a big fan of hungarian notations, but thanks for the added comments :-)
There are two different kinds of Hungarian Notation. This is actually Systems Hungarian, the most dominant one, and not the original concept which initially also was called Apps Hungarian. There's a big difference between them, one you can read about here: joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong