Search code examples
c#exceladd-inoffice-automationvba

Read the calculated values from Excel using AddIn Formulas and Microsoft Object Library


we are trying to retrieve a calculated value from a cell which has add-In formulas in it. The sample add-in "myUtilityl.xla" is working properly in excel. It retrieves value for the addin function =ISOWEEKNUM(F9). But we are unable to retrieve the value programatically using C# & Microsoft Object Library. The add-In "myUtilityl.xla" is attached to Excel. Environment is VS2010

I am providing the sample code here.

        string path = @"C:\Test.xls";
        Workbook theWorkbook;
        Worksheet theWorksheet;
        Range readRange;
        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();            
        theWorkbook = app.Workbooks.Open(path);
        Sheets theSheets = (Sheets)theWorkbook.Worksheets;
        theWorksheet =  (Worksheet)theWorkbook.Worksheets.get_Item("Sheet1");            
        readRange = theWorksheet.get_Range("B1");            
        MessageBox.Show(Convert.ToString(readRange.Value));
        //theWorkbook.Save();
        app.Workbooks.Close();

I am new to Microsoft Object library. Any help or clue will be very helpful.


Solution

  • Well Brijesh its working now. The only thing that was missing was that we have to open the xla. app.Workbooks.Open(xlaFilePath); Then it started working.. Thank you very much. i am posting the code here anyways

            string path = @"C:\Test2.xls";
            string xlaPath = @"C:\Test2.xla";
            Workbook theWorkbook;
            Worksheet theWorksheet, theWorksheet2;
            Range readRange;
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Workbooks.Open(xlaPath);
            theWorkbook = app.Workbooks.Open(path);
            theWorksheet2 = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet2");
            theWorksheet2.get_Range("A3").Value = 7;
            theWorksheet2.get_Range("A4").Value = 7;
            theWorkbook.RefreshAll();
    
            theWorksheet = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet1");           
            readRange = theWorksheet.get_Range("A1");
            Console.WriteLine(Convert.ToString(readRange.Value));
            Console.ReadLine();            //theWorkbook.Save();             
            theWorkbook.Close();
            app.Workbooks.Close();
    

    Above code inputs two values into cells of sheet2 and the VBA UDF calculated value is retrieved.