4.3. Testing and Debugging VBA Code

The Code window is where you actually write your code, including the subroutines, functions, and declarations. In addition to the Code window, you'll use other components of the VBA Editor to test and debug your code. The following sections look at each of those components.

4.3.1. When Should You Debug Your Code?

There are a few schools of thought about when to debug your VBA code, and it's normal for developers to use different approaches in varying situations. You could debug as you write, testing every few lines, although that could be quite time-consuming. You'd have to run your code every few lines (possibly with incomplete procedures) and make heavy use of the tools such as the Immediate window and Watch statements discussed later in this section. The advantage of this method is that you always know the value of your variables, and the likelihood of making or perpetuating a mistake is reduced.

An alternative method is to write all of the code for your application and then debug it. This approach might seem tempting because it doesn't require you to stop your productive code typing to debug your application. However, you can easily end up with numerous errors, some of which could require you to make major changes to your code. Using that technique can be like opening Pandora's Box, particularly as code becomes more complex and interdependent, with one function calling another function.

The best debugging method falls somewhere between ...

Get Access™ 2007 VBA Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.