VBA to Add Calculated Field and Measure into a Pivot Table

PShingadia

New Member
Joined
Aug 5, 2015
Messages
47
Hi:

I have the following code which I am trying to use to clear out the data fields in a pivot table and substitute with a data field selected by the user with a macro button. The code falls down on the very last line showing a 'Run time error 5 Invalid call or argument'. Please help!

Sub Add_Data_Field_PowerPivot_HiddenName()
'Add the Data field to the pivot table.
'The field is determined by the button text that calls the macro.


Dim pt As PivotTable
Dim shp As Shape
Dim cf As CubeField
Dim sField As String
Dim sTableName As String


'Set variables
Set pt = ActiveSheet.PivotTables(1)
Set shp = ActiveSheet.Shapes(Application.Caller)
sField = shp.TextFrame.Characters.Text
sTableName = shp.AlternativeText
sField = "[" & sTableName & "].[" & sField & "]"

'Remove existing fields
For Each cf In pt.CubeFields
If cf.Name <> "Values" And cf.Orientation = xlDataField Then
cf.Orientation = xlHidden
End If
Next cf

'Add field that button was clicked for
pt.CubeFields(sField).Orientation = xlDataField


End Sub


Also how would this be amended to add a measure instead of a calculated field?
 
Last edited:

Excel Facts

Is there a shortcut key for strikethrough?
Ctrl+S is used for Save. Ctrl+5 is used for Strikethrough. Why Ctrl+5? When you use hashmarks to count |||| is 4, strike through to mean 5.

Forum statistics

Threads
1,223,761
Messages
6,174,344
Members
452,556
Latest member
Chrisolowolafe

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