mardi 13 juin 2017

How do I instantiate an empty workbook using Excel Interop?

I have this code:

using Excel = Microsoft.Office.Interop.Excel;
var excelApp = new Excel.Application();

if (CurrentWorkbook.Version == "Release")
{
}
else
{
      if (File.GetLastWriteTime(CurrentWorkbook.DataPath + CurrentWorkbook.FileName + ".xlsm").Date != DateTime.Today)
      {
           var MRPData = excelApp.Workbooks.Open(@"H:\@Business_Reporting_Today\MRP\Blank MRP Workbook.xlsm", 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
      }
}

and then later in my project I have:

if (CurrentWorkbook.Version == "Release")
{
}
else
{
    excelApp.DisplayAlerts = false;

    MRPData.Close(0);
    Marshal.FinalReleaseComObject(MRPData);
    excelApp.Quit();
    Marshal.FinalReleaseComObject(excelApp);
}

However since I declared MRPData in an if code block, it of course, "Does not exist in current context," in the later code block. I have tried to pull the declaring of the variable out of the code block with this:

var MRPData = new Excel.Workbook();

This gets rid of the compile errors but gives me a run time error that says, ": 'Retrieving the COM class factory for component with CLSID {00020819-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).'"

How do I fix this problem, so that I can declare it outside of the if code block?

Aucun commentaire:

Enregistrer un commentaire