Share via


Monitor and Debug Your Code: Part I

This article may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. To maintain the flow of the article, we've left these URLs in the text, but disabled the links.

MOD Spotlight

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

Stepping through Code Line by Line

By Evan Callahan

In trying to stay on course to reach a destination, a navigator uses various tools to keep track of the vessel's location and heading, and keeps a constant eye on the chart. Because of obstacles, wind conditions, or currents, changes in course are common, and a navigator has to anticipate problems and adjust accordingly. A change in course doesn't necessarily indicate a mistake; it's just part of the job.

When you program in Microsoft Visual Basic, you have to anticipate that errors will pop up here and there, both while you're programming and when you run your application. Microsoft Access comes equipped with many tools that, like a ship's compass or direction finder, help you keep track of where your application is and where it's heading. In this two-article series, you'll learn to monitor your Visual Basic code as it runs, and to understand what's really happening inside that computer when your application is running. You'll use Visual Basic tools to find bugs and then fix them and test to make sure they're taken care of.

To start the lesson, start Access and open the Ch06 Contacts database in the practice files folder (available for download; see end of article).

Stepping through Code Line by Line

Visual Basic provides tools that let you stop your code while it's running, and step through Visual Basic statements one by one. This way, you can see what's really going on in your code.

To watch code run, you first need to open it up and tell Visual Basic where you want to start watching it. Included with this article is some Visual Basic code available for download; see end of article for details. First, you'll open the Messages module and move to the Confirm function. You'll also tell Visual Basic to display the Debug toolbar, which contains tools to help you step through your code:

  • In the Database window, click the Modules shortcut.
  • Double-click the Messages module. Access opens Visual Basic and displays your code.
  • Scroll down in the Code window to view the Confirm function.
  • On the View menu, point to Toolbars, and then click Debug. Visual Basic displays the Debug toolbar, which has buttons that help you step through your code.
  • Drag the Debug toolbar to the top of the Visual Basic window, out of the way of the Code window.

Setting a Breakpoint to Stop Running Code

When you want Visual Basic to stop running your code midstream so that you can take a look at it, you set a breakpoint at the line of code you want to check. A breakpoint tells Visual Basic, "When you get to this line - but before you run it - stop everything and display the code." It's like calling time out in a basketball game: the action stops so that you can regroup, consider what you're doing right or wrong, and make adjustments. Then, when the time out is over, you allow your code to continue, letting the game go on as before.

Set a breakpoint at the beginning of a procedure. You'll set a breakpoint at the very beginning of the Confirm function, on the functionstatement itself. This way, you can take a look at the function each time it runs. To set and clear breakpoints, you use the gray margin that runs down the left side of the Code window.

Click the gray margin to the left of the Confirm function header line (the line that begins with Public Function Confirm), as shown in FIGURE 1.


FIGURE 1: Click the margin to set a breakpoint for this line.

A red dot appears in the margin, and the line of code changes to white text on red. This indicates that Visual Basic will stop when it encounters this code - in other words, as soon as it tries to run the Confirm function.

(Tip: If you set a breakpoint on the wrong line of code, click the red dot to clear the breakpoint, and then click next to the correct line.)

Run the procedure. Now try running the Confirm function from the Immediate window:

  • Click the Immediate window button.
  • Type ?Confirm("Isn't it wonderful?"), and press [Enter]. The Confirm function runs, but as soon as it starts, Visual Basic encounters the breakpoint you set (see FIGURE 2). It then switches back to the Confirm function in the Code window. When you view running code, you'll notice that Visual Basic displays a current statement indicator: a yellow arrow in the margin, and a yellow background highlighting the current statement.


FIGURE 2: The procedure stops running before it even starts.

