Community Pick: Many members of our community have endorsed this article.

Debugging VBA and VB6 Applications

Martin LissKeep everyone healthy; Get Vaccinated
CERTIFIED EXPERT
Almost 50 years of programming experience. Click '+ More' in my "Full Biography" to see links to some articles I've written.
Published:
Updated:
Edited by: Andrew Leniart
This article describes how to debug VBA and VB 6. The images in the article are from VB 6, but if you are debugging a VBA application what you will see will be similar. If you are using VBA and don't see something that's referred to here then please send me a message.

The debugging module can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.



There is also a companion Debug Toolbar that looks like the following and that toolbar will be the focus of this tutorial:



If you can't find that toolbar then you can add it to the menus by pulling down the View menu item, clicking Toolbars, and checking Debug.


Components of the Debug Toolbar

They are (in order)

o Continue (toggle)

o Break

o End

o Toggle Breakpoint

o Step Into

o Step Over

o Step Out

o Locals Window

o Immediate Window

o Watch Window

o Quick Watch

o Call Stack


The following is an explanation of what each button does. (I've changed the order a bit.)


Start/Continue (toggle)

Availability: Design time and when in break mode

Shortcut: F5


Clicking Start not surprisingly starts your program running just likes F5 does. After Start is clicked it is disabled.


Break

Availability: Run time only

Shortcut: CTRL+BREAK


Once your program has started, and, for example, the main form has loaded and it is ready for interaction with the user, pressing the Break button pauses the execution of the program and takes you to the edit window for the form. Pressing the button also has the effect of enabling the Start button and toggling it to Continue. At this point, you can do things like adding or changing code in the Click event of a command button. Pressing the Continue button takes you back to Run mode where you can now click the command button to see the effect of your change. The breaking/changing code/continuing/testing code cycle can, of course, be repeated as many times as needed.


Immediate Window

Availability: At all times but it is read-only at run time

Shortcut: CTRL+G


The Immediate Window is one of three debugging windows that allow you to monitor the values of expressions and variables while stepping through the statements in your application. The other two windows (which I'll discuss later) are the Watch window and the Locals window.


There are at least four very useful things that you can do with the Immediate Window.


1) Display the results of Debug.Print statements


As an example let's assume you have the following code in your command button.

 

Private Sub Command1_Click()

    Dim lngCounter As Long
    
    For lngCounter = 1 To 3
        Debug.Print lngCounter * 20
    Next
    
End Sub


When you click the command button, the Debug.Print statements will cause the value of lngCounter * 20 to be printed to the Immediate Window so if you then click the Immediate Window button you will see the following.



2) Check the value of variables


While you are in break mode you can display the values of the global variables in your form. For example, if you have a Private intMyInt As Integer statement you can see what the value of intMyInt is by typing ?intMyInt in the Immediate Window and pressing return. The same thing can be accomplished by typing print intMyInt. The values of such things as command button and label captions, textbox text, etc. can be displayed as well. In addition, you can see the value of variables in a Sub or Function if you are at a break point but more about that later.


3) Change the value of variables and properties


If you type something like intMyInt = 7 (note that you don't use the question mark) VB will change the value as requested and you can continue execution using that new value. This can be a big time-saver when debugging. A big time-saver when designing a form is that you can, for example, change the value of the Left property of a command button and immediately see what it looks like on the form. If it still needs adjusting you can change it again and again if necessary until you get it right. In this case, you will have to record that value in the IDE, but it is much better than having to repetitively change the value, run the program, see how it looks, stop, change the value, run the program, etc. until you get it right.


4) Run code


It's nice to be able to display the values of variables in the Immediate Window but if you have a set of variables you need to display and you need to do it more than once, retyping them can be tedious. Fortunately, there's a better way. You can simply create a Sub that you run from the Immediate Window! As an example let's assume that you have 3 variables that are involved in your debugging efforts. You would then create a Sub that looks something like this.

 

Private Sub DisplayDebugValues()
    Debug.Print "The value of intMyInt is " & intMyInt
    Debug.Print "The value of lngCounter is " & lngCounter
    Debug.Print "The value of strSomeThing is " & strSomeThing
End Sub

Once you have that Sub you can display them any time you are in break mode by simply typing the name of the Sub in the Immediate Window, pressing Enter, and the three values will be displayed. Note that in order for this to work, the variables need to be global in scope. In other words, they need to be defined as Public in a module or in the Declarations section of a form or sheet.


Toggle Breakpoint

Availability: At design time and when in break mode

Shortcut: F9


