Macro to add field into pivot tables

rubenidas

New Member
Joined
Aug 10, 2016
Messages
11
Hi all,
I am trying to create a macro that will insert the field "Month" into the 'Axis Fields (Categories)' section on all pivot tables in my workbook. I created a dashboard that has slicers for all kinds of stuff. Now i want a button that will break down the view into months, and remove the month fields when it is clicked again.

FYI - the pivot tables are not really on the dashboard sheet, only the graphs. The pivot tables are on individually sheets which are hidden. There's like 10 of them.

Hope this makes sense!

Code:
Sub AddMonth()'
' AddMonth Macro
'
    Dim Pvt As PivotTable
    
        For Each Pvt In ActiveSheet
        With Pvt.PivotFields("Month")
        
        .Orientation = xlRowField
        .Position = 2
    End With
    ActiveWorkbook.ShowPivotTableFieldList = False
End Sub
 
Code:
Sub Add_Delete_Month()
    Dim ws As Worksheet
    Dim Pvt As PivotTable
    Dim PvtField As PivotField
    Dim FieldExists As Boolean
    For Each ws In ActiveWorkbook.Sheets
        For Each Pvt In ws.PivotTables
            For Each PvtField In Pvt.PivotFields
                If PvtField.Name = "Month" Then
                    If PvtField.Orientation = xlRowField Then FieldExists = True
                End If
            Next
            If FieldExists Then
                Pvt.PivotFields("Month").Orientation = xlHidden
            Else
                With Pvt.PivotFields("Month")
                    .Orientation = xlRowField
                    .Position = 2
                End With
            End If
        Next
    Next
    ActiveWorkbook.ShowPivotTableFieldList = False
End Sub
 
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top