Sub topic 15
Automating Slicers with VBA
This chapter assumes you can insert a slicer by hand, connect it to several PivotTables through Report Connections, and save a workbook as macro-enabled (.xlsm). You also need to be able to open the Visual Basic Editor with Alt+F11. The macros here automate what you have already done through the ribbon.
When automation is worth it
Most reports never need a macro. VBA pays off in three cases:
- You build the same dashboard every month from a new data extract.
- You must reset every filter to a known state before the report is shared.
- You need to set a slicer to a specific selection, such as "East and West only", as part of a larger refresh routine.
If you only need to create one slicer once, use the ribbon. A macro for a one-off task costs more time than it saves.
The slicer object model
A slicer is split across two objects, and this explains most of the confusion in VBA code.
- A SlicerCache holds the filter state: which items are selected, which PivotTables are connected, and how items are sorted. It belongs to the workbook.
- A Slicer is the visible control on a sheet. It has a position, a size, a caption, and a style. Several slicers can share one cache.
Filter settings go on the cache, and appearance settings go on the slicer. To select items or connect a PivotTable, work with SlicerCache. To move or restyle the control, work with Slicer.
Creating a slicer
Creating a slicer takes two calls. SlicerCaches.Add2 creates the cache from a PivotTable and a field name. Slicers.Add then places a visible control on a sheet.
Sub AddRegionSlicer()
Dim pt As PivotTable
Dim sc As SlicerCache
Set pt = ActiveSheet.PivotTables(1)
Set sc = ActiveWorkbook.SlicerCaches.Add2(pt, "Region")
sc.Slicers.Add ActiveSheet, , "RegionSlicer", "Region", 10, 400, 140, 150
End SubThe arguments of Slicers.Add are, in order:
- The destination sheet.
- The level, which you can leave empty for a normal slicer.
- The slicer name.
- The caption shown at the top of the control.
- Top, Left, Width, and Height, in points.
The cache gets a generated name. In most workbooks it is Slicer_Region, but it becomes Slicer_Region1 if a cache for that field already exists. If your later macros depend on the name, set it yourself with the third argument of Add2:
Set sc = ActiveWorkbook.SlicerCaches.Add2(pt, "Region", "Slicer_Region")The name must be unique in the workbook. Running the macro twice with a fixed name raises an error on the second run. The next section shows how to guard against that.
Looking up and listing caches
Hard-coded names are fragile, because a colleague may have renamed or deleted the cache. This function returns the cache or Nothing, so your macro can decide what to do.
Function FindCache(cacheName As String) As SlicerCache
Dim sc As SlicerCache
For Each sc In ActiveWorkbook.SlicerCaches
If sc.Name = cacheName Then
Set FindCache = sc
Exit Function
End If
Next sc
End Function
Sub ListSlicerCaches()
Dim sc As SlicerCache
For Each sc In ActiveWorkbook.SlicerCaches
Debug.Print sc.Name, sc.SourceName, sc.PivotTables.Count
Next sc
End SubSourceName is the field the slicer filters. The count shows how many PivotTables are connected. ListSlicerCaches writes its output to the Immediate window (Ctrl+G), which makes it a quick way to find the exact names in an unfamiliar workbook.
You can use FindCache to make creation safe to repeat:
Sub EnsureRegionSlicer()
Dim sc As SlicerCache
Set sc = FindCache("Slicer_Region")
If sc Is Nothing Then
Set sc = ActiveWorkbook.SlicerCaches.Add2( _
ActiveSheet.PivotTables(1), "Region", "Slicer_Region")
sc.Slicers.Add ActiveSheet, , "RegionSlicer", "Region", 10, 400, 140, 150
End If
End SubConnecting more PivotTables
Report Connections is a dialog box that edits the PivotTables collection of the cache. In code, you add to that collection:
Sub ConnectSlicerToSecondPivot()
Dim sc As SlicerCache
Set sc = ActiveWorkbook.SlicerCaches("Slicer_Region")
sc.PivotTables.AddPivotTable ActiveSheet.PivotTables(2)
End SubThe rule from the Report Connections chapter still applies: the PivotTable must use the same pivot cache as the one the slicer was built on. If it does not, AddPivotTable raises a run-time error. Adding a PivotTable that is already connected also raises an error.
The following macro handles both problems. It connects every PivotTable in the workbook that shares the source PivotTable's cache and skips the ones that are already connected.
Function IsConnected(sc As SlicerCache, pt As PivotTable) As Boolean
Dim p As PivotTable
For Each p In sc.PivotTables
If p.Name = pt.Name And p.Parent.Name = pt.Parent.Name Then
IsConnected = True
Exit Function
End If
Next p
End Function
Sub ConnectToAllSharedPivots()
Dim sc As SlicerCache
Dim basePt As PivotTable
Dim ws As Worksheet
Dim pt As PivotTable
Set sc = ActiveWorkbook.SlicerCaches("Slicer_Region")
Set basePt = sc.PivotTables(1)
For Each ws In ActiveWorkbook.Worksheets
For Each pt In ws.PivotTables
If pt.CacheIndex = basePt.CacheIndex Then
If Not IsConnected(sc, pt) Then
sc.PivotTables.AddPivotTable pt
End If
End If
Next pt
Next ws
End SubCacheIndex identifies the pivot cache behind a PivotTable. Two PivotTables with the same value share data, so they are eligible for the same slicer. To disconnect a PivotTable, use sc.PivotTables.RemovePivotTable pt.
Setting and clearing selections
The first thing to know about selection is that every item starts selected, which means "no filter". To filter, you turn items off.
Sub ShowEastAndWestOnly()
Dim sc As SlicerCache
Dim si As SlicerItem
Set sc = ActiveWorkbook.SlicerCaches("Slicer_Region")
sc.ClearManualFilter
For Each si In sc.SlicerItems
If si.Name <> "East" And si.Name <> "West" Then
si.Selected = False
End If
Next si
End SubCalling ClearManualFilter first guarantees a known starting point. Without it, items you turned off in an earlier run stay off.
Clearing is a single call, and it is the code equivalent of the Clear Filter button:
Sub ClearRegionSlicer()
ActiveWorkbook.SlicerCaches("Slicer_Region").ClearManualFilter
End SubTo reset every slicer and timeline before you save or send a report, loop over the whole collection:
Sub ClearAllSlicers()
Dim sc As SlicerCache
For Each sc In ActiveWorkbook.SlicerCaches
sc.ClearManualFilter
Next sc
End SubFormatting and settings from code
The appearance properties on a Slicer match the options on the Slicer tab of the ribbon. Cache-level properties cover sorting and the handling of items with no data.
Sub FormatRegionSlicer()
Dim sc As SlicerCache
Dim sl As Slicer
Set sc = ActiveWorkbook.SlicerCaches("Slicer_Region")
Set sl = sc.Slicers("RegionSlicer")
sl.Caption = "Sales region"
sl.NumberOfColumns = 2
sl.Style = "SlicerStyleLight2"
sl.Top = 10
sl.Left = 400
sl.Width = 160
sl.Height = 120
sc.SortItems = xlSlicerSortAscending
End Subsc.CrossFilterType controls how items with no data are shown. Assign one of the constants xlSlicerCrossFilterNone, xlSlicerCrossFilterHideButtonsWithNoData, or xlSlicerCrossFilterShowItemsWithNoData. These correspond to the settings in the Slicer Settings dialog box.
Timelines in code
A timeline uses the same collections. You pass the constant xlTimeline as the cache type when you create it, and the date field must meet the requirements covered earlier. A disabled timeline in the interface becomes a run-time error in code, so check that the field holds true dates before you run the macro.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| "Subscript out of range" on `SlicerCaches("...")` | The cache name differs from the one in your macro | Run `ListSlicerCaches` and copy the exact name |
| Error on `AddPivotTable` | Different pivot cache, or already connected | Compare `CacheIndex` and use `IsConnected` |
| Error when creating a slicer a second time | A cache or slicer with that name exists | Use `FindCache` first |
| Slicer shows the wrong items after a data refresh | Old items remain in the cache | Refresh the pivot cache, then reapply the selection |
| Macro does nothing visible | The workbook is in Protected View, or macros are disabled | Enable editing and macros for the file |
Exercise
Write a macro called SelectOneRegion that takes a region name as a String argument, clears the "Slicer_Region" filter, and then deselects every item except the one named. What must the macro do to avoid a run-time error if the name is misspelled?
Show answer
Clear the filter first with sc.ClearManualFilter. Then loop through sc.SlicerItems and set si.Selected = False for each item whose Name differs from the argument. A misspelled name matches no item, so the loop would deselect every item and raise an error. To avoid this, first loop once to check that an item with that name exists. If none does, exit the macro (or show a message) without changing the selection, so the slicer stays cleared.
Exercise
A slicer controls two PivotTables on different sheets. A macro calls sc.PivotTables.AddPivotTable for the second PivotTable and fails. Name two possible causes and how to check each.
Show answer
First, the second PivotTable may use a different pivot cache. Compare pt.CacheIndex for both PivotTables. If the values differ, the slicer cannot connect to it. Second, the PivotTable may already be connected. Loop through sc.PivotTables (or check sc.PivotTables.Count and the names) before calling AddPivotTable.