A breakpoint is a place at which the program will pause until you manually let it resume.  To set a breakpoint you can either place the cursor on the line where you want the code to pause and then press F9 or, more simply, just click in the margin of that line. When you do either of those things VB places a red bullet in the margin and also highlights the line in red. Here is an example where a breakpoint has been placed on a line.


 

If you then run the program and the breakpoint is reached, VB will highlight the line's code in yellow and then wait there for you to do whatever you want. One of the things that you might want to do is to check the value of variables in the Sub or Function (these are called Local variables) and there are several ways to do that while the code in the Sub or Function is paused. You can hover the mouse over a variable and VB will pop up a little box that shows the variable name and its value, or you can bring up the Immediate Window as we discussed previously, or you can highlight any valid expression and click the Quick Watch window or you can click the Locals Window. The latter two will be described later.


I should mention here that while F9 will toggle a breakpoint on and off, CTRL+SHIFT+F9 will turn all breakpoints off.

Quick Watch

Availability: Always available but only useful when in break mode

Shortcut: SHIFT+F9


As mentioned previously if you highlight a variable or a valid expression, clicking the Quick Watch button will show you the value. Here's an example where I've done that with txtSquare(intSquare).Text (which is a valid expression) and you can see that the value is Y. Clicking the Add button allows you to add a watch, but more about that later.



Locals Window

Availability: Always available but only useful when in break mode

Shortcut: (None)


Here's what you would see at the same point in the program if you opened the Locals window. I've expanded the information for the form (referred to as Me) and the information for the Controls.Item6.



Step Into

Availability: Design time and when in break mode

Shortcut: F8


Step Into allows you to follow the execution of your program line by line as VB executes it. If you press F8 at Design Time the program will start just like it would if you pressed F5 (Start), except that after it is started VB will pause the program just before the first executable line and it will highlight that first executable line in yellow. It will also place a yellow arrow in the left-hand margin. When you press F8 while in break mode VB executes the current line and then pauses at the next line. In either case, you can step through the whole program if you desire by repetitively pressing F8. Note that at any time during that process you can use the Quick Watch, Immediate or Locals window as described above.


One very useful feature that is available while stepping through the code is the ability to drag the yellow arrow to any executable line of code, thus allowing you to skip or repeat lines.


Step Over

Availability: Design time and when in break mode

Shortcut: SHIFT+F8


Step Over is similar to Step Into except that as its name implies it will step over or skip the current line. Note that it doesn't skip the execution of the line, only the stepping through. In other words, if the current line is a call to a long Sub that you don't really care about, stepping over will execute the call and then pause at the line following the call.


Step Out

Availability: Design time and when in break mode

Shortcut: CTRL+SHIFT+F8


If you are in the same long sub as mentioned above, pressing Step Out will leave that sub and pause at the next executable line. Just like Step Into, Step Out doesn't skip the execution of the rest of the sub, only your viewing of it.


Call Stack

Availability: In break mode

Shortcut: CTRL+L


The Call Stack displays a list of all active procedure calls. An active procedure is the Subs and Functions in the application that were started but not yet completed. In the following trivial example, a breakpoint was placed on last in a string of Subs and the Call Stack shows the order of the calls (bottom-up) that got us to the breakpoint. All the subs are shown in the list because none of them have actually finished yet. If you were to step through the code from this point you would see the subs, starting with Sub5, disappear one by one from the Call Stack as the code progressed back up the chain exiting and thus finishing the subs. Finally, if you double-click on one of the entries or click on it and then press the Show button you will be taken to that procedure and a green triangle will be placed in the left-hand margin showing the next procedure in the stack.



Watch Window

Availability: At all times

Shortcut: (None)


We now (finally) come to what I consider the heart of debugging; the Watch Window.


Earlier I talked about the Quick Watch window which allows you to see the values of variables or valid expressions when you are at a breakpoint. (Note that from here on when I refer to "expression" that I mean both valid expressions and variables.) The weak point of that method is that you have to set the breakpoint before you are able to use the window. A watch, on the other hand, allows you to set up an expression that VB watches for you as the program runs and optionally pauses the program when a condition you state occurs. In other words, you don't have to know where to put the breakpoint - VB does it for you!


You can create a watch by

o Clicking the Watch Window button, right-clicking on it and choosing Add watch... or

o Clicking the Debug|Add Watch... menu item or

o Highlighting an expression, right-clicking, and choosing Add Watch...

When you do one of those things you will be presented with the Add watch window which looks like this.



Let's now examine the three parts of that window.


1) Expression

The Expression is the expression you are interested in. It can be a single variable name like intMyInt or a simple expression like intMyInt = 5 or a complex expression like intMyInt > 5 and SomeOtherVar = 37 and bOK = True. Note that capitalization doesn't count and that while there may be a limit to the complexity or length of the expression, I haven't run across either.