Step through the code one line at a time. Nothing is happening right now because of the breakpoint - but in a sense, your code is still running. Information about the procedure, such as the values of local variables and arguments, is stored in your computer's memory. Visual Basic is ready to continue running the function as soon as you say so. You'll use the Step Into command, which tells Visual Basic to run one line of code, and then display the Code window again and return control to you:

  • Click the Step Into button. When you click the button, Visual Basic moves the current statement indicator to the statement that uses the MsgBox function (see FIGURE 3). Note that Visual Basic skips over two lines of code: the comment statement and the Dim statement. Because these lines of code don't perform an action, they never become the current statement. The line of code in FIGURE 3 uses the MsgBox function to display a message to the user, and assigns the return value of the function to the bytChoice variable. When you start the code running again, you can expect to see the message on the screen.
  • Click the Step Into button again. Access returns to the front and the current statement runs, which displays your message on the screen.
  • Click OK. When you answer the question in the message box, Visual Basic finishes running the statement by assigning your choice to the bytChoice variable. It then returns to the Code window and moves the current statement indicator to the next line of code: the If...Then statement that determines whether you clicked the OK button.
  • Click the Step Into button again. Because the condition in the If...Then statement is True - the bytChoice variable is equal to the vbOK constant - Visual Basic moves to the line of code directly underneath the If...Then statement, as shown in FIGURE 4.
  • Click the Step Into button again. Visual Basic sets the return value of the Confirm function to True, and then skips over the Else block, moving the current statement indicator to the End If statement, as shown in FIGURE 5. Here's where you can really see the value of stepping through your code. If the condition in the If...Then statement were false - if you'd chosen Cancel instead of OK - Visual Basic would have taken a different path through the code. By stepping through your code, you can see exactly which lines of code actually run, rather than trying to guess what's happening in your procedures.
  • Click the Step Into button two more times. The last two statements in the function run. When you step past the End Function statement, the Immediate window becomes active again (see FIGURE 6). This is where you started running the code - before it was stopped by the breakpoint - so this is the place Visual Basic returns you to when the code finishes running. The Immediate window displays the return value of the function, which is True.
  • Close the Immediate window.
  • In the margin, click the red dot next to the line with the breakpoint (the Confirm function's header line). This clears the breakpoint you set so that Visual Basic will allow the Confirm function to run without interruption in the future.


FIGURE 3: The current line of code.


FIGURE 4: When the
If...Then condition is True**, this line runs next.**


FIGURE 5: Visual Basic skips to the
End If statement.


FIGURE 6: After stepping past the
End Function statement, the Immediate window becomes active again.

Stepping from One Procedure to Another

So far, you've stepped through code in just one procedure. But you may have learned to separate your code into a procedure for each task. When you step through code in your application, Visual Basic can automatically step into each procedure you call so that you can follow the progression of your code.

To see this, you'll step through the BeforeUpdate event procedure on the Contacts form. This event procedure calls the Confirm function, so you'll get to see how Access runs both procedures.

Open the Contacts form's module and set a breakpoint. Before you can step through the code in an event procedure, you need to set a breakpoint in the function:

  • Switch to Access (click the View Microsoft Access button on the toolbar).
  • In the Database window, click the Forms shortcut.
  • Select the Contacts form, and then click the Code button. Visual Basic returns to the front and displays the Contacts form's module. The first procedure in the window is the Form_BeforeUpdate event procedure.
  • Resize the Code window so that it displays most of the code in the procedure (drag the upper-left corner of the window to make it larger).
  • In the gray margin, click next to the fifth line in the procedure - the one that calls the Confirm function. This sets a breakpoint on the statement, so code will stop running there (see FIGURE 7).


FIGURE 7: Click next to line that calls the
Confirm function.

Step through the event procedure. To run an event procedure on a form, you don't use the Immediate window - instead, you make the event occur on the form in Access, and the event procedure runs automatically:

  • Switch to Access.
  • Click the Form View button.
  • Click the Postal Code field, and delete the value in the field.
  • Press [Shift]+ [Enter] to save the current record. The BeforeUpdate procedure runs, and when Visual Basic encounters the breakpoint you set, it displays the event procedure in the Code window, as shown in FIGURE 8. The line of code in FIGURE 8, the next statement that will run, calls the Confirm function in the Messages module. When you step through this statement, Visual Basic will pass control to the Confirm function.
  • Click the Step Into button. Visual Basic switches to the Messages module and displays the Confirm function (see FIGURE 9).
  • Now that you're in the Confirm function, you could step through code line by line. Instead, you'll use another new technique to run several lines of code at once, stepping through the entire Confirm function.
  • Click the Step Out button. The Step Out command tells Visual Basic to run code until it finishes the current procedure, then pause again when it returns to the procedure that called it. When you click the button, the code in the Confirm function displays your message in Access, asking whether you want to save the record without a postal code.
  • Click Cancel. When the Confirm function ends, Access returns control to the Form_BeforeUpdate event procedure - remember, this is the procedure that called the Confirm function. Starting up where it left off, it moves the current statement indicator to the If...Then statement after the line that called the function, as shown in FIGURE 10. You can now continue stepping through the event procedure, or just tell Visual Basic to continue.
  • Click the Continue button. The BeforeUpdate event procedure finishes running.
  • Switch to Access. Because you chose the Cancel button in the message box, your code didn't allow the record to be saved - the pencil icon is still displayed in the record selector. In the next section, you'll try to save the record again.


FIGURE 8: The procedure runs until it reaches the line of code with the breakpoint.


FIGURE 9: When you step into a different procedure, Visual Basic displays it.


FIGURE 10: After Visual Basic returns from another procedure, code continues running where it left off.

(Note: When you're stepping through code in an event procedure, you can't switch back to the form until the event procedure finishes running. If you want to stop code from running, use the Reset command [Run menu] to end the procedure and reset all variables. The Reset command is also useful if an error occurs while you're stepping through code, when you may seem to be "stuck" in the procedure. If you can't fix the error and move on, use the Reset command to stop all code from running.)

Monitoring Variables and Other Values

Stepping through your code can help you figure out where it's going. But as your application progresses, the values of variables and fields stored in the computer's memory change, affecting how your application works. To really understand what's happening as your code runs, you'll want to find out the values of variables and fields along the way. You need a window into the computer's brain.

Using the debugging tools built into Visual Basic, you can find out the value of a variable, control, or other expression, e.g. when you use the Immediate window to find out the value of a property. However, there are more efficient ways to monitor values while your code is running, such as using the Locals window. In the Locals window, Visual Basic displays the values of all variables and objects that apply to the currently running procedure - the local variables and objects, as they're called. As code runs, the Locals window automatically reflects the changing values of the variables it shows.

Step through the event procedure again. To see how the Locals window works, you'll run the form's BeforeUpdate procedure one more time by trying to save the record again with the Postal Code field blank. Then, you'll monitor the value of a variable while the procedure runs:

  • Press [Shift]+ [Enter] to save the current record. When Visual Basic encounters the breakpoint you set in the BeforeUpdate event procedure, it displays the Code window. Now that the procedure is running, you can check the Locals window to see the value of the blnOK variable, which the procedure uses to determine which choice you make in the message box.
  • Click the Locals window button. Like the Immediate window, the Locals window can be docked at the side or bottom of the Visual Basic window, or it can be a floating window.
  • Drag the title bar of the Locals window up to the center of the Visual Basic window, and then position and resize the window so that you can see as much of your code as possible. The Locals window lists three objects, the third of which is the blnOK variable. As you can see in FIGURE 11, the blnOK variable is currently set to False. (Tip: In the Locals window, you may notice the entry for "Me" listed above the two variables. This entry, which you'll find at the top of the Locals window whenever an event procedure is running, represents the current form or report object - in this case, the Contacts form - with all its controls and properties. Using this entry, you can view properties of the form and its controls as you monitor your application. To display properties of the form, click the small box with a plus sign to the left of the Me entry. This expands a long list of properties and objects belonging to the form. To view the properties of controls on the form, locate them in the expanded list and click their plus signs.) You're ready to step through the event procedure and watch its variables. In the previous run through this code, you stepped into the code of the Confirm function. This time, you'll learn how to save time by skipping over procedures that you aren't interested in. To run a line of code without stepping into the procedure it calls, use the Step Over command - it works just like the Step Into command, except that it runs procedures without pause.
  • Click the Step Over button on the toolbar. The Confirm function runs, displaying its message box.
  • Click OK. Visual Basic displays the BeforeUpdate event procedure again - although you stepped over the Confirm function, you are still stepping through code line by line. The Confirm function in the line you just stepped over should have set the blnOK value based on your choice in the message box.
  • Sure enough, the Locals window shows that the blnOK variable is now set to True -indicating that you chose OK in the message box (see FIGURE 12). You can now continue stepping through the event procedure.
  • Click the Step Over button again. Because the value of the variable is True - which means that NotblnOK is False -the If...Then block doesn't run (see FIGURE 13).
  • Click the Step Over button three more times. The BeforeUpdate event procedure finishes running, allowing the record to be saved in the Contacts form.
  • Close the Locals window.


FIGURE 11: The value of the
blnOK variable is False**.**


FIGURE 12: The value of
blnOK is now True**.**


FIGURE 13: The
If...Then block doesn't run.

Other Techniques for Monitoring Code

The Locals window is useful when you want to monitor the value of a variable or other object continuously while your code runs. But there are several other techniques you can use for monitoring the progress of your code.

Set watch expressions in the Watch window. The Locals window shows only the variables and objects in the current procedure. Sometimes, you may want to view the values of variables or objects outside the current procedure - variables shared by your entire application, for example. To specify exactly what data you want to monitor, use the Add Watch or Quick Watch command (from the Debug menu). When you run your code, the values of each expression you've specified are displayed in the Watch window.

Send values or messages to the Immediate window. If there is a certain point in your code where you want to check the status of your procedure or the value of a variable, you can send a message to the Immediate window by using the Print method of the Debug object. Anywhere you want to send output to the Immediate window, insert a line and type Debug.Print followed by the expression you want to display. For example, you might add the following line of code in the BeforeUpdate procedure instead of using a watch expression:

Debug.Print "The Confirm function returned: "; 
      blnOK

This way, each time the procedure runs, it reports the value of blnOK in the Immediate window. You don't need to set a breakpoint or step through code at all - you can just check the Immediate window after the procedure finishes running.

Display message boxes. If you want to report on the progress of a procedure while it runs, but you don't want to check the Immediate window each time, you can instead display messages to yourself using the MsgBox function. For example, you could place the following line of code in the BeforeUpdate procedure:

MsgBox "The Confirm function returned: " 
      & blnOK

Change code as it runs. In most programming systems, you can't change code while it's running. But in Visual Basic, you have the flexibility to change the values of variables or code itself while you step through line by line. Suppose you're monitoring a variable and you notice it doesn't have the value you expect. If necessary, you can add a line of code to your procedure and continue running it.

Set the current statement. Normally, when stepping through code, you don't control the order in which Visual Basic statements occur. However, if you're stepping through code and would like to change which statement runs next, you can use the Set Next Statement command (from the Debug menu). This is especially useful if you change a line of code that didn't work as expected, and you want to run it again without restarting the procedure.

The strategy you select to monitor and debug your code depends on what problems you're trying to diagnose and how often you need to check what's happening. As you program in Visual Basic, you'll learn which techniques are most appropriate for each debugging task.

Conclusion

The procedures you've stepped through so far aren't broken - although you've learned more about how they work by monitoring them more closely, they seem to be working just fine. But what if code isn't working as you'd planned? This is when Visual Basic tools come in especially handy. In the next installment of this series, you'll learn to check your Visual Basic code as you enter it, and then fix any errors you find.

From Microsoft Access 2000 Visual Basic for Applications Fundamentals by Evan Callahan. Reproduced by permission of Microsoft Press. All rights reserved.

Evan Callahan owns Callahan Software Solutions, a database consulting firm specializing in Microsoft Access, as well as in Visual Basic and Web publishing. He worked for Microsoft from 1989 to 1995, where he created documentation, online Help, and sample applications for Access and Visual Basic.