Debugging

Debugging is a process of finding and fixing errors in program code. The following is a typical way of using the debugger to step through the code and identify errors:

  1. Add breakpoints at particular lines of code, where you suspect errors, by clicking at the grey left margin of the code window.
  2. Press F5 to execute the VBA code.
    • VBE executes the code until the first breakpoint is met, putting the code into break mode. The particular line of code at the breakpoint is not executed yet.
  3. Choose one of the three operations at the breakpoint:
Operation Shortcut key Action of the debugger
Continue F5 It continues executing until the next breakpoint.
Step Into F8 If the current point beak does not have a procedure (a Function or Sub procedure) to be called, it executes the line of code. Otherwise, it goes into the procedure. To step out of a procedure, press Ctrl+Shift+F8.
Step Over Shift+F8 If the current point beak has a procedure to be called, it treats the procedure as a single instruction, instead of going into the procedure.

The operations listed in the table above can alternatively be accessed from the Debug menu on the menu bar.

  1. As you step through the code to identify possible errors, you can hover the mouse pointer over any variable to examine its current value. If VBE does not display the value, enable the Auto Data Tips option in the Editor tab of the VBE Options dialog box. (Choose Tools | Options from the menu bar to display the Options dialog box.)

Alternatively, you may use the Immediate window to check the current value of a variable when the code is in break mode. For example, enter the following statement in the Immediate window:

? myVariable

In addition, you may use the Locals window and the Watch window (which are the topics to be discussed next) to monitor the values of variables when debugging your VBA code.

 

Debugging

Locals window

Watch window

Call stack

A debugging example from scratch

The MsgBox function