Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Can anyone help me convert this excel macro to c#. I need to add
the calculated field to my pivot table programmaticlly.


VB
ActiveSheet.PivotTables("MFRData").CalculatedFields.Add "calc", _
       "=order_qty *  +order_qty * 10%", True
   ActiveSheet.PivotTables("MFRData").PivotFields("calc").Orientation = _
       xlDataField
Posted
Updated 15-Jan-12 8:28am
v2

1 solution

C#
Excel.PivotTable pt = xlSheet.PivotTables("MFRData");
Excel.PivotField ptField
Excel.CalculatedFields cfField = pt.CalculatedFields();
ptField = cfField .Add("calc", "='order_qty' * +'order_qty' * 10%", true);
pt.AddDataField(ptField , " calc", Excel.XlConsolidationFunction.xlSum);
 
Share this answer
 
Comments
gianpy67 4-Aug-15 10:08am    
Hi, this row
ptField = cfField .Add("calc", "='order_qty' * +'order_qty' * 10%", true);
is error why ??
gianpy67 4-Aug-15 11:00am    
When the line command is
pt.AddDataField(ptField , " calc", Excel.XlConsolidationFunction.xlSum);
error, why ??
SG2107 19-Aug-15 8:03am    
Is this code working for anyone?
I am getting following error in line :
pt.AddDataField(ptField , " calc", Excel.XlConsolidationFunction.xlSum);

Error: {"The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))"} System.Exception {System.Runtime.InteropServices.COMException}

Can anyone help, I need to find Percentage of 2 pivot columns
gvijay94 21-Sep-18 7:54am    
Instead of this line
pt.AddDataField(ptField , " calc", Excel.XlConsolidationFunction.xlSum);

please add below 2 lines like this
ExcelLib.PivotField CalculatedPivotField = (ExcelLib.PivotField)pivotTable.PivotFields("calc");
CalculatedPivotField.Orientation = ExcelLib.XlPivotFieldOrientation.xlDataField;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900