I'm having an issue with this piece of code causing Excel to crash every time it is run. When I remove the bold section, it runs just fine. Any thoughts on how I can get this to work? Is Excel being overloaded?
(I'm not great with VBA, but what i'm trying to do is select the pivot table in the active sheet, have the sum of "cost" added to the values section of the pivot, and then format it. Then, have the sum of "Impressions" added to the value section of the pivot, and then format it.)
Sub PivotFormat()
Dim pf As PivotField
ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).AddDataField ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Cost"), "Sum of Cost", xlSum
Set pf = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Sum of Cost")
pf.DataRange.NumberFormat = "_($* #,##0.00"
ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).AddDataField ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Impressions"), "Sum of Impressions", xlSum
Set pf = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Sum of Impressions")
pf.DataRange.NumberFormat = "#,##0"
End Sub
(I'm not great with VBA, but what i'm trying to do is select the pivot table in the active sheet, have the sum of "cost" added to the values section of the pivot, and then format it. Then, have the sum of "Impressions" added to the value section of the pivot, and then format it.)
Sub PivotFormat()
Dim pf As PivotField
ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).AddDataField ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Cost"), "Sum of Cost", xlSum
Set pf = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Sum of Cost")
pf.DataRange.NumberFormat = "_($* #,##0.00"
ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).AddDataField ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Impressions"), "Sum of Impressions", xlSum
Set pf = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name).PivotFields("Sum of Impressions")
pf.DataRange.NumberFormat = "#,##0"
End Sub