Skip to content

Excel VBA Macro to a Create Slicer for PivotTable

    As with PivotTables, you need to create the cache for a slicer before creating the slicer itself. To create the slicer cache use SlicerCaches.Add2, SlicerCaches being a property of the Workbook object.

    SlicerCaches.Add(Source, SourceField, Name, SlicerCacheType)

    Mandatory parameters are Source (the PivotTable) and SourceField– the field you want to create a slicer for.

    To create the slicer use Slicers.Add, Slicers being a property of the SlicerCache object.

    Slicers.Add(SlicerDestination, Level, Name, Caption, Top, Left, Width, Height)

    The only mandatory parameter is SlicerDestination –the worksheet you want the slicer to appear on.

    For some strange reason for both the Add2 and Add methods, if you name the parameters you get a runtime error.

    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim wb As Workbook
    Set wb = ActiveWorkbook
    Dim PTcache As PivotCache
    Dim PT As PivotTable
    Dim SLcache As SlicerCache
    Dim SL As Slicer
    'Define the cache for the PivotTable
    Set PTcache =wb.PivotCaches.Create(SourceType:=xlDatabase, _
    SourceData:=Range("Sales_Data[#All]"),Version:=xlPivotTableVersion15)
    'Create the PivotTable
    Set PT = ws.PivotTables.Add(PivotCache:=PTcache,_
    TableDestination:=Range("J1"),TableName:="Sales Analysis")
    PT.AddFieldsRowFields:=Array("Region", "Branch"), _
    ColumnFields:="Product",PageFields:="Product Category"
    PT.AddDataFieldField:=PT.PivotFields("Revenue"), _
    Caption:="No ofTransactions", Function:=xlCount
    'Create Slicer Cache
    Set SLcache = wb.SlicerCaches.Add2(PT,"Product Category",  _
    "ProdCatSlicerCache")
    'Create Slicer
    Set SL = SLcache.Slicers.Add( _
    ws, , "ProdCatSlicer","Select a Product Category", _
    Range("G1").Top,Range("G1").Left)
    'Define which values are not selected in the Slicer
    With SLcache
    .SlicerItems("COOKWARE").Selected = False
    .SlicerItems("CUTLERY").Selected = False
    End With

    To clear the filter applied to a slicer…

    ActiveWorkbook.SlicerCaches("ProdCatSlicerCache").ClearManualFilter