【问题标题】:Pivotfields multiple filterPivotfields 多重过滤器
【发布时间】:2017-09-22 07:04:39
【问题描述】:

我有下面的代码,我试图让我的数据透视表的数据透视表部分显示 3 个国家(法国、比利时和卢森堡)。每次更新表格时,国家列表都会扩展和收缩(但法国、比利时和卢森堡仍然存在)。

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

  End With

这不起作用,现在出现的代码有问题(错误),但比利时和卢森堡没有出现在过滤列表中

有人可以帮忙吗?

【问题讨论】:

  • 您当前的方法使用 .CurrentPage 属性,该属性仅在以下情况下相关:a)您的数据透视字段是 PageField(即出现在数据透视表字段列表的过滤器窗格中)和 b)如果“选择多个未选中字段下拉列表中的“项目”选项。 PageField 属性用于将数据透视表设置为仅显示一个数据透视项。您不能使用它来显示多个项目。
  • 您能确认 PivotFIeld 在数据透视表中的位置吗?即它是在过滤器区域,还是在行或列区域?

标签: excel pivot-table vba


【解决方案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

【讨论】:

  • 非常感谢,我不能让它工作,代码没有任何错误,对我来说看起来不错,但结果是列表中的所有国家仍然被选中(除了第一个,我看到在代码中计划)
  • .PivotItems(i).Visible = False
  • 我知道你说这需要更长的时间,但无论如何都可以,非常感谢,你最近帮了我很多忙
  • 没问题。您能否详细说明 ".PivotItems(i).Visible = False" 的含义?您能否详细说明 PivotFIeld 在数据透视表中的位置?即它是在过滤器区域,还是在行或列区域?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
相关资源
最近更新 更多