计算字符串中特定值出现的次数

时间:2021-05-19 16:39:39

标签: excel vba

我有多行,有些单词用分号(;)分隔,需要计算某个单词在 Sheet1 的 A 列单元格字符串中出现的次数。

以两行为例:

Column "A"
Banana; Apple; Orange
Banana; Banana; Apple

我想出了这个代码来计算我想计算的特定单词:

Sub count()

'The count will be registered in "B6"

strcount = "Banana"

For i = 2 to 30
    If InStr(Sheets("Sheet1").Cells(i, "A").Text, strcount) <> 0 Then
     
       Cells(6, "B").Value = Cells(6, "B").Value + 1

    End If
Next i

End Sub

此代码的问题在于它无法识别第二行中 "Banana" 的 2 次出现,返回的计数为 2 而不是 3:

Results for each fruit:
Banana: 2
Apple: 2
Orange: 1

我发现问题是 InStr 只识别字符串是否存在,但我该如何克服这个问题?


解决方案:

basodre 和 Алексей 的回答都有效。

对于 basodre 的代码,我只需要更改分隔符“;”到“;”(分号后有一个空格)以匹配我的字符串。

aFoods = Split(rIterator.Value, "; ")

Алексей 的回答也很完美,但到此编辑时仅限于 Excel 2019 或更高版本,因为它使用“TEXTJOIN”功能,我无法想出替代品。

3 个答案:

答案 0 :(得分:0)

这是一个我认为可以满足您需求的示例。请查看并修改您的范围,并让我们知道它是否有效。

Sub CountWords()
    Dim rng As Range
    Dim aFoods As Variant
    Dim rIterator As Range
    Dim counter As Long
    
    Const theFood As String = "Banana"
    
    Set rng = Range("A1:A3")
    
    counter = 0
    For Each rIterator In rng
        aFoods = Split(rIterator.Value, ";")
        
        For i = LBound(aFoods) To UBound(aFoods)
            If aFoods(i) = theFood Then
                counter = counter + 1
            End If
        Next i
    Next rIterator
    
    Debug.Print counter
End Sub

答案 1 :(得分:0)

正则表达式的解决方案:

Option Explicit

Sub test1()
    Dim re As Object, result As Object, text As String, fruit As Variant
    
    Set re = CreateObject("vbscript.regexp")
    re.Global = True
        
    text = WorksheetFunction.TextJoin(";", True, Columns("A"))
    'In Excel < 2019 you can use: text = Join(WorksheetFunction.Transpose(Intersect(Columns("A"), ActiveSheet.UsedRange)), ";")
    
For Each fruit In Array("Banana", "Apple", "Orange")
        re.Pattern = "\b" & fruit & "\b"
        Set result = re.Execute(text)
        Debug.Print "Amount of [" & fruit & "] = " & result.Count
    Next
End Sub

Output:  
Amount of [Banana] = 3  
Amount of [Apple] = 2  
Amount of [Orange] = 1  

答案 2 :(得分:0)

使用正则表达式

Sub FindEntries()
    Dim mc, rw
    Const word$ = "Banana"
    With CreateObject("VBScript.RegExp")
        .IgnoreCase = True: .Global = True: .Pattern = "(^|;\s+)" & word & "(?=;|$)"
        For rw = 2 To Cells(Rows.Count, "A").End(xlUp).Row
            Set mc = .Execute(Cells(rw, "A")): [B6] = [B6] + mc.Count
        Next
    End With
End Sub