怎样取得一个字符串在另外一个字符串中出现的次数?
一个简单的函数,VBA中没有,我们可以用几种方法来实现,一般是使用循环来数数字,我们也可以使用 REPLACE 的特性结合 LEN 函数计算来计算出现次数。相对来说使用 REPLACE 代码更少。
问题:
怎样取得一个字符串在另外一个字符串中出现的次数?
方法一:
Function strCount(strA As String, strB As String) As Long
Dim lngA As Long
Dim lngB As Long
Dim lngC As Long
lngA = Len(strA)
lngB = Len(strB)
lngC = Len(Replace(strA, strB, ""))
strCount = (lngA - lngC) / lngB
End Function
方法二:
Public Function sCount(String1 As String, String2 As String) As Integer
Dim I As Integer, iCount As Integer
I = 1
Do
If (I > Len(String1)) Then Exit Do
I = InStr(I, String1, String2, vbTextCompare)
If I Then
iCount = iCount + 1
I = I + 2
DoEvents
End If
Loop While I
sCount = iCount
End Function