如何从字符串中找到Slash的出现次数

Cod*_*gry 25 excel vba excel-vba

如何使用Excel VBA宏查找字符串中正斜杠字符(/)的出现次数?

小智 37

老问题,但我想我会通过在excel论坛上找到的答案来增加答案的质量.显然,计数也可以使用.

    count =Len(string)-Len(Replace(string,"/",""))
Run Code Online (Sandbox Code Playgroud)

答案全部归功于原作者:http://www.ozgrid.com/forum/showthread.php?t = 45651

  • 一个更通用的答案是`count = (Len(string)-Len(Replace(string,"/",""))) / len("/")`。那么你也可以对长度大于1的字符串进行计数。 (7认同)
  • 这样做的好处是,您可以使用`SUBSTITUTE()`在VBA中轻松地在公式中使用它 (2认同)

ass*_*ias 17

使用以下功能,如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
Run Code Online (Sandbox Code Playgroud)


mar*_*uja 14

Function CountOfChar(str as string, character as string) as integer
      CountOfChar = UBound(Split(str, character))
End Function
Run Code Online (Sandbox Code Playgroud)