我正在寻找循环切片器和 select 下一个项目和下一个打印枢轴

I am looking to loop through a slicer and select the next item and the next to print a pivot

我有一个切片器链接到 2 个枢轴 tables。我想从第一项到最后一项遍历切片器并打印相应的 tables.

我试过以下代码:

Sub Slicerloop
    Dim sI As SlicerItem, sI2 As SlicerItem, sC As SlicerCache
    Set sC = ActiveWorkbook.SlicerCaches("Slicer_UID")
    With sC
        For Each sI In sC.SlicerItems
            For Each sI2 In sC.SlicerItems
                If sI.Name = sI2.Name Then sI2.Selected = True Else: sI2.Selected = False
            Next        
        Next
    End With        
End Sub

没有错误消息,但这不会 select 下一个条目并因此更改主元 table。

通过这种方式,您可以遍历所有切片项并使用它们各自的标题作为数据透视表的屏幕截图。

Private Sub LoopAllSlicerItemsAndCapturePivottable()
    Dim sc As Excel.SlicerCache
    Dim si As Excel.SlicerItem, siDummy As Excel.SlicerItem
    Dim pt As Excel.PivotTable
    Dim co As Excel.ChartObject
    Dim wsBlank As Excel.Worksheet

    Set sc = ActiveWorkbook.SlicerCaches("Slicer_UID")
    Set pt = sc.PivotTables(1)

    ' add a blank sheet to get a blank Chart instead of PivotChart later 
    Set wsBlank = ActiveWorkbook.Sheets.Add

    For Each si In sc.SlicerItems
        sc.ClearManualFilter
        For Each siDummy In sc.SlicerItems
            siDummy.Selected = (si.Name = siDummy.Name)
        Next siDummy

        ' now only 1 sliceritem is selected and can be used
        With pt.TableRange2 ' or TableRange1
            .CopyPicture Appearance:=xlScreen, Format:=xlPicture
            Set co = wsBlank.ChartObjects.Add(1, 1, .Width, .Height)
            co.Select
            co.Chart.Paste
            co.Chart.Export _
                fileName:=ActiveWorkbook.Path & "\Whatever " & si.Caption & ".png", _
                filtername:="PNG"
            co.Delete
        End With
    Next si

    Application.DisplayAlerts = False
    wsBlank.Delete
    Application.DisplayAlerts = True

End Sub