excel interop exception 0x8002000B

0

I have the following code to open a workbook and keep just one sheet:

//Get a new workbook.
oWB = app.Workbooks.Add(Missing.Value);

int len = oWB.Sheets.Count;

for (int i = 1; i < len; i++)
{
    ((Worksheet)oWB.Sheets[i]).Delete();
}

oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.ActiveSheet;

This code has worked for many years in many client configurations.

For some reason, I have a customer with excel 2013 (in Hebrew), and on his machine I get the following exception:

System.Runtime.InteropServices.COMException (0x8002000B): Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
   at Microsoft.Office.Interop.Excel.Sheets.get__Default(Object Index)
   at IOSIGHT.Win.ActiveReports.ExcelHelper.StartExcel()

If I understand the situation, it seems that for some reason the workbook was left with no sheets, so then call to oWb.ActiveSheet throws an exception. Any idea what caused this?

And yes I saw other posts on the same exception, but my code does not match their scenarios.

c#
.net
excel
office-interop
asked on Stack Overflow Jul 11, 2013 by omer schleifer • edited Dec 10, 2020 by Osama Rizwan

1 Answer

3

Loop backwards so you do not try to remove an index that no longer exists.

E.g for (int i = len; i > 1; i--) ...

answered on Stack Overflow Jul 11, 2013 by Alex K.

User contributions licensed under CC BY-SA 3.0