Please Help!
// ERROR System.Runtime.InteropServices.COMException: '0x800A03EC'
Excel.PivotField newMeasure = calculatedFields.Add("NewMeasure", formula, true);
AddMeasure(task.attachment.FullName,
WorkSheetIndex: GetWorksheetIndex(task, "Promo Voice total"),
pivotTableName: "pt1",
MeasuresName: "myesures",
formula: "=A1+B1");
public static void AddMeasure(string file, int WorkSheetIndex, string pivotTableName, string MeasuresName, string formula)
{
Excel.Application excelApp = new Excel.Application();
try
{
Excel.Workbook workbook = excelApp.Workbooks.Open(file);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[WorkSheetIndex];
Excel.PivotTable pivotTable = worksheet.PivotTables(pivotTableName) as Excel.PivotTable;
if (pivotTable != null)
{
Excel.CalculatedFields calculatedFields = pivotTable.CalculatedFields();
if (calculatedFields != null)
{
Excel.PivotField newMeasure = calculatedFields.Add("NewMeasure", formula, true);**// HERE ERROR `System.Runtime.InteropServices.COMException: '0x800A03EC'`**
((Excel.PivotField)pivotTable.PivotFields($"{MeasuresName}")).Orientation = Excel.XlPivotFieldOrientation.xlDataField;
if (newMeasure != null)
{
pivotTable.AddDataField(newMeasure);
Console.WriteLine($"Measure '{MeasuresName}' added successfully.");
}}}
workbook.Save();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
}
// ERROR System.Runtime.InteropServices.COMException: '0x800A03EC'
Excel.PivotField newMeasure = calculatedFields.Add("NewMeasure", formula, true);
VB.NET
I quickly wrote this code in VB.net. It works as expected. Later in the day if I get the time, I will update the post with the C# code if you are still stuck...
Before:
Code:
Output
C#
Option Strictis switched off by default in VB.Net and hence it allows implicit data type conversion. If you do a straight conversion of the code that I gave above to C# it will error out on the line as shown below. I believe this is the error that you were getting...In VB.net when you right click on your project and select "Properties", you get the
Compiletab (as shown below) where you can tweak theOption Strictproperty.This tab is missing in C# (as shown below).
This setting does not exist in C#, because like I mentioned above implicit data type conversion is not allowed in C#.
So how do we tackle this? We use the dynamic keyword. This keyword brings Option Strict Off equivalent functionality to C#.
Try this code. I have tested it. It works.