要求:根据 a 的状态显示\隐藏 aRange
行。Selected
SlicerItem
VBA 程序:( 根据 OP 方法)
尝试以下过程(请参阅过程中的注释\解释):
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
另一种方法:
请记住, aSlicer
是一种PivotTables
双向工作的远程控制,即Slicer
更新PivotTables
和PivotTables
更新Slicer
,因此无需验证是否PivotTable
由Slicer
操作更新,只需检查Visible
属性目标PivotItem
中的目标PivotTable
,无论 和 是否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