2017-08-16 46 views
0

我有下面的代码,我试图让我的pivotfields数据透视表的一部分显示3个国家(法国,比利时和卢森堡)。每次更新表格时,国家/地区列表都会扩展和签订合同(但法国,比利时和卢森堡仍在使用)。Pivotfields multiple filter

'delete all filters for country 
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("countryName") 
    .ClearAllFilters 
    .CurrentPage = "FRANCE" 
    .PivotItems("BELGIUM").Visible = True 
    .PivotItems("LUXEMBOURG").Visible = True 

    End With 

这不起作用,还有现在的代码问题出现的,但比利时和卢森堡不会出现过滤列表

任何人都可以在这方面帮助的(错误)?

+0

您当前的方法使用.CurrentPage属性,它是唯一相关,如果a)您透视字段是PageField(即出现在数据透视表字段列表的过滤器面板)和b)如果“选择多个项目”该字段下拉菜单中的选项未被选中。 PageField属性用于设置数据透视表以仅显示一个PivotItem。您不能使用它来显示多个项目。 – jeffreyweir

+0

您可以确认PivotTable中PivotFIeld的位置?即它在“过滤器”区域还是“行或列”区域? – jeffreyweir

回答

1

此代码应该做你需要的。要了解有关快速过滤数据透视表的更多信息,请查看我的blogpost on the subject

Option Explicit 

Sub FilterPivot() 
Dim pt As PivotTable 
Dim pf As PivotField 
Dim pi As PivotItem 
Dim i As Long 
Dim vItem As Variant 
Dim vCountries As Variant 

Set pt = ActiveSheet.PivotTables("PivotTable1") 
Set pf = pt.PivotFields("CountryName") 

vCountries = Array("FRANCE", "BELGIUM", "LUXEMBOURG") 

pt.ManualUpdate = True 'Stops PivotTable from refreshing after each PivotItem is changed 

With pf 

    'At least one item must remain visible in the PivotTable at all times, so make the first 
    'item visible, and at the end of the routine, check if it actually *should* be visible   
    .PivotItems(1).Visible = True 

    'Hide any other items that aren't already hidden. 
    'Note that it is far quicker to check the status than to change it. 
    ' So only hide each item if it isn't already hidden 
    For i = 2 To .PivotItems.Count 
     If .PivotItems(i).Visible Then .PivotItems(i).Visible = False 
    Next i 

    'Make the PivotItems of interest visible 
    On Error Resume Next 'In case one of the items isn't found 
    For Each vItem In vCountries 
     .PivotItems(vItem).Visible = True 
    Next vItem 
    On Error GoTo 0 

    'Hide the first PivotItem, unless it is one of the countries of interest 
    On Error Resume Next 
    If InStr(UCase(Join(vCountries, "|")), UCase(.PivotItems(1))) = 0 Then .PivotItems(1).Visible = False 
    If Err.Number <> 0 Then 
     .ClearAllFilters 
     MsgBox Title:="No Items Found", Prompt:="None of the desired items was found in the Pivot, so I have cleared the filter" 
    End If 
    On Error GoTo 0 

End With 

pt.ManualUpdate = False 

End Sub 
+0

非常感谢这个,我完全无法得到这个工作,代码没有任何错误,它看起来不错,但结果是,列表中的所有国家仍然被选中(除了第一个,其中我看到的是在代码中计划) – Ollie

+0

实际上刚刚解决了这个 – Ollie

+0

PivotItems(i).Visible = False – Ollie