Dynamic number of datafields in pivot table

Stephen57

New Member
Joined
Apr 12, 2011
Messages
4
I have a number of datafields i'm inserting into a pivot table. That number of fields can be different each time the code is executed. Is there a way to assign an Array to add data fields? I tried this:

ActiveSheet.PivotTables("Heads").AddDataField ActiveSheet.PivotTables("Heads").PivotFields(Range("Dates")), Array(Range("Dates")), xlSum

and get a pivot table class error. I'm a beginner :-).
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
I have created an Array and verified that it is populating correctly. My code has evolved into the following, and I'm still getting an error when it comes to adding the data field:

Code:
Sheets.Add.Name = "Pivot"
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        Range("Pivot_Data"), Version:=xlPivotTableVersion10).CreatePivotTable _
        TableDestination:="Pivot!R3C1", TableName:="Heads", DefaultVersion _
        :=xlPivotTableVersion10
 
    Sheets("Pivot").Select
 
    Cells(3, 1).Select
 
    With ActiveSheet.PivotTables("Heads")
        .ColumnGrand = False
        .RowGrand = False
        .InGridDropZones = True
        .RowAxisLayout xlTabularRow
    End With
 
    With ActiveSheet.PivotTables("Heads").PivotFields("CC")
        .Orientation = xlColumnField
        .Position = 1
    End With
 
    For n = 0 To Date_Count
        ActiveSheet.PivotTables("Heads").AddDataField _
            ActiveSheet.PivotTables("Heads").PivotFields(Dates(n)), _
            Dates(n), xlSum
    Next n

Any help would greatly be appreciated.
 
Upvote 0

Forum statistics

Threads
1,224,607
Messages
6,179,871
Members
452,948
Latest member
UsmanAli786

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