簡體   English   中英

計算字符串中特定值的出現次數

[英]Count number of occourences of specific values in a string

我有多行,其中一些單詞由分號(;)分隔,並且需要計算某個單詞出現在 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

這段代碼的問題是它無法識別第二行中“香蕉”的 2 次出現,返回的計數是 2 而不是 3:

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

我看到問題是 InStr 只能識別字符串是否存在,但我該如何克服呢?


解決方案:

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

對於 basodre 的代碼,我只需要更改“;”中的分隔符到“;”(分號后有一個空格)以匹配我的字符串。

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

Алексей 的答案也很完美,但在此編輯時僅限於 Excel 2019 或更高版本,因為它使用“TEXTJOIN”function,而我無法找到替代品。

這是一個我認為可以滿足您需要的示例。 請查看,修改您的范圍,並讓我們知道它是否有效。

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

正則表達式的解決方案:

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  

使用正則表達式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM