Respond to Excel Errors in .NET

In .NET, errors are reported as exception objects. You handle errors using the VB.NET Try...Catch...End Try construct. When .NET receives an error from a COM component, such as Excel, it checks the COM error code (COM identifies errors as HRESULTs which are 32-bit numbers) and tries to map that error to one of the .NET exception classes, such as DivideByZeroException.

If .NET can’t map an HRESULT to a .NET exception class, it reports that error as a COMException. A COMException includes Source and Message properties that are filled in if they are available, plus it includes the HRESULT as an ErrorCode property.

How it works

When working with Excel from .NET, you will find that most errors are reported as COMExceptions and that the Source and Message properties are sometimes, but not always, helpful. For example, referring to a worksheet that doesn’t exist causes an COMException with Source equal to “Microsoft.Office.Interop.Excel” and a Message property “Invalid index.” But setting a cell to an invalid value is reported as a COMException with an empty Source property and a Message property set to “Exception from HRESULT: 0x800A03EC.”

The following code illustrates causing, catching, and reporting different types of Excel errors in .NET:

 Private Sub cmdCauseErrors_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCauseError.Click Try ' This worksheet (9) doesn't exist. m_xl.ActiveWorkbook.Sheets(9).Range("B2").value ...

Get Excel 2003 Programming: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.