1
votes

I have 3 pivot tables using same source data. I have month wise budget and actual numbers (3 columns - Month, Budget, Actual).

I have created one slicer for month and only want to show months which have actual numbers(for example Jan to June). Right now, it is showing all the months as budget numbers are present for the entire year. How can I achieve this with VBA code?

As a first step, I have tried a value filter on the pivot table, but I am getting an error. My plan was to filter the pivot table with actual not equal to zero months first, and then to apply the selection of months to the slicer.

    Sub filtermonth()
    '
    ' filtermonth Macro
    '
  ActiveSheet.PivotTables("PivotTable4").PivotFields("Month").PivotFilters.Add2 _
            Type:=xlValueDoesNotEqual, DataField:=ActiveSheet.PivotTables("PivotTable4" _
            ).PivotFields("Actuals"), Value1:=0
    End Sub

I am getting the below error when i run this

Run time error 1004: Unable to get the PivotFields property of the PivotTable Class

1

1 Answers

0
votes

I guess, you have "Month" as row field and "Sum of Actual" (renamed as "Actuals") as data field.

You get an error, if the values are filtered already, so you need to clear the filters before.

By following code, you set the month name's visibility on/off in your slicer:

Sub HideUnnecessaryMonths()
    Dim pt As PivotTable
    Dim pfMonth As PivotField, pfActuals As PivotField
    Dim r As Range
    Dim i As Long

    Set pt = ActiveSheet.PivotTables("PivotTable4")
    Set pfMonth = pt.PivotFields("Month")
    Set pfActuals = pt.PivotFields("Actuals")

    pfMonth.ClearAllFilters
    pfMonth.PivotFilters.Add2 _
        Type:=xlValueDoesNotEqual, _
        DataField:=pfActuals, _
        Value1:=0

    For i = 1 To 12  ' each month
        On Error Resume Next
        Set r = pt.GetPivotData("Actuals", pfMonth.Name, i)
        If Err.Number <> 0 Then
            On Error GoTo 0
            pfMonth.PivotItems(i + 1).Visible = False
        End If
        On Error GoTo 0
    Next i
End Sub

Remarks, if you want to completely hide month names in a slicer:

As long as you have the budget as data field also (e. g. "Sum of Budget"), you can't completely hide month names in your slicer:

  • You can switch the visibility of individual months on/off,
    but slicer still shows all months (marked or not)
  • You could use a date filter to reduce pivot rows,
    but slicer still shows all months
  • You could use a value filter, e. g. "Actuals" > 0,
    but slicer still shows all months

Only if you would show "Budget" as second row field instead (which would be useless, as you can't see the summarized budget), then you could edit your slicer's settings and disable "Hide items with no data". Then your slicer would show a reduced list of month names.