There is one issue that I have been having, and I am trying to fix it because if the program crashes (the excel file stays open in the background), or the user has the excel workbook already open the program will crash because it is unable to open an already opened workbook.
Was trying to counter this issue by using the method from this question : C#: How can I open and close an Excel workbook?
But much to my dismay no success.
With this setup I get an error at wb.Close(true)
saying I cannot use an unassigned local variable. To me it kind of makes sense, but I don't see how that is the case. It's not like an if
statement where if the condition isn't met it doesn't jump in the loop. The try
block will always execute.
Excel.Workbook wb;
try
{
wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
wb.Close(true);
}
I also tried this way :
Excel.Workbook wb = new Excel.Workbook();
try
{
wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
wb.Close(true);
}
but this time, I get a error: 80040154 Class not registered
on the line Excel.Workbook wb = new Excel.Workbook();
when running the program. again... don't know why.
Any help is greatly appreciated.