VBA De-Select All Slicer Options (except 1)

大城市里の小女人 提交于 2020-02-23 07:30:51

问题


The below code is giving an odd result. The slicer has 22 options (#1 at top going down to #22 on bottom).

If I currently have #12 selected, and then run the code, it will select slicer options 1-12. If X = the # of currently selected slicer option, the code will select 1 - X, and the options below stay un-selected. The above is just an example and not meant to show a natural, or desired, starting point.

Other info that may be relevant: Multiselect = True, The 2nd to bottom option = "", The Last option -"blank"

What I want the code to do is select the 3rd to last option, which is the first (from bottom) option that isnt blank or null data. This explains the commented out line.

However, I cannot figure out why the code below is not deselecting all options.

Sub Slicer()

Dim WB As Workbook
Set WB = ThisWorkbook
Dim i As Integer
Dim n As Integer



With WB.SlicerCaches("Slicer_Processed_date")
    n = .SlicerItems.Count

    For i = 1 To n
        If .SlicerItems(i).Selected = True Then
            .SlicerItems(i).Selected = False
        End If
    Next i

   '.SlicerItems(n - 2).Selected = True
End With   
End Sub

回答1:


You can't deselect all items. You must leave one item visible at all times, or VBA will throw an error.

If you want off-the-shelf code to filter a Slicer on an array, check out my answer at How to update slicer cache with VBA

That array can have just the one thing in it if you like. And the comments in that code will help you understand how to filter a Slicer efficiently.

Edit: Now that I understand what you need, use this:

Sub SliceByIndex()


Dim sc As SlicerCache
Dim si As SlicerItem
Dim l As Long
Dim i As Long

Set sc = ThisWorkbook.SlicerCaches("Slicer_Test")

l = sc.SlicerItems.Count
With sc
    .PivotTables(1).ManualUpdate = True 'Stops PivotCache recalculating until we are done

    ' Select the first item, because one item MUST remain visible at all times.
    ' We'll unselected it when we're done
    .SlicerItems(1).Selected = True

    'Deselect everything else
    For i = 2 To l
        .SlicerItems(i).Selected = False
    Next i

    'Select the desired item
    .SlicerItems(l - 2).Selected = True

    'Deselect the first items
    .SlicerItems(1).Selected = False

    'Turn the PivotCache calculation on again
    .PivotTables(1).ManualUpdate = False
End With


End Sub


来源:https://stackoverflow.com/questions/50108890/vba-de-select-all-slicer-options-except-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!