如何从 VBA 代码或公式访问 Excel Pivot table 中选定的报表过滤器值?

How can I access selected report filter values in Excel Pivot table from VBA code or Formulas?

我有一个带报表过滤器字段的数据透视表 table。我需要根据用户在报告过滤器字段中选择的值进行一些操作。

如果用户选择单个值(或选择 All)- 获取该值没有问题。在示例视频中,它是单元格 B1,但如果选择了多个值,则此字段仅显示 Multiple selected.

我从哪里可以获得选定的特定报告过滤器值?我可以从 Excel 公式中访问这些值吗?如果没有 - 我可以从 VBA 代码访问这些值吗?

Sample video

由于 Whosebug 中没有 activity,我 post 向其他几个论坛提出了问题。我得到回应(导致解决方案)的唯一地方是 msdn forum。如果其他人在 Whosebug 中搜索此内容 - 我 post 此处解决方案的本质,提供的链接中提供了其他信息。

我没有得到如何直接从公式访问报表过滤器的值的信息 - 但这可以通过创建用户定义的函数来完成 -> see how to do that

1) 这是从 VBA 代码(通过 P.Thornton)访问报告过滤器字段的方法:

Sub Button960_Click()
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim pi As PivotItem
        Set pt = ActiveSheet.PivotTables(1)

        pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
        pt.PivotCache.Refresh

        Set pf = pt.PivotFields("your report field name")
        For Each pi In pf.PivotItems
            Debug.Print pi.Name, pi.Visible

            If pi.Visible Then
                '... user has selected this value!
            End If
        Next   
End Sub

请注意,您应该设置 PivotCache.MissingItemsLimit = xlMissingNone 否则您可能会遇到意想不到的结果。在我的例子中,事实证明缓存有一堆值不再存在于数据源中。这是一个遗留文件,那些不存在的值很可能在过去的某个时刻存在于文件中,后来从文件中删除了。因此,清除 PivotCache 会清除一些旧的、不存在的数据。

2) A nice solution how to display list of selected values by the side of the report filter fields available at the msdn forum(来自 D.Tamburino)

P.S。感谢来自 MSDN 论坛的 P.Thornton 和 D.Tamburino!