要求:根据SlicerItem 的Selected 状态显示\隐藏Range 行。
VBA 程序: (根据 OP 方法)
尝试以下过程(参见过程中的 cmets\explanation):
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
Dim sc As SlicerCache, sl As Slicer
Dim sPt As String, sFld As String, sItm As String, sRng As String
'Use variables to hold the criteria to be applied
sPt = "PivotTable1"
sFld = "Chain"
sItm = "A.6"
sRng = "287:346"
With Target
Rem Validate PivotTable
If .Name <> sPt Then Exit Sub
' As Slicer names can be easily changed by users, need to identify
' the SlicerCache connected to the target `PivotTable` using the
' SourceName of the PivotField. This step returns the SlicerCache
' connected to the PivotTable otherwise, the SlicerCache is nothing.
Rem Set SlicerCache
For Each sl In .Slicers
If sl.SlicerCache.SourceName = sFld Then
Set sc = sl.SlicerCache
Exit For
End If: Next: End With
Rem Validate SlicerItem & Apply Result
If Not (sc Is Nothing) Then
' This line Shows\Hides the target range based on the opposite
' status of the target SlicerItem.
Me.Rows(sRng).EntireRow.Hidden = Not (sc.SlicerItems(sItm).Selected)
Else
' PivotTable is not connected to a Slicer of the target PivotField
MsgBox "PivotTable [" & sPt & "]" & String(2, vbLf) & _
vbTab & "is not connected to Slicer of Field [" & sFld & "].", _
vbApplicationModal + vbInformation, "Slicers Selection"
End If
End Sub
另一种方法:
请记住,Slicer 是PivotTables 的一种远程控制,可以双向工作,即Slicer 更新PivotTables,PivotTables 更新Slicer,如这样就不需要验证PivotTable是否被Slicer操作更新了,只需要检查目标PivotItem中目标PivotItem的Visible属性,不管Slicer是否和PivotTable 是否连接。
此过程仅使用目标 PivotTable,即显示或隐藏目标范围,具体取决于 PivotItem 在数据透视表中是否可见。
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
Dim sPt As String, sFld As String, sItm As String, sRng As String
sPt = "PivotTable1"
sFld = "Chain"
sItm = "A.6"
sRng = "287:346"
With Target
Rem Validate PivotTable
If .Name <> sPt Then Exit Sub
Rem Validate PivotItem & Apply Result
With .PivotFields(sFld).PivotItems(sItm)
Me.Rows(sRng).EntireRow.Hidden = Not (.Visible)
End With: End With
End Sub