如何在Excel中使用切片器链接表和数据透视表?

时间:2018-04-02 19:18:54

标签: excel pivot-table slicers excel-tables

好。我在Excel中的工作表上有一个名为“ALL_INFO”的表,我在其他工作表中创建了一个数据透视表,其名称为“PIVOT_INFO”。我想知道链接表的方法,以及使用Slicers过滤信息的数据透视表,它将反映在两个表中。

有人知道我该怎么做吗?

提前谢谢你。

1 个答案:

答案 0 :(得分:1)

为数据透视表创建一个切片器,为表创建一个切片器。确保PT Slicer可见,并且Table Slicer隐藏在用户无法看到的位置。然后将此代码放在与您的PT所在的工作表对应的工作表模块中:

Option Explicit

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
Dim sLastUndoStackItem As String
Dim sc_Pivot As SlicerCache
Dim sc_Table As SlicerCache
Dim si_Pivot As SlicerItem
Dim si_Table As SlicerItem

With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With

If Target.Name = "PivotTable1" Then '<= Change name as appropriate
    On Error Resume Next 'in case the undo stack has been wiped or doesn't exist
    sLastUndoStackItem = Application.CommandBars(14).FindControl(ID:=128).List(1) 'Standard Commandbar, undo stack
    'The above line doesn't seem to work in my version of O365 so we'll use the English language backup
    If sLastUndoStackItem = "" Then sLastUndoStackItem = Application.CommandBars("Standard").Controls("&Undo").List(1)
    On Error GoTo 0

    If sLastUndoStackItem = "Filter" Or sLastUndoStackItem = "Slicer Operation" Then

        Set sc_Pivot = ActiveWorkbook.SlicerCaches("Slicer_Data") '<= Change name as appropriate
        Set sc_Table = ActiveWorkbook.SlicerCaches("Slicer_Data1") '<= Change name as appropriate
        sc_Table.ClearAllFilters

        On Error Resume Next 'In case items differ between Table and PT
        For Each si_Pivot In sc_Pivot.SlicerItems
            With si_Pivot
                sc_Table.SlicerItems(.Name).Selected = .Selected
            End With
        Next si_Pivot
    End If
End If

With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
End With

End Sub

以下是我使用“Master”切片器之前的情况:

enter image description here

......这就是我使用“Master”切片器后的事情:

enter image description here

请注意,过滤表会隐藏整个工作表中的行。因此,您不希望在表格旁边随时放置任何您想要保持可见的内容。