我想排除数据透视表过滤器上的项目。
我的过滤器出现错误。对于这个我得到
错误 1004“无法获取数据透视表类的 Pivotfields 属性
我还想添加一个功能,首先选择过滤器中的所有项目,然后排除多个项目。
Sub ExcludeItemsFromFilter()
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
'Set the pivot table object
Set pt = ActiveSheet.PivotTables("PivotTable3")
'Set the pivot field object
Set pf = pt.PivotFields("Headquarter") '**ERROR ON THIS LINE**
'Loop through all the pivot items in the pivot field object
For Each pi In pf.PivotItems
If pi.Name = "Applied Materials, Austin (58460)" Or pi.Name = "Applied Materials, Inc., Dallas (33741)" Then
pi.Visible = False 'Exclude the item from the filter
End If
Next pi
End Sub
我也尝试过这个,我明白了
错误 438“对象不支持此属性或方法”。
Sub ExcludeItemsFromBICubeFilter()
Dim objCube As Object
Dim objFilter As Object
Dim strFilterName As String
Dim strItemName As String
'Set the filter name and item names to exclude
strFilterName = "Headquarter"
strItemName = "Applied Materials, Austin (58460)"
'Set the cube object
Set objCube = ActiveSheet.PivotTables("PivotTable3")
'Set the filter object
Set objFilter = objCube.Filters(strFilterName) '**ERROR ON THIS LINE**
'Exclude the specified item from the filter
objFilter.Members(strItemName).Exclude = True
End Sub
由于您将
pt
设置为 ActiveSheet.PivotTables("PivotTable3")
,请确保运行宏时您位于带有 PivotTable3
的工作表上,否则您将收到错误 1004。
我创建了一个干净的工作簿,其中包含一个非常简单的数据表(如下),插入一个数据透视表(重命名为 PivotTable3 以匹配您的代码),然后按原样运行您的第一个代码(除了在出现错误的行中添加撇号之外)分隔评论)。一切都按预期工作 - 如果上述提示不起作用,您可以尝试相同的方法并查看是否是您的代码或工作簿的问题?
数据表:
结果:
代码:
Sub ExcludeItemsFromFilter()
Dim ws as Worksheet
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
'Set worksheet object
Set ws = Sheets("your_sheet_with_pivotttable3") 'replace with your sheet name
'Set the pivot table object
Set pt = ws.PivotTables("PivotTable3")
'Set the pivot field object
Set pf = pt.PivotFields("Headquarter") ' **ERROR ON THIS LINE**
'Loop through all the pivot items in the pivot field object
For Each pi In pf.PivotItems
If pi.Name = "Applied Materials, Austin (58460)" Or pi.Name = "Applied Materials, Inc., Dallas (33741)" Then
pi.Visible = False 'Exclude the item from the filter
End If
Next pi
End Sub