How to update slicer cache with VBA

前端 未结 2 453
无人及你
无人及你 2020-12-07 06:26

I\'m using Excel VBA to hide/show elements on slicer depending upon user selection.

I have the following code :

 Private Sub removeFilterWithSlicer()         


        
相关标签:
2条回答
  • 2020-12-07 07:12

    This code shows how to filter a Slicer on an array called vSelection.

    Option Explicit
    
    Sub FilterSlicer()
    Dim slr As Slicer
    Dim sc As SlicerCache
    Dim si As SlicerItem
    Dim i As Long
    Dim vItem As Variant
    Dim vSelection As Variant
    
    Set sc = ActiveWorkbook.SlicerCaches("Slicer_ID")
    'Set sc = slr.SlicerCache
    
    vSelection = Array("B", "C", "E")
    
    For Each pt In sc.PivotTables
        pt.ManualUpdate = True 'Stops PivotTable from refreshing after each PivotItem is changed
    Next pt
    
    With sc
    
        'At least one item must remain visible in the Slicer at all times, so make the first
        'item visible, and at the end of the routine, check if it actually  *should* be visible
        .SlicerItems(1).Selected = True
    
        'Hide any other items that aren't already hidden.
        'Note that it is far quicker to check the status than to change it.
        ' So only hide each item if it isn't already hidden
        For i = 2 To .SlicerItems.Count
            If .SlicerItems(i).Selected Then .SlicerItems(i).Selected = False
        Next i
    
        'Make the PivotItems of interest visible
        On Error Resume Next 'In case one of the items isn't found
        For Each vItem In vSelection
            .SlicerItems(vItem).Selected = True
        Next vItem
        On Error GoTo 0
    
        'Hide the first PivotItem, unless it is one of the countries of interest
        On Error Resume Next
        If InStr(UCase(Join(vSelection, "|")), UCase(.SlicerItems(1).Name)) = 0 Then .SlicerItems(1).Selected = False
        If Err.Number <> 0 Then
            .ClearAllFilters
            MsgBox Title:="No Items Found", Prompt:="None of the desired items was found in the Slicer, so I have cleared the filter"
        End If
        On Error GoTo 0
    End With
    
    
    For Each pt In sc.PivotTables
        pt.ManualUpdate = False
    Next pt
    
    End Sub
    
    0 讨论(0)
  • 2020-12-07 07:16

    at least one has to be selected. works the same way when selecting with a mouse. you cannot un-select all

    0 讨论(0)
提交回复
热议问题