简体   繁体   中英

Linking drop-down selection to slicer

I have a drop-down list (Excel data-validation) with the same options as a slicer (both from different sources).

How do I link my drop-down list selection to my slicer?

Nothing is recorded when I make a selection on a drop-down list.

Eg

Drop-down list: Area 1, Area 2, Area 3  
Slicer: Area 1, Area 2, Area 3  

Goal: If I select Area 3 from my drop-down list, my slicer should have Area 3 selected too.

You need a event routine for Change that is triggered whenever the cell where the dropdown lives is changed, and a routine that changes the slicer.

Put the following code to the worksheet object in the VBA-Editor (not to a new module). Change the cell address (in the example it is E10 to the cell you are using). If you have more than one slicer in your workbook, you have to change the index to SlicerCaches to the one you want to modify (as usual in VBA, you can use the index number or the name).

Option Explicit
' The Event routine    
Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address(False, False) = "E10" Then
        SelectSlicerItem ThisWorkbook.SlicerCaches(1), Target.value
    End If
End Sub

The following routine can be put either below the event routine or into a module. Note that if the itemText is not found in the slicer, all items will be selected.

Sub SelectSlicerItem(sc As SlicerCache, itemText As String, Optional defaultItem As String = "")
    Dim si As SlicerItem, found As Boolean
    found = False
    sc.ClearManualFilter
    For Each si In sc.SlicerItems
        ' Debug.Print si.Caption, si.value
        If si.Caption <> itemText Then
            si.Selected = False
            found = True
        End If
    Next si
    If Not found And defaultItem <> "" Then SelectSlicerItem sc, defaultItem
End Sub

Edit: Changed SelectSlicerItem to deal with default item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM