这里有一个提供您所需功能的VBA宏。
- 使用字典对象测试唯一性
- 在字典中进行计数
- 然后对结果进行排序
请仔细阅读代码中的注释以了解需要做出的假设和需要设置的引用。同时,注意标点符号可能会导致同一个单词被计入不同的类别。如果这可能是个问题,我们只需要以不同的方式拆分源数据,例如在拆分空格之前消除所有标点符号,或者使用正则表达式进行拆分。
'Set Reference to Microsoft Scripting Runtime
Option Explicit
Sub UniqueWordCounts()
Dim wsSrc As Worksheet, wsRes As Worksheet
Dim rSrc As Range, rRes As Range
Dim vSrc As Variant, vRes As Variant
Dim vWords As Variant
Dim dWords As Dictionary
Dim I As Long, J As Long
Dim V As Variant, vKey As Variant
'Assume source data is in column 1, starting at A1
' Could easily be anyplace
Set wsSrc = Worksheets("sheet2")
With wsSrc
Set rSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
'Results to go a few columns over
Set wsRes = Worksheets("sheet2")
Set rRes = rSrc(1, 1).Offset(0, 2)
'Read source data into vba array (for processing speed)
vSrc = rSrc
'Collect individual words and counts into dictionary
Set dWords = New Dictionary
dWords.CompareMode = TextCompare
For I = 1 To UBound(vSrc, 1)
'Split the sentence into individual words
For Each vKey In Split(vSrc(I, 1))
If Not dWords.Exists(vKey) Then
dWords.Add Key:=vKey, Item:=1
Else
dWords(vKey) = dWords(vKey) + 1
End If
Next vKey
Next I
'Size results array
ReDim vRes(0 To dWords.Count, 1 To 2)
'Column headers
vRes(0, 1) = "Word"
vRes(0, 2) = "Count"
'Populate the columns
I = 0
For Each V In dWords.Keys
I = I + 1
vRes(I, 1) = V
vRes(I, 2) = dWords(V)
Next V
'Size results range
Set rRes = rRes.Resize(UBound(vRes, 1) + 1, UBound(vRes, 2))
'Populate, format and sort the Results range
With rRes
.EntireColumn.Clear
.Value = vRes
With .Rows(1)
.Font.Bold = True
.HorizontalAlignment = xlCenter
End With
.EntireColumn.AutoFit
.Sort key1:=.Columns(2), order1:=xlDescending, key2:=.Columns(1), order2:=xlAscending, MatchCase:=False, Header:=xlYes
End With
End Sub
^p
"(段落标记)替换非单词字符,然后将其粘贴回Excel以获取单词列。 - Slai