问题
I need to create a list of words used in all cells in column A, with a count of occurrence for each word on the list.
So far, I've been able to create the list of words. (by searching the forum.) The list of words is generated in column B, can anyone help me with the code so it also generate the count of occurrence in column C?
Thank you!
Sub Sample()
Dim varValues As Variant
Dim strAllValues As String
Dim i As Long
Dim d As Object
'Create empty Dictionary
Set d = CreateObject("Scripting.Dictionary")
'Create String With all possible Values
strAllValues = Join(Application.Transpose(Range("A1", Range("A" & Rows.Count).End(xlUp))), " ")
strAllValues = Replace(strAllValues, ".", "")
strAllValues = Replace(strAllValues, ",", "")
strAllValues = Replace(strAllValues, "!", "")
strAllValues = Replace(strAllValues, "?", "")
strAllValues = Application.WorksheetFunction.Trim(strAllValues)
'Split All Values by space into array
varValues = Split(strAllValues, " ")
'Fill dictionary with all values (this filters out duplicates)
For i = LBound(varValues) To UBound(varValues)
d(varValues(i)) = 1
Next i
'Write All The values back to your worksheet
Range("B1:B" & d.Count) = Application.Transpose(d.Keys)
End Sub
回答1:
I'll just deal with the unique list and count.
...
'Fill dictionary with all values (this filters out duplicates)
For i = LBound(varValues) To UBound(varValues)
d.item(varValues(i)) = d.item(varValues(i)) + 1
Next i
'Write All The values back to your worksheet
Range("B1").resize(d.count, 1) = Application.Transpose(d.Keys)
Range("C1").resize(d.count, 1) = Application.Transpose(d.items)
来源:https://stackoverflow.com/questions/52978539/excel-vba-counting-word-occurence-while-creating-list-of-words