2) Context

The Context choices defines for VB where you would like it to watch the Expression, and as you see above the default is all procedures in all modules - in other words, the whole program. You will notice I'm sure that the Context choices are two drop-down items and, for example, if you click on the Module drop-down, you will see something like the following where all the modules in the program are listed.



If you have selected a module then clicking on Procedure will display the procedures contained in that module.


2) Watch Type

There are three Watch Types and you can choose one of them.


Watch Expression
In order to use Watch Expression effectively, you need to have a breakpoint set. Once the watch is created and the breakpoint is reached, clicking on the Watch window button will display something like the following. Note that the Watch Window is dock-able and once docked there's no need to click on it in order for its contents to be seen.


If you are interested in watching a value, creating a Watch Expression is better than using Quick Watch because the latter requires you to continually highlight the expression you are interested in and a Watch Expression doesn't.

The eyeglasses symbol under Expression tells you that it's a Watch Expression, and the little box with the plus sign indicates that txtSquare has more than one property that we can look at. Clicking on the plus sign will expand the result to show you all the properties and their values. Note that if the Watch Expression had been txtSquare(Index).Text instead of just txtSquare(Index) that there would be no plus sign since we were specific about the property we were interested in. The other things displayed in the widow are pretty self-explanatory but I'll mention them for completeness. Value is the value of the expression, Type is the type of item you are looking at, and Context is the scope of the Watch Expression.

This is probably as good a place as any to mention that once you have a Watch Expression you can change or delete any watch by way of the Debug|Edit Watch menu item.

Break When value Is True


The above is a second watch that I added by highlighting an expression and choosing (All Procedures) and Form1 as the Context and selecting Break When value Is True (indicated by the page-in-hand symbol) as the watch Type. I chose Form1 as the Context because I knew that mstrLastPlayer was a variable with a form-wide scope and I wanted to see where in the form it was being changed. Note that if I had chosen (All Procedures) and (All Modules) as the Context that the Value would have said: "<Expression not defined in context>" and the Value would always show as "Empty" since the Context was too broad.

Break When Value Changes
As far as I know, there is no limit to the number of watches you can have and I could add a third watch with mstrLastPlayer as the Expression and Break When Value Changes selected. That type of watch is indicated in the window by a yellow-triangle-in-hand symbol and I'm sure you have already figured out that that watch would pause the program any time mstrLastPlayer changed value.


Unfortunately watches only exist as long as the particular project is open and can not be saved. Also, a watch that you are no longer interested in can get in your way by, for example, continually pausing the program when one of the "Break" type watches becomes true or its value changes. You can, of course, get around that by deleting the particular watch or you can simply edit the watch by adding say, an "X" at the front of the expression thereby making it invalid. Once it is invalid VB will ignore it but not delete it. Later on, if you like you can remove the "X" which will reactivate it.


Debug Is A Great Tool

Over the years I've found that Debug has been an invaluable asset in helping me track down the bugs that slip into my programs, and I hope that this tutorial has given you enough of an understanding of it so that you will feel comfortable using it to track down your errors.


To give you a start at using it I've attached a version of a Tic-Tac-Toe game I wrote that has a bug. What happens is that the second time either "X" or "O" wins a game their total shows as 3 rather than 2. You may well be able to find the bug by just visually inspecting the program but I encourage you to try to find it using the tools provided by Debug.

Tic-Tac-Toe-Bug.zip

 

If you find that this article has been helpful, please click the “thumb’s up” button below. Doing so lets me know what is valuable for EE members and provides direction for future articles. It also provides me with positive feedback in the form of a few points. Thanks!


29
17,130 Views
Martin LissKeep everyone healthy; Get Vaccinated
CERTIFIED EXPERT
Almost 50 years of programming experience. Click '+ More' in my "Full Biography" to see links to some articles I've written.

Comments (11)

Commented:
OMG Martin - thank you for this article, I sooooo wish I had read it sooner!  Will read a few more times. Cheers,
Martin LissKeep everyone healthy; Get Vaccinated
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2023

Author

Commented:
You're welcome to both of you. Sorry I didn't see your comment earlier Stephen.
Jeff DarlingDeveloper Analyst
CERTIFIED EXPERT

Commented:
viewed!
Luis DiazIT consultant

Commented:
Very useful and helpful article!
A very useful tutorial - thanks a million.. I was familiar with several of the commands per se, but not with the toolbars and the windows. This will simplify the task of debugging a great deal!

View More

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.