我正在尝试计算从第2行开始的AJ列中每一行中此短语“SMM:”的出现次数,然后从第2行开始将每行的值赋值给列BL。
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
答案 0 :(得分:2)
对于完全匹配,您应该使用" vbBinaryCompare"。如果你想匹配" smm:"与" SMM:"那么你应该使用" vbTextCompare"。试试这个:
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
答案 1 :(得分:2)
此函数通过计算使用子字符串拆分字符串中的元素数来获取计数。
Function getStrOccurenceCount(Text As String, SubString As String)
getStrOccurenceCount = UBound(Split(Text, SubString))
End Function
您可以像这样修改您的代码
工作表(&#34; pptsr&#34;)。范围(&#34; BL2&#34;&amp; f).Value = getStrOccurenceCount(cellCheck.Text,&#34; SMM:&#34;)< / p>
以下是如何使用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秒: