3

What are some methods of debugging VBA code?

Specifically:

  • Stepping through code
  • Breakpoints and the Stop command
  • TheDebug command
  • Locals & watch windows
  • Call stack
ashleedawg
  • 20,365
  • 9
  • 72
  • 105
  • 2
    re: votes for **too broad**. Yes, this article covers a broad range of issue in only a couple pages, and it's solved countless problems for me, and I've referred dozens of people to it. ***3 Close votes in a couple minutes?*** Perhaps you didn't read it all the way through to realize how much is covered by the author. It is imperative that this content and more is not lost in a few weeks. I respect opinions and appreciate different points of view, but an "instant close" isn't either. – ashleedawg May 05 '18 at 12:25
  • 3
    @pnuts It seems a significant part of the community dislikes canonicals, and makes posting one an uphill struggle. Some go as far as claiming the concept is invalid. See [this Meta answer](https://meta.stackoverflow.com/a/364947/2751851) (warning: it is a bit rambling) and the ensuing discussion. – duplode May 06 '18 at 00:31
  • 7
    By the way, this question should be a wiki too, I think. – Stargateur May 06 '18 at 07:34
  • 2
    I'm voting to close this question as Too Broad because one could write an entire book on it. – Robert Columbia May 06 '18 at 11:38
  • 2
    @RobertColumbia- This post is **at or near #1** in popularity out of Chip's entire archive. I know I, for one, have referred dozens of new VBA and VB coders to this post at it's former location. I have site traffic info enroute from the host, so I'll be able to confirm that statistic soon. Do not every single question Stack Overflow have *a lot* more that could be written about it? This post is a solid tool for a novice coder troubleshooting for the first time, *and* a good refresher for the experienced. If you feel more information should be added, then by all means do so. – ashleedawg May 06 '18 at 15:40
  • 5
    As http://www.cpearson.com is no longer down, this Q/A is (aside from being too broad), now redundant. – Cerbrus May 07 '18 at 09:55
  • @Cerbrus - cpearson.com will likely be down again before it stays up. There is a matter of funding, and a collection will be taken. More details will follow from the organizer. The site is also incomplete. – ashleedawg May 07 '18 at 12:15
  • 2
    @ashleedawg: Sure, but my point is that they're working on having the site up where it's supposed to be. Not somewhere where it's a poor fit. – Cerbrus May 07 '18 at 12:16
  • 1
    @Cerbrus You're very verbal with your opinions. I don't understand what your issue is. You are missing a lot of information that's right in front of you (or perhaps just like to argue). You know, my actions weren't with *evil intent*, nor were they made nonchalantly or in ignorance. Only trying to help everyone as a whole here (not just concede the "noisy one.") My intentions were clarified from the start, and it looks like the ideal solution (site revival, of which i am a part) is hopefully going to happen, fingers crossed. There are still roadblocks, working on it. – ashleedawg May 07 '18 at 12:26
  • 3
    @ashleedawg: You didn't discuss this before-hand. You just _did_, then announced _"oh, yea, I did this"_. I'm sure your intentions are honorable, but the fact of the matter is that this question, as is, is a poor fit for Stack Overflow, and it's _redundant_. The site will be preserved. – Cerbrus May 07 '18 at 12:28
  • Related meta question: *[Can we preserve Chip Pearson's content on Stack Overflow?](https://meta.stackoverflow.com/questions/367383/)* – Peter Mortensen Oct 27 '21 at 16:29

1 Answers1

11

Debugging VBA Code

This page describes methods for debugging your VBA code.


Introduction

Debugging a program is one of the most important steps in software development. Knowledge of VBA's debugging tools can make debugging easier and more productive. This page describes several of VBA's built-in debugging tools you can use when testing and debugging your application.


Stepping Through Code

One of the first methods to debug code is to step through the code one line at a time. To step through code, put the cursor on the first line of code to be analyzed and press F8 or choose Step Into on the Debug menu. The next line of code to be executed will be displayed in yellow background with a black font. Note that the highlighted line of code has not yet been executed -- it is the next line to execute.

If your code calls another procedure, stepping through the code with F8 will cause execution to enter the called procedure in a line-by-line sequence. If you want to execute the called procedure without stepping through it, press Shift+F8. This will execute the called procedure and then pause on the line of code after calling the procedure. If you are already stepping through a procedure, you can press Ctrl+ F8 to resume code execution line-by-line. At any time you are paused either in step-by-step mode or at a breakpoint (see below), you can press F5 or Continue from the Run menu to cause VBA to run to completion or until a pause statement is encountered.

Whenever you are paused in step-by-step mode, you can query or change a variable's value from the Immediate window.


Break Points And The Stop Command

A breakpoint is a marker placed on a line of code that causes execution to pause immediately before executing that line. You can add a breakpoint to a line of code by putting the cursor on the line of code in question and pressing F9, choosing Toggle Breakpoint on the Debug menu, or clicking in the left margin next to the line of code. When a breakpoint is set, the line is displayed in brick-red background with a white font. When you run the code, execution will pause immediately before the line of code with the breakpoint and will display it in yellow background with a black font. Note than the line in yellow has not yet been executed -- it is the next line of code to run.

While the code is paused at the breakpoint, you can issue commands in the Immediate window to change or query a variable's value. To view the content of a variable, enter a ? character followed by the name of the variable and then press Enter. You can change a variable's value by entering VariableName = NewValue in the Immediate window and pressing Enter.

If the Immediate window is not visible (typically at the bottom of the VBA Editor screen), press Ctrl+G or choose Immediate Window from the View menu to make the window visible.

To remove a breakpoint, put the cursor on the line of code and press F9. You can clear all breakpoints by choosing Clear All Breakpoints from the Debug menu or pressing Ctrl+Shift+F9. VBA also provides the Stop command. This simply stops code execution on that line of code and enters break mode.

Once you are finished debugging the code, be sure to go back and clear all breakpoints (choose Clear All Breakpoints from the Debug menu or press Ctrl+Shift+F9) and be sure to remove or comment out all Stop statements.

When you are paused at a breakpoint or in step-by-step mode, you can change the next line to be executed, either before the current line to re-run a section of code, or after the line to skip statements. Right-click the line where you want execution to resume and right-click and choose Set Next Statement or choose Set Next Statement from the Run menu. Execution will resume at the selected line of code.


The Debug Command

VBA provides a Debug object with two properties, Print and Assert that you can use display a variable's value and to control the program flow. Debug.Print will write what follows it to the Immediate window. Code execution is not interrupted. After displaying the text in the Immediate window, code execution continues to run. You can mix literal text with variable names in the Debug.Print statement. For example,

Debug.Print "The value of variable X is: " & X

You can display several variables at once in the Immediate window by separating them with commas. For example,

Debug.Print X, Y, Z

The Debug.Assert command is a conditional breakpoint that will cause execution to pause on the Debug statement if the expression that following the Assert statement is False. For example,

Debug.Assert Var >= 0

This will pause on the Debug.Assert statement if Var >= 0 is False; that is, it will pause if Var is negative. It may seem backwards that execution is paused when the condition is False rather than True, but the Assert method was adopted from the C language, and its usage remained the same as in C.

Be sure to remove or comment out the Debug.Print and Debug.Assert statements when you are finished debugging. You generally don't want these statements to be operative during normal usage of your application.


The Locals Window

The Locals windows allows you to view the value of all the variables in a procedure when you are stepping through the procedure. To display the Locals window, choose Locals Window from the View menu. Using the Locals window is easier to display variable values than examining the value from the Immediate window. For simple variable types (e.g., Long and String variables), the value is displayed on one line. For complex types or objects (e.g., a Range variable), its properties are displayed in a collapsible tree-like structure.


The Watch Window

The Watch window displays all the Watches in effect. You can display the Watch window by choosing Watch Window from the View menu. A Watch is an instruction to VBA to pause code when an expression is True or when the variable being watched changes value. To create a Watch on a variable, open the Watch window and right-click in the Watch window and choose Add Watch... from the popup menu or choose Add Watch... from the Debug windows. In the Add Watch dialog, enter in the Expression text box a variable name whose value you want to watch. Then choose Break When Value Changes. When you run the code, execution will pause at the line after the line that modifies the variable's value. When code pauses, the value of the variable will have already been updated.

To remove a Watch, right-click it in the Watch window and choose Delete Watch from the popup menu. To modify a Watch, right-click it in the Watch window and choose Edit Watch from the popup menu.


The Call Stack

The Call Stack is a data structure maintained by VBA that tracks which procedure called another procedure. For example, if procedure AAA calls BBB which calls CCC, the Call Stack window will display the list of procedures starting with the most recent procedure and below that, the chain of procedures that were executed to get to the current position. You can view the Call Stack by choosing Call Stack from the View menu. This is useful to track the flow of execution that ended up in the current location. Unfortunately, there is no programmatic way to get information from the call stack.


Source: Chip Pearson at Pearson Software Consulting: http://www.cpearson.com/Excel/DebuggingVBA.aspx

Community
  • 1
  • 1
ashleedawg
  • 20,365
  • 9
  • 72
  • 105
  • 3
    I'm flagging this answer as a potential copyright violation. – Robert Columbia May 06 '18 at 11:40
  • @RobertColumbia - You (or mods, or whomever) can contact me directly with any concern about legalities. Homework has been done, several hours invested, due diligence has been made..(My contact info is at bottom of the related [meta](https://meta.stackoverflow.com/q/367383/8112776) post, as well as on [my profile](https://stackoverflow.com/users/8112776)./ashleedawg?tab=profile). – ashleedawg May 06 '18 at 15:49
  • 5
    This answer is redundant, as the [site is back online](http://www.cpearson.com/Excel/DebuggingVBA.aspx). – Cerbrus May 07 '18 at 09:56
  • @pnuts: no, the question should be closed. – Cerbrus May 08 '18 at 21:04
  • @pnuts: The question being redundant also makes the answer redundant. We can debate semantics forever, but that'd be pointless. – Cerbrus May 08 '18 at 21:21