VBA - Calculated Fields in Pivot Table

Catmao

New Member
Joined
Mar 12, 2015
Messages
27
Hi All,

Here is my source data (6 columns):
Name Gender NewGrade1(NewField1) NewGrade2(NewField2) OldGrade1(OldField1)
OldGrade2(OldField2)
I want to create a pivot table and calculated fields of % Change to Field1, % Change to Field2, and the filed names are "Grade1 % Change", "Grade2 % Change".
There could be more fields, so I want use For/Next function.

Below is my code. The red is where I got error 1004: Unable to get the PivotFields property of the PivotTable class. (Field(i) is Grade(i), e.g. Field1 is Grade1)
For i = 1 To NumFields
PvtTbl.CalculatedFields.Add Name:="Field(i)Change", Formula:="=IF(OldField(i)=0,0,(NewField(i) -OldField(i))/OldField(i))"

With PvtTbl.PivotFields("Field(i)Change")
.Orientation = xlDataField
.Function = xlSum
.Position = i
.NumberFormat = "0.00%"
.Caption = Field(i) & " % Change"

End With
Next i

Thanks in advance!
 
Last edited:

Excel Facts

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
Hi
See if this example is useful:

Code:
Sub AddCalcField()
Dim pvtT As PivotTable, i%, si$, fml$
Set pvtT = ActiveSheet.PivotTables(1)
i = 1
si = CStr(i)
fml = "=IF(OldField" & si & "=0,0,(NewField" & si & "-OldField" & si & ")/OldField" & si & ")"


pvtT.CalculatedFields.Add "Field" & si & "Change", fml, True


With pvtT.PivotFields("Field" & si & "Change")
    .Orientation = xlDataField
    .Function = xlSum
    .Position = i
    .NumberFormat = "0.00%"
    .Caption = "Field" & i & " % Change Final"
End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,880
Messages
6,127,519
Members
449,385
Latest member
KMGLarson

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