HRESULT: 0x800401A8 when getting UsedRange of Worksheet

1

I'm trying to open an Excel Sheet, get the UsedRange and loop through it.

This already worked once, but then I had the exception

COM object that has been separated from its underlying RCW cannot be used

after using

System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);

Note that the exception kept coming up in the code below as well, not when actually releasing. I did this the first time and since then I couldn't get the code below to work. Sadly, I don't know at which line exactly he crashed anymore.

Because the exception kept comming up, I restarted my PC and since then when trying to access UsedRange, I get an Exception:

System.Runtime.InteropServices.COMException: "Ausnahme von HRESULT: 0x800401A8"

Here is the code:

using Excel = Microsoft.Office.Interop.Excel;
....
var xlApp = new Excel.Application();
var xlWorkBook = xlApp.Workbooks.Open(file);
Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets["Tabelle1"];
for (int i = 1; i < xlWorkSheet.UsedRange.Rows.Count; i++)
{ ...

This worked once, so I'm thinking the COM object is still not working correctly. (Like in the first exception)

What can I do to make it work again?

c#
excel
com
asked on Stack Overflow Oct 1, 2019 by Annabett

1 Answer

0

What happened is that I accidentally closed the Workbook and quitted the App in the foor loop and not after it. I accidentally put it in front of the }.

for (int i = 1; i < xlWorkSheet.UsedRange.Rows.Count; i++)
{ 
  ...
  xlWorkBook.Close(false);
  xlApp.Quit();
}

Of course, that's supposed to go after the loop. You cannot access a variable in a workbook that isn't open anymore.

So if you've got the error, check if the workbook is actually really open.

Shame on me.

answered on Stack Overflow Oct 1, 2019 by Annabett

User contributions licensed under CC BY-SA 3.0