Tracking Down Errors

Gaining more experience with VBA makes it easier to find those pesky errors. Some error messages can be challenging, like the one in Figure 7 below:

Figure 7. Syntax error in module out of the current context.

When this error appeared, there was no way to enter the debugger at the line that failed. It was necessary to step through the code a line at a time to find that the error happens while trying to display a dialog box called "Wiz1". But the syntax of this line is correct! Where is the syntax error?

There are macros in another module sheet assigned to controls in the Wiz1 dialog. When the Show statement activates the dialog, VBA parses the macros and finds an error. The debug window context is in Sub Main in a different module sheet, so VBA can't show the error—it just displays a general message. An easy way to find the error is to stop the macro and select the dialog sheet for the Wiz1 dialog. Then run the dialog using the Run Dialog button in the Forms toolbar, or the Tools/Run Dialog menu selection. This will force syntax checking of the event procedures linked to the controls in the dialog. The debug window will open and point at the mistake. Alternatively, set a breakpoint in the module containing the init macro for the dialog and step through the code from there. There's even a third way, which is to use the Step Into button in the VBA toolbar to step into the dialog's macro code.

With a bit of practice the developer can get pretty good at deciphering the error messages to understand their deeper, hidden meanings. In Figure 8 below, a dot is missing from the front of the reference to an edit box for the chart title. The VBA parser says "Where's my object?" while the human says "Huh?"

Here's another example where learning to think like the VBA parser helps to get past a confusing error message. In Figure 9 below, the brackets around a button name are missing. Instead of typing DialogSheets("GWiz3") to refer to the dialog box, an object variable called GWiz3 was defined. VBA looks at GWiz3 and understands it is a dialog box object, so it next looks at ButtonWiz3Next and expects to find a property or method by that name. Since it doesn't, Excel displays an error dialog. Perhaps a better error message would be "Object doesn't support ButtonWiz3Next property or method". The figure shows the lines that were typed in the debugger's immediate window to figure out the problem.

Figure 8. True meaning: "Shouldn't there be a dot in front of this line?

Figure 9. Learning to think like the VBA parser.