I have following code that does a name check in a worksheet collection and return true if that worksheet has been found.
foreach (Excel.Worksheet sheet in xlApp.Worksheets)
{
if (sheet.Name.Equals("myXlSheet"))
{
resultWorkSheet = (Excel.Worksheet)xlApp.Worksheets.Item["myXlSheet"];
return true;
}
}
For some reason, xlApp.Worksheets would give 0x800A03EC Error sometimes. It doesn’t seem to happen all the time though. And I can’t reproduce the same error in development environment, which really baffles me.
So what’s problem here? Any good ideas or suggestions? Thanks.
Your code does not specify the workbook you are using, so a call to Worksheets defaults to the active workbook (Old yet relevant MSDN). If somehow the current user’s active workbook does not contain that sheet or there were no workbooks, then an error would occur. Obviously, this shouldn’t happen but improbable things almost always happen sometimes in programming.
I haven’t tested this, but I’m assuming updating your problem line to this should work:
Edit: I thought about it some more and realized that you didn’t actually indicate where the error happens.
You should check to make sure there are workbooks before you attempt to do the your for loop. You can check this, by getting the count something like: