Debug Excel .NET Applications

Excel projects do not report errors that occur in Excel the way you might expect. Instead of halting execution when an error occurs, Excel projects just continue on as if nothing happened. This can be very confusing since the code exits the procedure where the error occurred and no warning is displayed. A good way to see this behavior is to try to activate a worksheet that doesn’t exist. For example:

   Private Sub ThisWorkbook_Open(  ) Handles ThisWorkbook.Open
   ThisApplication.Sheets("doesn't exist").activate(  ) ' Error! Code exits.
    ' Set the ActiveSheet object
    If ThisApplication.ActiveSheet.Type = Excel.XlSheetType.xlWorksheet Then 
       ActiveWorksheet = CType(ThisApplication.ActiveSheet, Excel.Worksheet)
    Endif
    ' Find the control on the sheet and hook up its events.
    cmdReformat = CType(FindControl("cmdReformat"), MSForms.CommandButton)
   End Sub

In the preceding code, ActiveWorksheet and cmdReformat are never set because Excel can’t find the worksheet to activate. The project keeps running, though, and you’re just left to wonder why none of your event procedures are working.

You can prevent this by telling Visual Studio .NET to break into the debugger when exceptions are thrown, as described in the following steps:

  1. From the Debug menu, choose Exceptions. Visual Studio .NET displays the Exceptions dialog box.

  2. Select Common Language Runtime Exceptions and select When the exception is thrown: Break into the debugger, as shown in Figure 5-20, then ...

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.