我有下面的VB代码
Sub CountWordFrequencies()
Dim InputSheet As Worksheet
Dim WordListSheet As Worksheet
Dim PuncChars As Variant, x As Variant
Dim i As Long, r As Long, b As Long
Dim txt As String
Dim wordCnt As Long
Dim AllWords As Range
Dim PC As PivotCache
Dim PT As PivotTable
Dim PF As PivotField
Application.ScreenUpdating = False
Set InputSheet = ActiveSheet
Set WordListSheet = Worksheets.Add(after:=Worksheets(Sheets.Count))
WordListSheet.Range("A1").Font.Bold = True
WordListSheet.Range("A1") = "All Words"
InputSheet.Activate
wordCnt = 2
PuncChars = Array(".", ",", ";", ":", "'", "!", "#", _
"$", "%", "&", "(", ")", " - ", "_", "--", "+", _
"=", "~", "/", "\", "{", "}", "[", "]", """", "?", "*")
r = 2
Dim NotRealWord As Variant
NotRealWord = Array("OF","THE")
Do While Cells(r, 1) <> ""
txt = UCase(Cells(r, 1))
For i = 0 To UBound(PuncChars)
txt = Replace(txt, PuncChars(i), "")
Next i
txt = WorksheetFunction.Trim(txt)
x = Split(txt)
For i = 0 To UBound(x)
WordListSheet.Cells(wordCnt, 1) = x(i)
wordCnt = wordCnt + 1
Next i
r = r + 1
Loop
WordListSheet.Activate
Set AllWords = Range("A1").CurrentRegion
Set PC = ActiveWorkbook.PivotCaches.Add _
(SourceType:=xlDatabase, _
SourceData:=AllWords)
Set PT = PC.CreatePivotTable _
(TableDestination:=Range("C1"), _
TableName:="PivotTable1")
With PT
.AddDataField .PivotFields("All Words")
.PivotFields("All Words").Orientation = xlRowField
.PivotFields("All Words") _
.AutoSort xlDescending, "Count of All Words"
End With
Set PF = ActiveSheet.PivotTables("PivotTable1").PivotFields("All Words")
With PF
.ClearManualFilter
.EnableMultiplePageItems = True
For b = LBound(NotRealWord) To UBound(NotRealWord)
.PivotItems(NotRealWord(b)).Visible = False
Next b
End With
End Sub
这是一个词频分析功能,用户将在 A 列中插入字符串列表,从 A2 开始。他们将单击运行此脚本的按钮。然后,该脚本会将字符串分解为单个单词并创建一个数据透视表,该表将计算每个单词的频率,按频率排序。
以下是显示机制的图片:
结果
现在我的过滤器有问题。最终,我希望数据透视表自动过滤掉“NotRealWord”数组中的单词列表,因为这些单词对分析没有用处。我的代码只有在脚本可以在被分解的单词中找到数组列表中的所有值时才有效。所以在我的例子中,我设置了 NotRealWord = Array("OF", "THE") 并且数据透视表字段确实有这些词,所以它工作得很好。但是如果我添加了“BY”,它会返回此错误“无法获取 PivotField 类的 PivotItems 属性”。我该如何解决?
或者甚至更好,我怎样才能使 NotRealWord 成为一个动态数组,它采用列 F 中的值列表,以便用户可以添加更多他们想要过滤掉的单词,而无需修复代码(我的第一张图片也显示F) 列。
请注意,我不太擅长 VB。我知道如何阅读和适应复杂的代码,但不知道 FB 字的进出