无法为 VBA 中的常规数据透视表 table 引用 VisibleSlicerItemsList

Cannot reference VisibleSlicerItemsList for regular pivot table in VBA

我正在尝试为 VBA(不是 PowerPivot)中的常规 Pivot table 操作切片器,但我无法引用 VisibleSlicerItemsList。我得到一个错误:

Application-defined or object-defined error

知道我做错了什么吗?

Screenshot showing data and pivot table with slicer from test workbook, along with the error message "Application-defined or object-defined error" for the VisibleSlicerItemsList in the Locals window

您可以下载测试工作簿here

检查此 属性 上的 MSDN 条目 - 它指出:

The VisibleSlicerItemsList property is only applicable for slicers that are based on OLAP data sources (SlicerCache.OLAP = True).

在您的示例中,您使用的数据透视表 table 连接到 sheet 中的数据,而不是连接到 OLAP 多维数据集。

您可以使用这样的代码解决它,它迭代 SlicerCacheSlicerItems 集合:

Option Explicit

Sub Test()

    Dim objCache As SlicerCache
    Dim objItem As SlicerItem
    Dim varChoices As Variant
    Dim lngCounter1 As Long
    Dim lngCounter2 As Long

    Set objCache = ThisWorkbook.SlicerCaches("Slicer_Company")
    varChoices = Array("1", "3", "5")

    ' iterate slicers
    For lngCounter1 = 1 To objCache.SlicerItems.Count
        Set objItem = objCache.SlicerItems(lngCounter1)
        'assume not for selection
        objItem.Selected = False
        'iterate choices to check for activation
        For lngCounter2 = 0 To UBound(varChoices)
            If objItem.Name = varChoices(lngCounter2) Then
                'activate and exit loop
                objItem.Selected = True
                Exit For
            End If
        Next lngCounter2
    Next lngCounter1

End Sub