UPDATE: I think I found the answer but I have not been able to see if there is a way to do this in Excel 2013.
https://msdn.microsoft.com/en-us/library/office/mt574976.aspx
That link has documentation on ModelMeasures.Add Method but there are no real great examples I can find out there right now. If anyone has a good example that works in Excel 2013 to add a measure to a model using VBA, please share as the answer.
Best Example I could find, but not able to accomplish in Excel 2013: https://social.msdn.microsoft.com/Forums/en-US/c7d5f69d-b8e3-4823-bbde-61253b64b80e/vba-powerpivot-object-model-adding-measures-with-modelmeasuresadd?forum=isvvba
ORIGINAL POST:
I am trying to automate the adding of calculated fields to a powerpivot pivot table using VBA. I am not experienced in VBA.
When I manually add a Calculated Field using the below formula I am able to see the Calculated Field added. What is wrong with this VBA code?
Here is my code:
Sub Macro5()
Dim PvtTbl As PivotTable
Set PvtTbl = Worksheets("Sheet4").PivotTables("PivotTable6")
'Table1 is part of the PowerPivot data model and I have created a pivot table from Table1
PvtTbl.CalculatedFields.Add "column", "=IF(HASONEVALUE(Table1[TEXT1]), VALUES(Table1[TEXT1]), BLANK())"
'Selecting the pivot table and adding the new calculated field
Range("D7").Select
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").CubeFields("[Measures].[column]")
End Sub
The Error I get:
Run-time error '1004': Application-defined or object-defined error