How to count the number of events for a row in a cell?

I am trying to calculate the number of cases for this phrase “SMM:” on each row in column AJ starting at row 2, and then assigning a value for each row to column BL starting at row 2.

Sub calculateamlp()


Dim charactercount As Integer
Dim rangeAG As Range
Dim cellCheck As Range
Dim f As Integer
f = 2
 Worksheets("pptsr").Activate

Set rangeAG2 = Range("BL2", Range("BL2").End(xlDown))
Set rangeAG = Range("Aj2", Range("Aj2").End(xlDown))
For Each cellCheck In rangeAG

        charactercount = Len(cellCheck) - Len(WorksheetFunction.Substitute(cellCheck, ":", ""))


        Worksheets("pptsr").Range("BL2" & f).Value = charactercount

   f = f + 1
Next cellCheck

End Sub
+4
source share
2 answers

For exact match you should use "vbBinaryCompare". If you want to combine "smm:" with "SMM:", then you should use "vbTextCompare". Try the following:

Sub calculateamlp()
Dim count As Long, i As Long, j As Long, rw As Long
Dim ws As Worksheet
Set ws = Worksheets("pptsr")
With ws
    rw = .Range("AJ" & .Rows.count).End(xlUp).Row
    For i = 2 To rw
        For j = 1 To Len(.Cells(i, "AJ"))
            If InStr(j, .Cells(i, "AJ"), "SMM:", vbTextCompare) Then
                count = count + 1
                j = InStr(j, .Cells(i, "AJ"), "SMM:", vbTextCompare)
            End If
        Next j
        .Cells(i, "BL") = count
        count = 0
    Next
End With
End Sub
+2
source

This function gets the count by counting the number of elements in the Split String section using a substring.

Function getStrOccurenceCount(Text As String, SubString As String)
    getStrOccurenceCount = UBound(Split(Text, SubString))
End Function

You can change your code as follows

( "pptsr" ). ( "BL2" f).Value = getStrOccurenceCount (cellCheck.Text, "SMM:" )

getStrOccurenceCount .

Sub calculateamlp2()
    Const SUBSTRING As String = "SMM:"
    Dim rangeAG As Range
    Dim data As Variant
    Dim x As Long

    Set rangeAG = Range("AJ2", Range("AJ2").End(xlDown))

    data = rangeAG.Value

    For x = 1 To UBound(data)
        data(x, 1) = getStrOccurenceCount(CStr(data(x, 1)), SUBSTRING)
    Next

    rangeAG.EntireRow.Columns("BL").Value = data
End Sub

: 999,999 , 0.9375 :

enter image description here

+2

Source: https://habr.com/ru/post/1683045/


All Articles