隐藏基于切片器选择的工作表行

时间:2018-04-05 19:37:32

标签: vba excel-vba pivot-table slicers excel

如果选择切片器中的某个值,有没有办法隐藏某些行? 我有一些图表只有在选择了一个特定的链条时才需要显示,如果它没有被选中 - 然后隐藏图表(位于第287行:345行)。 我试过跟随,但它没有工作:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If ActiveWorkbook.SlicerCaches("Slicer_Chain").SlicerItems("ChainName").Selected = True Then
        Rows("287:346").Hidden = False
    Else
        Rows("287:346").Hidden = True
    End If

End Sub

2 个答案:

答案 0 :(得分:0)

我会将Worksheet_PivotTableUpdate事件定位为与切片器关联的数据透视表。

位置:

在包含与切片器关联的数据透视表的工作表的代码窗格中。

如下所示:

注意:

  1. 根据需要更改数据透视表名称
  2. 如果要隐藏的行位于不同的工作表中,请在行之前添加工作表名称,例如

    ThisWorkbook.Worksheets("Sheet1").Rows("287:346").EntireRow.Hidden = False
    
  3. <强>代码:

    Option Explicit
    
    Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
    
        If Target.Name <> "PivotTable1" Then
            Exit Sub
        Else
           If Parent.SlicerCaches("Slicer_Chain").SlicerItems("ChainName").Selected Then
            Rows("287:346").EntireRow.Hidden = False
           Else
            Rows("287:346").EntireRow.Hidden = True
           End If
        End If
    
    End Sub
    

答案 1 :(得分:0)

要求:根据Range的{​​{1}}状态显示\隐藏Selected行。

VBA程序: (根据OP方法)

尝试以下过程(请参阅过程中的注释\解释)

SlicerItem

另一个Aproach:

请注意, 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 1}}更新PivotTables,因此无需验证Slicer操作是否更新PivotTable,只需检查Slicer属性即可无论VisiblePivotItem是否已连接,目标PivotTable中的定位Slicer

此过程仅使用目标PivotTable,即显示或隐藏目标范围,具体取决于PivotTable是否在数据透视表中可见。

PivotItem