微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用动态数组过滤数据透视表的 VBA

如何解决使用动态数组过滤数据透视表的 VBA

我有下面的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 开始。他们将单击运行此脚本的按钮。然后脚本会将字符串分解为单个单词并创建一个数据透视表,该表将计算每个单词的频率,并按频率排序。

以下是显示机制的图片

  • 来自 A 列的用户输入

    enter image description here

  • 结果

    enter image description here

结果

现在我的过滤器有问题。最终,我希望数据透视表自动过滤掉“NotRealWord”数组中的单词列表,因为这些不是要分析的有用单词。我的代码仅在脚本可以在被分解的单词中找到数组列表中的所有值时才起作用。所以在我的例子中,我设置了 NotRealWord = Array("OF","THE") 并且数据透视表字段确实有这些词,所以它完美地工作。但是如果我添加了“BY”,它会返回这个错误“无法获取 PivotField 类的 PivotItems 属性”。我该如何解决这个问题?

或者更好的是,我怎样才能使 NotRealWord 成为一个动态数组,它采用假设列 F 中的值列表,以便用户可以添加更多他们想要过滤掉的单词而无需修复代码(我的第一个图片显示了F列)。

请注意,我并不擅长 VB。我知道如何阅读和改编复杂的代码,但不知道FB字的进出

解决方法

这是一种可能的方法,它与您当前的方法略有不同,但应该可以满足您的需求:

read()

正则表达式参考:https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/scripting-articles/ms974570(v=msdn.10)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。