2012-02-13 57 views

回答

10

使用以下功能,如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 
+0

不匈牙利命名法的忠實粉絲,但由於對於增加的評論:-) – assylias 2012-02-13 14:12:17

17

老問題,但我想我會添加到我在Excel論壇找到的答案的答案的質量。顯然,計數也可以使用。

count =Len(string)-Len(Replace(string,"/","")) 

的答案完全歸功於原作者爲:http://www.ozgrid.com/forum/showthread.php?t=45651

+1

哈!我只是想到了那個,但我來到這裏看看是否有更好的解決方案。 – GuitarPicker 2015-04-13 20:38:19

0

這是VBA Excel宏簡單的解決辦法。

Function CharCount(str As String, chr As String) As Integer 
    CharCount = Len(str) - Len(Replace(str, chr, "")) 
End Function 
+0

什麼使你的答案不同於Santhosh Divakar的? – 2016-08-18 07:20:31

3
Function Count(str as string, character as string) as integer 
     Count = UBound(Split(str, character)) 
End Function 
0

順便說一句,如果你是到性能,下面是比使用拆分或更換,以確定計數快20%:

Private Function GetCountOfChar(_ 
    ByRef ar_sText As String, _ 
    ByVal a_sChar As String _ 
) As Integer 
    Dim l_iIndex As Integer 
    Dim l_iMax As Integer 
    Dim l_iLen As Integer 

    GetCountOfChar = 0 
    l_iMax = Len(ar_sText) 
    l_iLen = Len(a_sChar) 
    For l_iIndex = 1 To l_iMax 
    If (Mid(ar_sText, l_iIndex, l_iLen) = a_sChar) Then 'found occurrence 
     GetCountOfChar = GetCountOfChar + 1 
     If (l_iLen > 1) Then l_iIndex = l_iIndex + (l_iLen - 1) 'if matching more than 1 char, need to move more than one char ahead to continue searching 
    End If 
    Next l_iIndex 
End Function 
相關問題