Immediate Window

In this blog post we look at how you can use the immediate window whilst coding.

The immediate window is a fantastic tool for testing and debugging code. Here are a few simple commands (open the immediate window and type these in directly, then press return):

Debug.print "Hello World"

Print "Foobarbar"

? "bar foo foo bar bar"

? and Debug.Print

Although we use these 3 methods to print from the immediate window, we must use Debug.Print to write to the immediate window when writing code in the normal window.

: to concatenate commands

Another shorthand notation is “:” which allows multiple commands on one line.  As the Immediate Windows doesn’t execute commands over several lines – just one line – you can use “:” to overcome this limitation. So now looping and conditionals structures are available to you:

Debug.print "Hello World": print "Foobar": ? "barfoo"

For t=1 to 10: ?t:Next

T=True: if T then ?"It’s true": else : ?"it’s false :("

T=False: if T then ?"It’s true": else : ?"it’s false :("

; to concatenate strings

Just like in the Code Window you can also use”;” to concatenate Strings together rather than “+”.

Note

You cannot use the “Dim” keyword in the Immediate Window. The good news though is that this is because it is not required; just assign values to variables as required.

' this will not work
Dim t As Integer: For t=1 to 10: ?t:Next

' this will work
T=0 : For t=1 to 10 : ?t : Next

Calling Procedures And Functions

To execute a procedure you need only type its name. To run a function (a procedure that returns a value) you need to write a “?” before the name of the function and include any relevant arguments in parentheses directly after. You can put the call keyword before a procedure or function if you wish but this literally only calls the procedure. So, if you were to use the call keyword before a function it would run the function but not return a value.

Public Function testAA() As String
  testAA = "done"
End Function

' this will not work
Call testAA()
Call (testAA)
A = call(testAA)

' this will work
call testAA
a=testAA()
? testAA()

Immediate Window is in Scope

Commands you type in the Immediate Window are executed immediately and in scope.  If you are not debugging, the window will operate at Global Scope; if you are debugging, the window operates at that function or procedure Scope.

And a final comment to make; when working in the Immediate Window any code you write using variables of the code being debugged will cause the program’s variables to be changed.  This is a highly desirable feature to help resolve bugs.

Related Posts

Debugging
Basic Tools for Writing Code
Compilation Explained
Opening The VBA Editor
The VBA Editor Explained
Visual Basic Editor Options

Leave a Reply

Your email address will not be published. Required fields are marked *

Visit Us On TwitterVisit Us On FacebookVisit Us On Youtube