Iterate over slicer via VBA and select a single item each time

前端 未结 3 2021
不知归路
不知归路 2020-11-30 15:48

I have several slicers within a spreadhseet. I\'d like to be able to loop over one of these via VBA, and select every option one by one. The macro below seems fine to my ti

相关标签:
3条回答
  • 2020-11-30 16:17

    Since the question I linked you too in my comment does not have an accepted answer (the user never choose to answer or reply to my suggestion), I will provide the solution to your problem here as well.

    Sub slicers(slName As String)
    
        Dim slItem As SlicerItem, slDummy As SlicerItem
        Dim slBox As SlicerCache
    
        Set slBox = ActiveWorkbook.SlicerCaches(slName)
    
        'loop through each slicer item
        For Each slItem In slBox.SlicerItems
    
            'show all items to start
            slBox.ShowAllItems 'or .ClearManualFilter
    
            'test each item against itself
            For Each slDummy In slBox.SlicerItems
    
                'if the item equals the item in the first loop, then select it
                'otherwise don't show it (thus showing 1 at a time between the nested loops)
                If slItem.Name = slDummy.Name Then slDummy.Selected = True Else: slDummy.Selected = False
    
                'more code to process the data (I suspect)
    
            Next slDummy
    
        Next slItem
    
    End Sub
    
    0 讨论(0)
  • 2020-11-30 16:31

    You can indeed have several selected items within an excel spreadsheet. The code you posted do nothing instead of selecting all items satisfying slDummy.Name = slItem.Name.

    If I understand well, you want to run some code once the item is selected, and then go to the next item. You can achieve this by unselecting one item after use, with item.selected = False.

    You may also want to select all items needed at first stage and then run a loop that will afect only the item that have the property .selected set to true. However it will probably be longer to execute as you'd have one more loop.

    0 讨论(0)
  • 2020-11-30 16:33

    I tried the above solutions but can't get them to work. I kept getting a 1004 object not defined error; might be because I'm using the data model. In the end I cobbled together this solution which picks up the slicer values from a range and then calls another macro to save in pdf (which was my ultimate objective). Not elegant but effective.

    Sub looop()
    
    Dim rng As Range, cell As Range
    Set rng = Sheet1.Range("B4:B5")
    For Each cell In rng
    
    ActiveWorkbook.SlicerCaches("Slicer_MasterBrand").VisibleSlicerItemsList = Array("[Customer].[MasterBrand].&[" & cell.Value & "]")
    
    a_ExportPDF
    
    Next cell
        
    End Sub
    
    0 讨论(0)
提交回复
热议问题