0

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.

woodykiddy
  • 5,622
  • 13
  • 49
  • 92

2 Answers2

0

Have you Googled that error code? I see tons of results regarding Excel interop:

Excel interop boils down to COM, so it doesn't really matter what language/context you get the error in; it could still be a clue to what you're doing wrong.

It looks like its a max length of some sort, be it the text in a cell, or number of cells, etc.

Community
  • 1
  • 1
Jonathon Reinhart
  • 116,671
  • 27
  • 221
  • 298
0

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:

resultWorkSheet = (Excel.Worksheet)sheet.Parent.Worksheets.Item["myXlSheet"];

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:

if (xlApp.Workbooks.Count != 0) 
{
   //Your loop here
}
Daniel
  • 12,569
  • 2
  • 34
  • 57
  • Thanks, Daniel. I think you brought up a pretty good point here. I had a brief chat with that client and he told me he sometimes would be working on multiple workbooks at the same times, switching from 1 workbook to another. As you mentioned, it'd give error if active workbook doesn't have any sheets. – woodykiddy Oct 16 '12 at 04:11
  • I will give it try using `sheet.Parent`. The API description is not very useful though... (Returns the parent object for the specified object.) Wish they had provided more descriptions and examples. – woodykiddy Oct 16 '12 at 04:16