有没有人知道根据值数组过滤PT标签行的方法。我尝试了这个,但收到了一个错误:
运行时错误“5” - 无效的参数或过程调用
Sub test()
Dim PT As PivotTable
Dim PF As PivotField
Dim StrArr() As Variant
StrArr = Array("89905-0496", "89905-0497", "89907-0492", "89587-0499", "89585-0498")
Set PT = Sheet5.PivotTables(1)
Set PF = PT.PivotFields("[HFM LEDGER ACCOUNTS].[CONCATENATED ACCOUNT].[CONCATENATED ACCOUNT]")
PF.ClearLabelFilters
PF.PivotFilters.Add2 Type:=xlCaptionEquals, Value1:=StrArr
End Sub
答案 0 :(得分:1)
这是我最接近的方法,它是UGLY!但是有效:
尝试使用此示例数据:
Name Number
lol 2
cheese 2
foo 6
ball 5
lol 5
cheese 3
使用样本数据创建一个数据透视表,该数据将对每个“名称”的数字进行求和
假设您想要在数据透视字段“名称”中过滤“foo”和“lol”值。
以下是代码:
Option Explicit
Sub add_filters_to_pivot()
Dim filters As Variant
Dim pivot_field As PivotItem
Dim pivot_filter As String
Dim element As Variant
Dim filter_exist As Boolean
filters = Array("foo", "lol")
ActiveSheet.PivotTables("PivotTable1").PivotFields("Name").ClearAllFilters
For Each pivot_field In ActiveSheet.PivotTables("PivotTable1").PivotFields("Name").PivotItems
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Name")
pivot_filter = pivot_field
filter_exist = filter_array(filters, pivot_filter)
If filter_exist <> True Then
.PivotItems(pivot_filter).Visible = False
End If
End With
Next pivot_field
End Sub
Public Function filter_array(array_to_filter As Variant, filter_string As String) As Boolean
Dim filtered_array As Variant
Dim i As Integer
filtered_array = Filter(array_to_filter, filter_string, True, vbTextCompare)
On Error GoTo is_false
For i = 0 To (UBound(filtered_array) + 1)
If filtered_array(i) = filter_string Then
filter_array = True
Exit Function
End If
Next i
is_false:
filter_array = False
End Function
答案 1 :(得分:0)
如果您的数据透视表基于OLAP,那么您可以在一个分配中过滤数组上的数据透视表。这非常方便,因为您可以为这样的数据透视表提供您想要保留的数组,或者您希望过滤掉的数组。见Pivot Table filter out only 1 option
很容易使您的数据透视表成为OLAP类型......只需在最初创建数据透视表时选择“添加到数据模型”。换句话说,Power Pivot PivotTables是OLAP数据透视表。
如果你有一个'普通'数据透视表,那么你需要迭代它。执行此操作时存在许多潜在的瓶颈,如果您不对它们进行编码,则可能需要几分钟来迭代PivotField,其中只有20,000个PivotItems。请参阅我在http://dailydoseofexcel.com/archives/2013/11/14/filtering-pivots-based-on-external-ranges/的帖子,了解有关注意事项的更多信息,然后在以下链接中查看我的答案: