Search code examples
c#excelformulacomexception

use object for adding formula to Excel c#


I want to add a formula as shown in the third component. When i remove the "=" everything works. But for adding a formula to excel, you need the "="... When I add the "=", the program doesn't work anymore... Then I receive the error: System.Runtime.InteropServices.COMException was unhandled HResult=-2146827284 Message=Exception of HRESULT: 0x800A03EC

Any ideas?

Thank you

        static void Main(string[] args)
    {
        //seed
        var listComponents = new List<Component>
        {
            new Component() {Name = "Vc1", Cell = "A1"},
            new Component() {Name = "Vc2", Cell="B1"},
            new Component() {Name = "Nv", Cell="A2",Calculation = "=((A1+B1)/2)/0,1"}
        };


        //program
        //create excel object, workbook and worksheet
        object misValue = System.Reflection.Missing.Value;
        var excelapp = new Excel.Application();
        Excel.Workbook newWorkbook = excelapp.Workbooks.Add();
        Excel._Worksheet worksheet = (Excel.Worksheet) excelapp.ActiveSheet;

        excelapp.Visible = false;

        //cycle through components
        foreach (var component in listComponents)
        {
            if (component.Calculation != null)
            {
                Excel.Range rng = worksheet.Range[component.Cell];
                rng.Formula = component.Calculation;
                String formula = rng.Formula;
                Console.WriteLine(formula);
            }
        }

        newWorkbook.Close(false, misValue, misValue);
        excelapp.Quit();

        Console.ReadLine();

    }

Solution

  • I needed to change the comma"," in the formula to a point".". Although in my local settings, excel uses the "," apparantley in the object it only uses the standard value ".". Thanks again for your help!