Using the Watch Window
The watch window is used to monitor expressions as your code runs. Unlike the Locals window that you can use to observe your variables as your code runs, you can use to watch window to observe whole expressions that you enter in the window. The expression can be a variable, a call to a function, or any other valid expression.
To display your Watch window, do the following:
- On the Visual Basic Editor menu bar, click on View
and select Watch Window
from the menu.
–or–
- Click the Watch Window
button on the Debug toolbar.
Adding a Watch Expression
There are three types of watch expressions in VBA.
-
Watch Expression
-
This displays the expression you’re watching and its value in the Watch window when your program enters break mode.
-
Break When Value Is True
-
This option causes VBA to enter break mode when the expression you’re watching becomes true during code execution. This helps you to determine the point at which an expression passes a test and what happens next.
-
Break When Value Changes
-
This type of Watch expression causes VBA to enter break mode if the value of the variable or property changes from its initial value. This helps when you want to observe exactly when a variable or property changes and what caused the change.
To add a Watch expression, do the following:
- On the Visual Basic Editor menu bar, click Debug
and select Add Watch
from the menu.
- In the Expression
text box, enter the expression that you want to monitor.
- Under Context
, select the procedure or module name that you want to set as the scope for the watch expression using the Procedure and Module drop-down lists.
- Under Watch Type
, select the Watch type you want to create from the three options. This determines how VBA will respond to the watch expression.
- Click OK
when done.
Tip
: A watch expression can be particularly useful when you have a loop with a lot of iterations and you want to enter break mode near the end of the loop counter. Using Step Into
to step through the code can be time-consuming for a very large loop. With the Watch window, you can set an expression that watches the loop counter and then breaks when it reaches a certain value.