如何使用Excel VBA宏查找字符串中正斜杠字符(/)的出现次数?
答案 0 :(得分:35)
老问题,但我想我会在excel论坛上找到答案,从而增加答案的质量。显然,计数也可以使用。
count =Len(string)-Len(Replace(string,"/",""))
答案的完全归功于原始作者:http://www.ozgrid.com/forum/showthread.php?t=45651
答案 1 :(得分:16)
使用以下功能,如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
答案 2 :(得分:13)
Function CountOfChar(str as string, character as string) as integer
CountOfChar = UBound(Split(str, character))
End Function
答案 3 :(得分:1)
顺便说一句,如果你进入表演,以下比使用拆分或替换确定计数快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
答案 4 :(得分:1)
我喜欢Santhosh Divakar的答案,因此我在其上进行了扩展,以解决可能要通过将结果除以搜索字符的长度来检查多个字符而不是单个字符的可能性,例如:
Function Num_Characters_In_String(Input_String As String, Search_Character As String) As Integer
'Returns the number of times a specified character appears in an input string by replacing them with an empty string
' and comparing the two string lengths. The final result is then divided by the length of the Search_Character to
' provide for multiple Search Characters.
Num_Characters_In_String = (Len(Input_String) - Len(Replace(Input_String, Search_Character, ""))) / Len(Search_Character)
End Function
例如,
的结果Num_Characters_In_String("One/Two/Three/Four//", "//")
为您提供1,因为句子的末尾只有一个双斜杠。
答案 5 :(得分:1)
如果您想同时兼顾性能和最少的内存使用,则“拆分”和“镜头/替换”解决方案都不是最佳选择。
这是我的建议
Public Function CountOf(ByRef s As String, ByRef substr As String, Optional ByVal compareMethod As VbCompareMethod = vbBinaryCompare) As Integer
Dim c As Integer
Dim idx As Integer
NEXT_MATCH:
idx = InStr(idx + 1, s, substr, compareMethod)
If idx > 0 Then
c = c + 1
GoTo NEXT_MATCH:
End If
CountOf = c + 1
End Function
这是性能,在一个简单案例和一个包含更多条目的案例中,每个选项运行1,000,000次:
5.828ms Empty Loop
s = '0,1,2,3,4,5,6,7,8,9', separator = ','
1.882s UBound(Split) algo
2.537s Len/Replace() algo
760.710ms CountOf()
s = '[ABC],long, longer,sdfgshttsdbghhgsssssshsdhhhhhhhhhhhh,,,,777777777777777777777777777777,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,LAST', separator = ','
18.330s UBound(Split) algo
21.743s Len/Replace() algo
9.544s CountOf()
因此,即使CountOf是一个函数调用,而Split和Len / Replace都直接在循环代码中,所以总体速度要快2到3倍。
还请注意,当项目数和项目长度增加时,性能比保持稳定,如下所示(测试仅进行1,000次迭代)
s ="[ABC],long,longer,sdfgshttsdbghhgsssssshsdhhhhhhhhhhhh,,,,777777777777777777777,Repeat(1000,"A...Z"),LAST', separator = ','
232.160ms UBound(Split): 1033
325.367ms Len/Replace(): 1033
113.658ms CountOf(): 1033
答案 6 :(得分:0)
这是VBA Excel宏的简单解决方案。
Function CharCount(str As String, chr As String) As Integer
CharCount = Len(str) - Len(Replace(str, chr, ""))
End Function
答案 7 :(得分:0)
这里是单行版本,当您不想调用单独的函数时可以使用。它只是CountChrInString和上面其他一些文件的压缩版本。
? UBound(Split("abcabcabc", "cd"), 1)
这将返回0。如果将“ cd”更改为“ ab”,则返回3。它也适用于变量。请注意,如果要检查的字符串(abcabc ...)为空,则它将返回-1。
答案 8 :(得分:0)
另一个不错的选择是使用RegExp。我在Microsoft Word中尝试了以下操作,但是我确定它在Excel中的效果大致相同。
在包含190,000个单词和2,400个三个字母的单词的Word文档中,以下功能对其进行计数平均需要0.938秒(我在其下包括一个Sub以便于显示时间):
Function RegExpCount(WholeString As String, Substring As String) As Long
Dim MatchCol As MatchCollection
With New RegExp
.Pattern = Substring
.Global = True
.IgnoreCase = False 'or True, depending on your needs
.MultiLine = False
Set MatchCol = .Execute(WholeString)
End With
RegExpCount = MatchCol.count
End Function
Sub CountInstances()
Dim StartTime As Double
Dim SecondsElapsed As Double
'Remember time when macro starts
StartTime = Timer
Dim Rng As Range
Set Rng = ActiveDocument.Range
Debug.Print "The number of times 'your substring' appears in this document is: " & RegExpCount(Rng.Text, "your substring")
'Calculate how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)
'Notify user in seconds
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation
End Sub
它总是正确输出2,400。 Alexis Martial的CountOf函数所花费的时间与Rick_R的UBound(Split)命令所花费的时间相同。它们在大约0.92-0.95秒内输出相同的计数。