Running a loop while debugging VBA Running a loop while debugging VBA vba vba

Running a loop while debugging VBA


There is actually a way for using loops or other multi-line statements in the Immediate Window - using a colon : to separate statements instead of a new line. Full solution is described here. Note that in the Immediate Window you also don't have to declare the variables using a Dim statement.

To summarize, your snippet would look something like this:

For i = 0 To 6: j=i: debug.Print i+j: Next i 


I think I understand your question. You want to run a multi-line code block (i.e. the loop) in the Immediate Window. This throws errors because the Immediate Window is only intended for single lines of code.

I don't have any suggestions other than those you already mentioned. I'd recommend putting your test loop into a separate function and calling that from the Immediate Window:

Sub Test()Dim i As Integer Dim j As Integer For i = 0 To 6       j=i    ' Do somethingNext i End

Another option is to set several breakpoints. You can also run one line of code at a time with F8.

What is likely the preferred method (i.e., what most people actually do) is use the full power of the IDE, which includes the Immediate, Locals and Watch panes. You can change the value of most variables at runtime by direct assignment in the Immediate Pane (i=6 will do exactly what you think it should do). The IDE also allows you to set breakpoints, add watch conditions, step through code line-by-line using the F8, step through function or procedure calls using Shift+F8, stepping over (and back) through code using the mouse/cursor, and with a few exceptions, you can even add new variables during runtime.