Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
What are some methods of debugging VBA code?
Specifically:
Stepping through code
Breakpoints and the Stop command
TheDebug command
Locals & watch windows
Call stack
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
Related
I can run a macro under forms, but when I look at the code behind the form, I am not able to step through it all.
I hit the line
Dat = [Forms]![frmMenu]![dtmDate]
and get the error:
Is there a way to resolve this so I can continue to test each step of the macro?
I opened the code with ALT + F11.
I am trying to pinpoint the queries which cause the macro to take so long to run.
You can't hit f5 to run + debug code in a form. You can do this for a standard code module, but not for what we call a class module.
If you wish to debug/step code in a form? Launch the form (normal view). Then go to the code behind, say a button click, and now you can set a break-point.
So, single step, or debug of forms code requires you FIRST load the form as normal. (you can't thus use f5 to run such code). But, you CAN debug as per above.
I have an application in Microsoft project that performs a Backtrace of a task and then uses the following to save that image to an Excel Tab
Application.EditCopyPicture Object:=False, ForPrinter:=0, SelectedRows:=0, FromDate:=EarliestStart, ToDate:=LFin, ScaleOption:=pjCopyPictureShowOptions, MaxImageHeight:=-1#, MaxImageWidth:=-1#, MeasurementUnits:=2
definitions for msome of the variables used in the procedure:
EarliestStart = StatusDate-30
Lfin = Finish of the target Task for the Backtrace, which would be the last task in the string.
I use a flag field to identify tasks that I want to create a backtrace for and then cycle through all the tasks to create the Backtrace images and saving them to a unique excel tab.
Every so often, my app "creates a secondary task pane" using the same view that I am using in the top half of the split screen. I do not want a split screen with the bottom half of the screen displayed. When I have a split screen, my application
Is there a vba command that I can use in code that will test for the presence of a secondary task pane and if present, clear it. I have been looking for something that would test the Ribbon task\details checkbox but have been unable to find it.
If before running the application I remove the secondary pane, it runs fine. If I start to run the vba with a secondary pane showing, it brings up a View "View" dialog.
I have experimented with:
ViewApplyEx SinglePane:=True, ApplyTo:=1
but this displays the View"Views" dialog and forces me to select a view from the list, which is not what I want to do.
Any suggestions as to where I should look?
The method you are looking for is PaneClose. It will close the lower pane of the active window. It does nothing if the lower pane was already closed. So do this:
Application.PaneClose
Application.EditCopyPicture Object:=False, ForPrinter:=0, SelectedRows:=0, FromDate:=EarliestStart, ToDate:=LFin, ScaleOption:=pjCopyPictureShowOptions, MaxImageHeight:=-1#, MaxImageWidth:=-1#, MeasurementUnits:=2
I have a program running. To test this program, I need only one breakpoint. This breakpoint hits between 7 and 8 times consecutively, where I need to change a value each time it breaks.
To accomplish this I am trying to write a macros to make it easier and faster to (rather than hitting continue after changing each value), but have hit a wall. My goal is to enter all values at once and have the macros set the values in the code for each break. Is there a way to continue to the next stop within the macros code?
Any pointers would be helpful as I am not a VB expert.
Thanks
An expression is evaluated as part of the evaluation of a breakpoint condition. (Right-click the breakpoint in Visual Studio, and choose 'Condition'). This expression could call a function that you write (as part of your macro code), and within that function you could change and values that you need to change, and then return a Boolean that determines whether the breakpoint is actually hit.
Of course you could just incorporate such a function call directly into your code, and have a conditional expression with a breakpoint within the If.
I associated a shape in PowerPoint with an action that delegates to a script in VBA. In the script itself I have defined a break point and provoke an error (just for debugging purposes).
When I run the presentation and I click on the shape, the break point is ignored and no error message is displayed, the code just silently stops at the line where the error is raised.
When I run the VBA script from the event handler of a form button, VBA behaves as expected: the break point is respected and the error message pops up.
Is there an explanation, why VBA behaves differently when executing a procedure called from an action, rather than executing from an event handler or directly from the editor. More importantly: is there a cure, i.e. something I can do to get the expected behaviour in actions?
I am currently using PPT2010 under Win7, but PPT2002 shows the same behaviour.
I've noticed this and similar things before. I'm fairly sure it's deliberate ... if you're in the middle of a presentation, you wouldn't want to see error messages or worse, get dumped into the IDE, so PPT just silently fails.
Try compiling the code once before running it and even try running it manually rather than by clicking the assigned action button.
I've always found problems in my code when breakpoints fail; as long as the code is valid and provokes no errors, the breakpoints work, even when the code's invoked from an action setting.
I have seen the same PowerPoint issue when placing code behind a master slide and other code behind slides that are not master slides. This is all within the same presentation. When calling a sub or function in the master slide from a non-master slide the master slide code executes but breaks are ignored. I am not sure how to articulate this but it seems that the debugging 'commands' from the initiating slide are respected and acted upon as you would expect but not the master slide debugging commands because they lie in a different domain or namespace etc. The debugging processes are only active for one 'domain'. The master and non-master slides do not share the same domain.
I have a very strange bug, which I believe is caused by some code we have executing, but I'm not sure where.
We can reproduce it to the point it happens whenever we click Tab, but short of putting a break point at the beginning of every method in the project to find out what is executing.
Is there a way to set visual studio to break whenever anything executes?
For those curious about the problem, every now and then, we have a few Rich Text Boxes that refuse to lose focus. You can't click out of it or tab out of it.
We have no On Validation or On Text Changed events attached to the control, and believe it's an event attached somewhere else to something we just aren't noticing.
You can set a breakpoint in the WndProc method, which will run whenever Tab is pressed.