如何從VBA Excel宏中的字符串中找到(/)字符出現次數。如何從字符串查找斜槓發生次數
9
A
回答
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
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
相關問題
- 1. 從斜槓查找字符串到空格或字符
- 2. 如何用斜槓分割字符串
- 3. ereg_replace - 字符串斜槓
- 4. 構建字符串斜槓
- 5. 如何從字符串中將重複的「斜槓」替換爲單斜槓?
- 6. 如何從字符串中將反斜槓替換爲單個反斜槓?
- 7. Ç查找字符串斜
- 8. 在字符串中查找反斜槓(\)--Python
- 9. JavaScript查找字符串是否以正斜槓結尾
- 10. Javascript:在字符串中查找斜槓(/)的索引
- 11. 如何編碼包含正斜槓的查詢字符串?
- 12. 自定義字符串格式0,0斜槓或反斜槓
- 13. Windows shell字符串操作(將反斜槓改爲斜槓)
- 14. 反斜槓在字符串返回兩個反斜槓
- 15. 如何從PHP查詢頁面將包含反斜槓和前斜槓的字符串傳回JavaScript使用AJAX
- 16. Ruby:如何從字符串中刪除尾部反斜槓?
- 17. 如何從字符串中刪除重複反斜槓
- 18. 如何從我的字符串中刪除正斜槓?
- 19. 如何從字符串中替換反斜槓和空格
- 20. 如何從字符串中刪除\(反斜槓)?
- 21. 如何從字符串中刪除斜槓?
- 22. 如何從C中的字符串中刪除斜槓
- 23. 如何從字符串去除正斜槓
- 24. 如何從JSON字符串中刪除反斜槓?
- 25. 從查詢字符串中刪除尾部斜槓Apache
- 26. 我應該如何將包含斜槓的字符串與單斜槓分開?
- 27. 如何在PHP中比較字符串並忽略斜槓和反斜槓
- 28. 如何用Emacs Lisp中的字符串中的反斜槓替換正斜槓?
- 29. 如何使用字符串#拆分反斜槓字符?
- 30. 如何替換Java字符串中的反斜槓字符
不匈牙利命名法的忠實粉絲,但由於對於增加的評論:-) – assylias 2012-02-13 14:12:17