如何计算字符串在VBA中的另一个字符串中出现的次数?

时间:2014-07-22 09:48:01

标签: vba ms-access ms-access-2010

如何计算Access VBA中另一个字符串出现在另一个字符串中的次数?例如,我如何计算“快速的棕色狐狸跳过懒狗”发生了多少次“?”?

5 个答案:

答案 0 :(得分:4)

你对子串/区分大小写没问题

matches = (len(lookin) - len(replace$(lookin, find, ""))) / len(find)

答案 1 :(得分:2)

您可以使用更少的变量来简化功能,并通过以下功能避免使用For。

Public Function getOccuranceCount(Expression As String, Find As String) As Long
'*******************************************************************************
'Code Courtesy of
'  Paul Eugin
'
'   Input  - Expression, the String to check
'            Find, the String pattern to be checked for
'   Output - The number of occurance of the Find String in the Expression String
'   Usage  - getOccuranceCount("The quick brown fox jumped over the lazy dog.","saw")
'               0
'            getOccuranceCount("The quick brown fox jumped over the lazy dog.","the")
'               2
'*******************************************************************************
On Error GoTo errDisplay
    Dim strArr() As String, i As Long
    strArr = Split(Expression, Find)
    getOccuranceCount = UBound(strArr)

errExit:
    Exit Function
errDisplay:
    MsgBox "The following error has occured while trying to get the count." & vbCrLf & vbCrLf & _
           "Error (" & Err.Number & ") - " & Err.Description, vbCritical, "Contact the DB Admin."
Resume errExit
End Function

该函数会将其拆分为数组,然后您需要的只是边界计数。希望这可以帮助。

答案 2 :(得分:1)

Dim lookin As String
Dim tofind As String
lookin = "The quick brown fox jumps over the lazy dog."
tofind = "the "

Dim r As Object, matches
Set r = CreateObject("VBScript.RegExp")

r.Pattern = tofind
r.IgnoreCase = True
r.Multiline = False
r.Global = True
Set matches = r.Execute(lookin)

匹配找到两个匹配。一个在索引= 0,一个在索引= 31。

答案 3 :(得分:0)

您可以使用此功能,它使用InStr:

Function CountStringOccurances(strStringToCheck As String, strValueToCheck As String) As Integer
'Purpose: Counts the number of times a string appears in another string.
On Error GoTo ErrorMessage
    Dim intStringPosition As Integer
    Dim intCursorPosition As Integer
    CountStringOccurances = 0
    intCursorPosition = 1
    For i = 0 To Len(strStringToCheck)
        intStringPosition = InStr(intCursorPosition, strStringToCheck, strValueToCheck)
        If intStringPosition = 0 Then
            Exit Function
        Else
            CountStringOccurances = CountStringOccurances + 1
            intCursorPosition = intStringPosition + Len(strValueToCheck)
        End If
    Next i
    Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function

该函数返回值在字符串中的位置。如果该值为0,则退出并返回该号码。如果它返回一个正值(并且如果该值存在则它将会出现),则它会在出现次数上加一,然后再次检查,将其起始位置移动到刚出现的位置之后。此函数不区分大小写。

使用上面的例子:

CountStringOccurances("The quick brown fox jumped over the lazy dog.","the")

将返回2.

答案 4 :(得分:0)

您可以在与this question相同的解决方案中使用Split。这是迄今为止我见过的最整洁的解决方案。