答案 0 :(得分:0)
这可以通过一些VBA代码来实现,请参阅Hide & Unhide (Filter) Columns with a Slicer or Filter Drop-down我应该说我自己没有对此进行测试,但代码是直截了当且不言而喻。
您需要调整代码,但基本设置为:
Private Sub Worksheet_PivotTableUpdate(ByVal Target As
PivotTable)
宏。......哪个叫...
他们提供的代码并不是特别复杂(见下文),但我认为对于VBA新手而言,这将是具有挑战性的,但并非不可能。
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
'Run the filter columns macro when the pivot table or slicer is changed
Select Case Target.Name
Case "PivotTable1"
Call m_FilterCol.Filter_Columns("rngQuarter", "Report", "Report", "PivotTable1", "Quarter")
End Select
End Sub
这是Filter_Columns宏代码。
Sub Filter_Columns(sHeaderRange As String, _
sReportSheet As String, _
sPivotSheet As String, _
sPivotName As String, _
sPivotField As String _
)
Dim c As Range
Dim rCol As Range
Dim pi As PivotItem
'Unhide all columns
Worksheets(sReportSheet).Range(sHeaderRange).EntireColumn.Hidden = False
'Loop through each cell in the header range and compare to the selected filter item(s).
'Hide columns that are not selected/filtered out.
For Each c In Worksheets(sReportSheet).Range(sHeaderRange).Cells
'Check if the pivotitem exists
With Worksheets(sPivotSheet).PivotTables(sPivotName).PivotFields(sPivotField)
On Error Resume Next
Set pi = .PivotItems(c.Value)
On Error GoTo 0
End With
'If the pivotitem exists then check if it is visible (filtered)
If Not pi Is Nothing Then
If pi.Visible = False Then
'Add excluded items to the range to be hidden
If rCol Is Nothing Then
Set rCol = c
Else
Set rCol = Union(rCol, c)
End If
End If
End If
'Reset the pivotitem
Set pi = Nothing
Next c
'Hide the columns of the range of excluded pivot items
If Not rCol Is Nothing Then
rCol.EntireColumn.Hidden = True
End If
End Sub