您可能能够使用模块子过程收集有效的计数,该过程在内存数组中执行所有数学运算并将计数返回到工作表。
我使用了一些标准的Lorem Ipsum 关键字和短语来创建上述示例数据。
点击Alt+F11,当VBE打开时,立即使用下拉菜单插入►模块(Alt+I,M)。将以下内容粘贴到标题为 Book1 - Module1 (Code) 的新模块代码表中。
Option Explicit
Sub count_strings_inside_strings()
Dim rw As Long, lr As Long
Dim k As Long, p As Long, vKEYs As Variant, vPHRASEs As Variant, vCOUNTs As Variant
ReDim vKEYs(0)
ReDim vPHRASEs(0)
With Worksheets("Sheet1") '<~~ set to the correct worksheet name\
'populate the vKEYs array
For rw = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
vKEYs(UBound(vKEYs)) = LCase(.Cells(rw, 1).Value2)
ReDim Preserve vKEYs(UBound(vKEYs) + 1)
Next rw
ReDim Preserve vKEYs(UBound(vKEYs) - 1)
'populate the vPHRASEs array
For rw = 2 To .Cells(Rows.Count, 2).End(xlUp).Row
vPHRASEs(UBound(vPHRASEs)) = LCase(.Cells(rw, 2).Value2)
ReDim Preserve vPHRASEs(UBound(vPHRASEs) + 1)
Next rw
ReDim Preserve vPHRASEs(UBound(vPHRASEs) - 1)
ReDim vCOUNTs(0 To UBound(vPHRASEs))
'perform the counts
For p = LBound(vPHRASEs) To UBound(vPHRASEs)
For k = LBound(vKEYs) To UBound(vKEYs)
vCOUNTs(p) = CInt(vCOUNTs(p)) + _
(Len(vPHRASEs(p)) - Len(Replace(vPHRASEs(p), vKEYs(k), vbNullString))) / Len(vKEYs(k))
Next k
Next p
'return the counts to the worksheet
.Cells(2, 3).Resize(UBound(vCOUNTs) + 1, 1) = Application.Transpose(vCOUNTs)
'run the helper procedure to Blue|Bold all of the found keywords within the phrases
Call key_in_phrase_helper(vKEYs, .Range(.Cells(2, 2), .Cells(Rows.Count, 2).End(xlUp)))
End With
End Sub
Sub key_in_phrase_helper(vKYs As Variant, rPHRSs As Range)
Dim p As Long, r As Long, v As Long
With rPHRSs
For r = 1 To rPHRSs.Rows.Count
.Cells(r, 1) = .Cells(r, 1).Value2
For v = LBound(vKYs) To UBound(vKYs)
p = 0
Do While CBool(InStr(p + 1, .Cells(r, 1).Value2, vKYs(v), vbTextCompare))
p = InStr(p + 1, .Cells(r, 1).Value2, vKYs(v), vbTextCompare)
Debug.Print vKYs(v)
With .Cells(r, 1).Characters(Start:=p, Length:=Len(vKYs(v))).Font
.Bold = True
.ColorIndex = 5
End With
Loop
Next v
Next r
End With
End Sub
您可能必须重命名要在第 5th 代码行中处理的工作表。我还包含了一个帮助程序,它使用 Blue|Bold 字体识别短语中的关键词。如果不需要,注释掉或删除第一个子过程底部的Call key_in_phrase_helper(...) 行。
点击 Alt+Q 返回您的工作表。点击Alt+F8打开Macros对话框和Run子程序。如果您的数据与我汇总的示例数据相似,那么您应该得到类似的结果。
¹ 这些是一些高级方法,但我认为它们也是解决您的问题的最佳方法。如果您有具体问题而您自己的研究没有充分解释,我会尝试在评论部分解决这些问题。我为创建此解决方案而创建的示例工作簿可应要求提供。