【发布时间】:2018-07-24 23:18:00
【问题描述】:
我有一个数据透视表,并且我创建了一个用户窗体,它应该允许用户选择某些过滤选项。我想根据用户输入根据链接到列的各种条件过滤行。但是,我似乎无法让它过滤多个值过滤器上的行。这在前端似乎也不可能,但我仍然希望 VBA 能找到方法。
这就是相关代码(在用户窗体的 OK 按钮后面)的开始方式:
'ok button - this is the big one, telling the button what to do with the selected options!
Private Sub CommandButton1_Click()
'targeting our familiar pivot table
Dim pvt As PivotTable
Set pvt = Sheets("Summary").PivotTables("PivotTable1")
'allowing multiple filters to be used at once
pvt.AllowMultipleFilters = True
'and identifying the row that we want to filter - n.b. this would need to change if corporate wanted to use another field as their lowest level row.
Dim pvtFieldBrand As PivotField
Set pvtFieldBrand = pvt.PivotFields("final brand")
'clearing any filters already set
pvtFieldBrand.ClearAllFilters
然后是过滤器。
这个单独工作:
'Filtering depending on whether 1+, 2+ or all 3 audiences favour it
Dim pvtFieldNoAud As PivotField 'then hide the column - at the top of this script, in fact, just in case it's not already hidden
Set pvtFieldNoAud = pvt.PivotFields("Sum of # Audiences")
If OptionButton3 = True Then
pvtFieldBrand.PivotFilters.Add2 Type:=xlValueIsBetween, DataField:=pvtFieldNoAud, Value1:=1, Value2:=3
End If
If OptionButton4 = True Then
pvtFieldBrand.PivotFilters.Add2 Type:=xlValueIsBetween, DataField:=pvtFieldNoAud, Value1:=2, Value2:=3
End If
If OptionButton5 = True Then
pvtFieldBrand.PivotFilters.Add2 Type:=xlValueEquals, DataField:=pvtFieldNoAud, Value1:=3
End If
然后是这些过滤器,我打算将它们作为多选选项,但它们只能在完全隔离的情况下工作 - 不能相互组合,也不能与任何其他过滤器组合:
'Only show if favoured by the selected audiences
Dim pvtFieldWW As PivotField
Set pvtFieldWW = pvt.PivotFields("Sum of WW overindex?")
Dim pvtFieldUU As PivotField
Set pvtFieldUU = pvt.PivotFields("Sum of UU overindex?")
Dim pvtFieldRR As PivotField
Set pvtFieldRR = pvt.PivotFields("Sum of RR overindex?")
If CheckBox1 = True Then
pvtFieldBrand.PivotFilters.Add2 Type:=xlValueIsGreaterThan, DataField:=pvtFieldWW, Value1:=0
End If
If CheckBox2 = True Then
pvtFieldBrand.PivotFilters.Add2 Type:=xlValueIsGreaterThan, DataField:=pvtFieldUU, Value1:=0
End If
If CheckBox3 = True Then
pvtFieldBrand.PivotFilters.Add2 Type:=xlValueIsGreaterThan, DataField:=pvtFieldRR, Value1:=0
End If
等等。
我需要用户能够以多达 6 种方式过滤此数据透视表。它可能可以使用前端的切片器和报告过滤器来完成,但我想限制用户的选项和用户错误的可能性,所以我计划将所有相关选项保留在用户窗体中,然后锁定一些功能,以便他们无法对数据透视表进行任何其他更改。任何想法都非常感谢!
【问题讨论】:
-
哦 - 我收到的错误消息是“运行时错误 1004 - 应用程序定义的或对象定义的错误”。它位于代码中代表调用的第二个过滤器的任何一行。
-
您不能将多个值过滤器应用于同一字段,即使在 VBA 中也是如此。 AllowMultipleFilters 设置允许您对同一字段应用多种类型的过滤器,但同一类型的过滤器不能超过一种。
-
啊,谢谢您的确认。如果有人阅读有兴趣,我想我接下来要尝试的是使用 VBA 过滤源数据,然后将可见单元格复制并粘贴到新选项卡,然后从该选项卡创建数据透视表(如在这里建议(不是我的问题):experts-exchange.com/questions/24325164/…)。以前没有做过,但我会记录一些宏,看看我是否可以将它们拼接在一起。
-
很高兴报告我上述评论中的方法绝对有效! :-)
标签: vba excel filter pivot-table