0

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.

Community
  • 1
  • 1
Adjit
  • 10,134
  • 12
  • 53
  • 98

2 Answers2

0

Try this:

Excel.Workbook wb = null;
try
{
    wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
    if (wb != null) wb.Close(true);
}
Jon B
  • 51,025
  • 31
  • 133
  • 161
  • Also, @krillgar is right - you probably want the close in a `finally` block instead of `catch`. – Jon B Apr 09 '14 at 18:51
  • why is that? the only time I would need to close the book would be if there is an exception. – Adjit Apr 09 '14 at 18:52
  • Then you're fine as is. `try { open } finally { close }` is a pretty common pattern, hence the assumption that it's what you really intended. – Jon B Apr 09 '14 at 18:53
0

You want finally instead of catch. A finally block will always execute, whether there is an exception or not. Even if there isn't an Exception thrown, you still want to close the workbook to clear up the resources.

Something like this should be what you need.

Excel.Workbook wb = new Excel.Workbook();

try {
    wb = exApp.Workbooks.Open(@file);
    //More code...
}
catch (Exception ex) {
    // Do any error handling you need/want to here.
}
finally {
    // If there's a way to determine if the workbook is open, try that first.
    wb.Close(true);
}
krillgar
  • 12,596
  • 6
  • 50
  • 86