Word vba debug print

Debug.Print is one of the useful tools presented in the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more  to figure out how a program works. It helps to analyze the changes in the values of variables created in the VBA program. It shows the output of the prompt window when we run the program without any bugs.

Debug.Print offers the two main benefits over using Msgbox to display the output of the code. It eliminates the need for clicking the “OK” button every time and shows the log of returned output values to the immediate windows. It saves a lot of time for users. The present article explains the use of excelIn today’s corporate working and data management process, Microsoft Excel is a powerful tool.» Every employee is required to have this expertise. The primary uses of Excel are as follows: Data Analysis and Interpretation, Data Organizing and Restructuring, Data Filtering, Goal Seek Analysis, Interactive Charts and Graphs.
read more
VBA Debug.Print with many examples and explains how to use it, covering the following things.

Table of contents
  • Excel VBA Debug.Print
    • What is VBA Debug Print?
    • How to Use Excel VBA Debug Print?
    • Examples of Excel VBA Debug.Print
      • Example #1 – Displaying the Values of the Variables
      • Example #2 – Debug print to File
      • Example #3 – Displaying the Factorial of a Number in the Immediate Window
      • Example #4 – Printing the Full name of the Active Workbook
    • Recommended Articles

VBA Debug Print

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Debug Print (wallstreetmojo.com)

What is VBA Debug Print?

Debug is an object in VBA used with the two methods called “Assert” and “Print.” The “Print” is helpful for in-display messages, and “Asserts” is useful in evaluating the conditions. In VBA, debug. In addition, one can use the print statement in any place of the coding program to show the values of a variable or messages in the immediate window. These do not need any acknowledgment or confirmation and do not display any effect on the code developed. It is safe and best to use the code to facilitate access to many users. These are just helpful in testing or evaluating the code to confirm that it is working correctly or not. It prints the variables, strings, numbers, arrays, and values in Excel and empty and active sheets.

How to Use Excel VBA Debug.Print?

VBA Debug.Print is the statement helpful in displaying more variables at a time in the immediate window. It is the best and alternative approach to show the output.

For example,

Debug.print count, sum, average, standard deviation

As shown in the example, all the variables are separated by commas. This statement can transfer the output to the immediate window even if a window is not opened. It does not stop running the code as in msgbox. This flexibility supports continuous monitoring of the changes in the output concerning changes in the code.

The variables count, sum, average, and standard deviation are displayed in the same line with equal space. If the immediate window is not opened, follow the following steps to see the output.

Steps to Open Immediate Window and See the Output

  • Press Ctrl + G or click on the ‘View’ menu in the VBA Editor.
  • Choose the option ‘Immediate Window.’
  • Place the cursor in the Window and again run the code.
  • Observe the output in the window.

Examples of Excel VBA Debug.Print

The following examples demonstrate the use of Debug.Print in Excel VBA.

You can download this VBA Debug Print Excel Template here – VBA Debug Print Excel Template

Example #1 – Displaying the Values of the Variables

First, go to the Developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more, click on “Macros,” and create a macro to write the code in the VBA and add a name to it.

VBA debug print Example 1

After adding a name, click on “Create.” It opens the VBA Editor.

VBA debug print Example 1-1

Develop a small program, as shown in the figure.

Code:

Sub Variables()

Dim X As Integer
Dim Y As String
Dim Z As Double
X = 5
Y = "John"
Z = 105.632
Debug.Print X
Debug.Print Y
Debug.Print Z

End Sub

VBA debug print Example 1-2

The screenshot shows three dimensions or variables decreasing X, Y, and Z as an integer, string, and double. One can use the Debug.Print these values. It will display the output in the prompt window. Press CTRL+G to see the result, as shown in the screenshot.

Run this code using the F5 key and press CTRL+G to see the output in the immediate window.

VBA debug print Example 1-5

One can simplify this program by separating the Debug.Print statements by a comma.

Code:

Sub Variables()

Dim X As Integer
Dim Y As String
Dim Z As Double
X = 5
Y = "John"
Z = 105.632
Debug.Print X, Y, Z

End Sub

VBA debug print Example 1-3

The debug statement prints the output in the same line, as shown in the screenshot.

VBA debug print Example 1-4

Example #2 – Debug print to File

This example illustrates the use of the VBA Debug.Print to display output to a file when the length of the text is too high.

The program is developed to print the output on a file, as shown in the figure.

Code:

Sub DebugPrintToFile()

Dim s As String
Dim num As Integer

num = FreeFile()
Open "D:ArticlesExceltest.txt" For Output As #num

s = "Hello, world!"
Debug.Print s ' write to the immediate window
Print #num, s ' write output to file

Close #num

End Sub

VBA debug.print Example 2

In this program, two variables, S and Num, are considered string and integer. The open statement creates a text file with the name test. A column called “Hello World” is declared into the variable S.

When you run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more manually or using the F5 key, one can write the output into the immediate window, and the file displays in the folder at a time.

VBA debug print Example 2-4

The output of the file shows in the below-mentioned figure.

VBA debug.print Example 2-1

Printing output to file is beneficial when presenting long text.

Example #3 – Displaying the Factorial of a Number in the Immediate Window

This example illustrates the use of the debug—a print statement to show the factorial of a number.

Code:

Public Sub Fact()

Dim Count As Integer
Dim number As Integer
Dim Fact As Integer
number = 5
Fact = 1
For Count = 1 To number
Fact = Fact * Count
Next Count
Debug.Print Fact

End Sub

Dp Example 3

One must consider three variables for determining the factorial, including the count, number, and fact. For loop is taken to repeat the multiplication of fact-value with count to determine factorial of the number.

Here, debug. The print statement uses outside the “for” loop to display the value after completing the circle. The output is determined.

Dp Example 3-1

If we use the Debug.Print statement inside the “for” loop; the fact-value is displayed for every recurring time, as shown in the figure.

Code:

Public Sub Fact()

Dim Count As Integer
Dim number As Integer
Dim Fact As Integer
number = 5
Fact = 1
For Count = 1 To number
Fact = Fact * Count
Debug.Print Fact
Next Count

End Sub

Example 3-2

Run the code by pressing the F5 key and see the output in the immediate window. In this situation, we should consider the last value as the factorial of the given number.

VBA debug print Example 3-4

Example #4 – Printing the Full name of the Active Workbook

This example explains how to print the current workbook name into the prompt window.

Then, the program develops, as shown in the figure.

Code:

Sub Activework()

Dim count As Long
For count = 1 To Workbooks.count
    Debug.Print Workbooks(count).FullName
Next count
Debug.Print count

End Sub

Example 4

Here ‘count’ is the variable taken to count the number of active workbooks and to display the full name of the active workbook. The full name and number of active workbooks are displayed, as shown in the figure.

Dp Example 4-1

The workbook’s path in the drives displays accurately using the VBA Debug.Print statement.

Things to Remember

  • The main issue with the debug .print is no text wrapping option for long strings in the immediate window.
  • We should bring the immediate window to the top to see the output in the user interface.
  • It is impossible to wrap the long text displayed in the immediate window. In this situation, we must show the result to a file stored in the drive.

Recommended Articles

This article has been a guide to VBA Debug.Print. Here, we learn how to use the VBA Debug.Print statement to analyze VBA code output along with examples and explanations. Below are some useful Excel articles related to VBA: –

  • Switch Case in VBA
  • VBA Break For Loop
  • VBA DatePart
  • VBA Print

I think one of the most underutilized methods for developers is the Print method! Beyond which, those that do use it often don’t necessarily use it to its full potential.

Did You Know?

Did you know the Print method actually has parts (options) that you can use? Most developer don’t.

 

What Is The Print Method?

The print method allow us to output (or ‘print’) information/values/content to VBA/VBE the Immediate Window.
 

How Is That Useful?

I know developers that don’t see the utility of Print when they have MsgBox, but they serve 2 distinct purposes.

MsgBox is more for the end-user, to display a message to them. Sadly, you can interact with a MsgBox. Amongst other things, you can’t copy the contents.

Print is only for the developer as it is displayed in the VBE Immediate Window.  The beauty here is:

  • that you can copy/paste its content which is great to search up those error numbers/descriptions.
  • use it while in the VBE creating code without having to switch back and forth to the Access GUI and VBE windows
  • using the options, and other techniques, you can format the output.
  • you can sprinkle it throughout procedure to see the evolution of variables, … in real-time. This is great for debugging purposes.

Basic Usage

Its most basic usage would be

a = "Some"
b = "Value"
Debug.Print a & " " & b

which will the return (in the VBE Immediate Window)

Some Value

Blank Line

There are times that it is useful to insert separation lines, a blank line and this is very easy to do!  Simply do either

Debug.Print

OR

Debug.Print ""

Options You Say

If you look at the documentation for a moment, you will see they mention Spc(n), Tab(n) & ;, so what are these and how do they work.

Spc

Used to insert space characters in the output, where n is the number of space characters to insert.Microsoft

So using Spc(n) you can insert n number of space in front of value, after the value or on it’s own.

Debug.Print Spc(12)

will return what appears to be a blank line, when in fact there are 12 space characters on it

            

Now realistically, no ones really going to output a series of spaces on their own like the example above, well not very often at least, but this can be used to pad/align content.

a = "Some"
b = "Value"
Debug.Print Spc(12); a
Debug.Print a; Spc(12)
Debug.Print a; Spc(12); b

which then outputs something along the lines of

            Some
Some            
Some            Value

where the

  • value ‘Some’ starts as the 13th character on the 1st line
  • 2nd line has 12 training spaces.
  • there is a 12 space gap between the words on the 3rd line

Tab(n)

Used to position the insertion point at an absolute column number where n is the column number.Microsoft

So, in plain English, somewhat like the spc(), tab enables you to position the output to a specific position (column).  Pay particular attention to the term absolute!  so it is not in function of a relative position, but the absolute position which is great for fixed position output.

Thus, we can quickly learn that

Debug.Print a

is the same as

Debug.Print Tab(1); a

as Tab(1) indicates to output the content on the 1st column.

You can also use Tab() to add whitespaces

a = "Some"
b = "Value"
Debug.Print a; Tab(10)
Some     

In the above, it adds 5 spaces, so the next available character would start on the 10th column. Thus, we could use it for fixed length output

a = "Some"
b = "Value"
Debug.Print a; Tab(10); b
Some     Value

Semi-Colon (;)

Let’s talk about the colon (;)!

Use a semicolon (;) to position the insertion point immediately following the last character displayed.Microsoft

Normally, when you perform a Print, it outputs the ‘value’ and then you start fresh on a new line.  The ; is a continuation operator telling the output to continue from the current position.  Thus, it allows us to continue to output content on the same line as the previous output.  Now, the example above doesn’t do it justice, so let’s try another more concrete example

a = "Some"
b = "Value"
   
Debug.Print a;
Debug.Print Spc(12);
Debug.Print b

which outputs

Some            Value

So we can now split the Debug.Print into multiple lines while having the output remain on a single line.

This can be very helpful when building long output.  Rather than creating a really long variable, string, … you can simply Debug.Print each on their own line, but use the ; so they continue to print out on the same line in the VBA/VBE Immediate Window.

Here’s a real example

        With oCol
            Debug.Print .Caption
            Debug.Print , .Description;
            Debug.Print , .Domain;
            Debug.Print , .InstallDate;
            Debug.Print , .LocalAccount;
            Debug.Print , .Name;
            Debug.Print , .SID;
            Debug.Print , .SIDType;
            Debug.Print , .Status
        End With

So the outputs 2 lines, one with just the Caption and a 2nd line with all the details for that entry. While Debugging, this format is much easier to read and tweak.

Here’s one more example, used to output the content of a recordset so that each record is on a single line.

Do While rs.EOF = False
    For i = 0 To rs.Fields.Count - 1
        Debug.Print rs(i) & ",";
    Next i
    Debug.Print
    rs.MoveNext
Loop

The comma!  The comma performs an indentation.  Like the spc() & tab() it can be used to aid legibility, add indentations …

Its usage is very straightforward.  Let’s pretend we’re gathering Disk Drive information and breaking down the partitions by drive.  Now let’s output it using some of the techniques we’ve discussed thus far

a = "Disk 1"
b = "Partition 1"
c = "Partition 2"
d = "Partition 3"
e = "Disk 2"
f = "Partition 1"
g = "Partition 2"

Debug.Print a & " " & b & " " & c & " " & d & " " & e & " " & f & " " & g
Debug.Print
Debug.Print a
Debug.Print b
Debug.Print c
Debug.Print d
Debug.Print e
Debug.Print f
Debug.Print g
Debug.Print
Debug.Print a
Debug.Print , b
Debug.Print , c
Debug.Print , d
Debug.Print e
Debug.Print , f
Debug.Print , g

this will then output something resembling

Disk 1 Partition 1 Partition 2 Partition 3 Disk 2 Partition 1 Partition 2

Disk 1
Partition 1
Partition 2
Partition 3
Disk 2
Partition 1
Partition 2

Disk 1
              Partition 1
              Partition 2
              Partition 3
Disk 2
              Partition 1
              Partition 2

I think it is pretty evident how useful the comma (,) is to making the output MUCH more legible!
 

Printing In The Immediate Window

There are times, debugging being the most common, when you wish to perform a Debug.Print directly in the Immediate Windows itself.  Here we can simplify things and instead of doing

Debug.Print a

We can simply do

? a

The ? replaces Debug.Print when entered directly in the Immediate Window!
 

Limitations

Sadly, you cannot use a With statement, thus something like

With Debug
    .Print a
    .Print b
    .Print C
    .Print d
    .Print e
    .Print f
    .Print g
End With

does not work.

Nor can you just use .Print on its own.

Nor can you use the ? directly in VBA code as it only works in the Immediate Window directly.
 

Useful Resources

Print method (Visual Basic for Applications)

Prints text in the Immediate window.

A bug is a mistake or error in a program that causes it not to work correctly. Debugging is the process of removing and fixing bugs to get a program to function properly. There are different types of bugs that have different causes and solutions. Bugs can be errors, mistakes, oversights, or poorly implemented logic. Some bugs are easy to detect and fix while others are difficult to recognize and rectify. A bug will ultimately cause a compile error, a runtime error, or an incorrect result.

Compile Errors

Compile Errors occur at compile-time when a language rule has been broken. A program will not run if it has an error in compilation. To detect compile errors use Debug → Compile VBAProject on the toolbar in the Visual Basic Editor. Using Debug → Compile will compile the code in all modules and raise an error message if there is a compile error anywhere, whereas running a procedure in one module may not show the compile error in another procedure or module.

Compile Error Procedures
Debug Compile
Compile Error Procedures Debug Compile

Syntax Errors are compile errors that occur because a syntax rule has been broken. Syntax is the structure of a language and determines what is considered a valid statement. By default, Auto Syntax Check is enabled and the Visual Basic Editor will alert syntax errors and certain other compile errors and highlight them red. If auto syntax check is disabled, pop-up messages will not appear but syntax errors will still appear in red. To enable or disable auto syntax check go to Tools → Options → Editor → Code Settings → Auto syntax check.

Disable Auto Syntax Check

Unhandled Runtime Errors

Runtime Errors occur while a program is running. Unhandled runtime errors will cause program execution to pause and a message will be displayed. The user can either press End to end execution of the program or press Debug to open the Visual Basic Editor and view the line of code that caused the runtime error. Runtime errors can be handled using the On Error statement which is discussed in the Error Handling section.

Runtime Error

Logical Errors

Bugs which cause incorrect output can be the trickiest to debug because the code can appear to work properly under the right conditions but then work incorrectly under other conditions. These silent logical errors are usually caused by poorly thought-out or poorly implemented logic or overlooking aspects of a problem or solution. This type of bug can often be caught through testing and reviewing the output of the code.

Public Function RandomLong(MinValue As Long, MaxValue As Long) As Long

    'BAD CODE - If MinValue > MaxValue erroneous results occur

    Randomize
    RandomLong = Int((MaxValue - MinValue + 1) * Rnd + MinValue)

End Function

Public Function RandomLong(MinValue As Long, MaxValue As Long) As Long

    'FIXED - Unacceptable state causes a runtime error instead of returning wrong answers

    If MinValue > MaxValue Then
        Err.Raise 5
    End If

    Randomize
    RandomLong = Int((MaxValue - MinValue + 1) * Rnd + MinValue)

End Function

A runtime error could exist within a silent error if it only occurs under specific conditions. Code may run normally under normal conditions but then break when an edge case is encountered, causing an unhandled runtime error which can leave a program or associated data in an intermediate state.

Debug Object

The Debug object contains two methods which assist in debugging VBA code, Print and Assert. The Debug object has a default global instance and cannot be instantiated. The Debug object can be accessed at any time in VBA just by typing Debug.

Debug.Print

Debug.Print is used to print text to the Immediate Window.

Public Sub Example()

    Debug.Print "Hello, World!"

End Sub

Debug Print

Debug.Assert

Debug.Assert will pause execution if a boolean expression does not evaluate to True. If the expression evaluates to False or Null execution will be paused.

Public Sub Example()

    Debug.Assert 1 > 0
    Debug.Assert True
    Debug.Assert 1

    Debug.Assert 1 < 0  'Pauses Execution
    Debug.Assert False  'Pauses Execution
    Debug.Assert 0      'Pauses Execution
    Debug.Assert Null   'Pauses Execution

End Sub

Debug Assert

Pause Program Execution

There are a number of ways to cause a program to pause execution and allow the user to inspect the state of a program in break mode.

Breakpoints

Breakpoints can be used in the Visual Basic Editor to pause program execution when a particular line of code is reached. Execution will pause before the line of code is executed. Breakpoints can be toggled by clicking in the margin next to the line of code, right-clicking the line of code and selecting Toggle → Breakpoint, or by using the Edit or Debug toolbars.

Breakpoint

Breakpoint Paused

Stop Statement

The Stop statement will pause execution when the keyword is encountered in the code.

Stop Statement

Watches

Watches can be used to pause execution when an expression evaluates to True or when the value of an expression changes.

Watch Break When Value Is True
Watch Break When Value Is True Paused

Runtime Errors

By default, when an unhandled runtime error is encountered a message will appear describing the error, giving the option to End program execution or to Debug. Selecting Debug will jump to the line of code that caused the error and leave program execution paused.

Unhandled Runtime Error

Different error trapping options can be selected to pause execution on all errors or to pause on errors inside class modules.

Error Trapping Option Description
Break on All Errors Will enter break mode when any error is encountered regardless of error handling code.
Break in Class Module Will enter break mode and show error inside class modules.
Break on Unhandled Errors This is the default setting. Will enter break mode when an unhandled runtime error occurs.

Error Trapping Options

Debug.Assert

Debug.Assert will cause execution to pause if a boolean expression does not evaluate to True. If the expression evaluates to False or Null execution will pause.

Public Sub Example()

    Debug.Assert 1 = 0
    Debug.Assert False
    Debug.Assert 0
    Debug.Assert Null

End Sub

Stepping Through Code

There are tools in the Visual Basic Editor for stepping through code which allow developers to take a close look at the way a program executes each line of code. There is: Step Into, Step Over, Step Out, and Run To Cursor. These tools can be accessed from the Debug Toolbar or by using keyboard shortcuts.

Tool Shortcut Description
Step Into F8 Executes a line of code and enters into procedures.
Step Over Shift + F8 Executes a line of code but will not enter procedures.
Step Out Ctrl + Shift + F8 Executes all lines of code within a procedure.
Run to Cursor Ctrl + F8 Executes all lines of code up to where the cursor is currently located.

Navigating Code

Navigating code is an important skill for programming as well as debugging. When a project grows it becomes more complicated to navigate the code. The Visual Basic Editor provides tools that facilitate navigating code.

Definition Shortcut

The Definition shortcut allows the developer to jump directly to a where a variable or procedure is defined. To jump to the definition of a variable or procedure right-click on the identifier and select Definition from the right-click menu or use the keyboard shortcut Shift + F2.

Definition

LastPosition Shortcut

The LastPosition shortcut allows the developer to jump to the position in code they last edited. To jump to the last position right-click in the Visual Basic Editor and select LastPosition or use the keyboard shortcut Ctrl + Shift + F2.

Last Position

Bookmarks

Bookmarks can be used to explicitly set positions in the code that can be cycled through. To set a Bookmark right-click on the line of code and select Toggle → Bookmark. To cycle through Bookmarks, use the Edit Toolbar.

Toggle Bookmark

Object Box and Procedure Box

The object box and procedure box drop-downs allow a developer to view all the objects and procedures in a module and jump directly to specific procedures as well as insert event procedures if applicable. The object box and procedure box are located at the top of the coding window. The object box is on the left and the procedure box is on the right.

Procedure Box

Split Code Window

The code window can be split so different parts of the same code window can be viewed simultaneously. To split the code window drag the handle at the top right corner of the code window.

Split Handle

Split code windows view the same code and changes in either window are reflected in both windows.

Split

Module And Procedure View

Code windows can be toggled between module view and procedure view. Module view makes the entire module visible in the code window. Procedure view makes only the current procedure visible in the code window. To toggle between module view and procedure view use the toggle buttons at the bottom left corner of the code window.

Module Procedure View

Useful Shortcuts

Action Shortcut Description
Intellisense Ctrl + j Shows options for completing code
Auto-Completion Ctrl + space Completes code or shows options for completing code
Definition Shift + F2 Jumps to where a variable or procedure is defined
Last Position Ctrl + Shift + F2 Jumps to the last active position in a code module

Important Windows

The Immediate Window, Locals Window, and Watch Window are all powerful debugging tools. These windows can be accessed from the View menu in the Visual Basic Editor.

VBE View Menu

Immediate Window

The Immediate Window can be used to view output, run code, and evaluate expressions. The Immediate Window can be accessed by pressing Ctrl + g in the Visual Basic Editor or from View → Immediate Window.

Immediate Window Examples

Debug.Print

Debug.Print outputs text to the immediate window. For example, Debug.Print «Hello, World!» will output «Hello, World!» to the immediate window.

Call Procedures

Procedures can be called from the immediate window by typing the name of the procedure followed by any parameters and pressing enter.

Evaluate Expressions Using «?»

To evaluate an expression in the immediate window type a «?» followed by the expression and press enter.

Execute Code Statements

Code can be typed directly in the immediate window and executed. Because only one line can be used in the immediate window to type code, write multiple statement using the «:» statement separator.

Locals Window

The Locals windows is used to track the values and types of variables during program execution. Pausing execution, stepping through code, and looking at the locals window is an effective way to observe changes in the state of a program. The Locals Window can be accessed from View → Locals Window.

Locals Window

Watches

The Watch Window is used to view how expressions evaluate during a program’s execution and to pause execution when certain conditions are reached. To Add a watch, highlight an expression, right-click the expression, and select Add Watch. Alternatively, right-click the Watch Window, select Add Watch, and type the expression. To access the Watch Window navigate to View → Watch Window.

Right-Click Add Watch
Add Watch
Watch Break on Value Change

Call Stack Window

The call stack window shows a list of active procedures. To see the call stack dialog either navigate to View → Call Stack, click the call stack icon on the Debug toolbar, or use the shortcut Ctrl + L.

Call Stack Window

Home / VBA / VBA Immediate Window (Debug.Print)

What is Immediate Window

Immediate Window is a small box in the Visual Basic Editor that you can use to execute a single line of code and get an instant result of that. In simple words, instead of executing your code directly in Excel, you can run a macro line to what it returns. It’s quite useful when you are debugging a code.

When you open the visual basic editor (Alt+ F11), you can see the immediate window at the bottom.

But, if it’s not there then you need to activate it from the edit menu, or you can also use the keyboard shortcut key Control + G.

And if you want to unlock it, click and hold the title bar and drop it and outside of the VB editor.

What is Debug.Print

Debug.Print is a command that you can use to execute a single line of code and get the result of that line in the Immediate Window. In simple words, when you use debug.print command at the starting of the line of code and then execute it, VBA shows the result of that line in the immediate window.

Imagine, you want to know which font color is applied A1. In that case, you can use the following line of code it starts with Debug.Print and then code to get the font color.

Debug.Print Range("A1").Font.Color

Now when you run this code, you get the result in the immediate window, like below:

Executing a Line of Code

Apart from using the debug.print you can directly execute a line of code from the immediate window. Let’s say if you want to enter a value in cell A1 you can directly type the following code in the immediate window, and after that, hit ENTER.

Immediate Window executes a single line of code at a time. So, you need to hit enter each line of code that you want to run.

Run a Macro Directly from the Immediate Window

You can also run a macro directly from the immediate window using the macro name. All you need to do is type the name of the macro and then hit enter.

Make sure to define the arguments within the immediate window if you have any.

Asking Quick Questions

You can also ask questions directly into the immediate window. What I’m trying to say is you can directly write a line of code in the immediate window and use a question mark to get the result.

Let’s say if you want to know the value that you have in cell A1, in that case, you can type the following line of code into the immediate window and hit enter.

?Range("A1").Value

Return to VBA Code Examples

In this Article

  • Displaying the Immediate Window
  • Executing Lines of Code
  • Questions and the Immediate Window
  • Run a Macro from the Immediate Window
  • Using Debug.Print
  • Using the Immediate Window When Running Code

The VBA Immediate Window is used to quickly run lines of VBA code, as well as fetch information about your code or Excel file. This tool allows you to test individual lines of code, which is useful when you are writing and debugging code. The output is displayed in the Immediate Window.

Displaying the Immediate Window

You need to display the Immediate Window first. In order to do this, you would press Alt + F11 to enter the Visual Basic Editor. Once you have inserted a module. Press Ctrl + G to view the Immediate Window.

You should see the following:

Viewing the Immediate Window in VBA

Executing Lines of Code

One of the things that the Immediate Window allows you to do is test a line of code. The following code will show you how to use the Immediate Window to fill Cell A1 of the Active Sheet with a light orange fill color. Type in the following line and then press Enter on your keyboard:

Range("A1").Interior.Color = RGB(246, 174, 134)

Testing Lines of Code Using the Immediate Window in VBA

The result is:

Using the Immediate Window in VBA to Fill a Cell

Questions and the Immediate Window

You can use the Immediate Window to get information about your workbook. You can do this by using the question mark. If you enter a statement preceded by a question mark then the Immediate Window will deliver the appropriate answer. Let’s say you have the number 5, in cell A1 which is selected. The following code will allow you to use the Immediate Window to get this value:

?ActiveCell.Value

The result is:

Asking Questions and Using the Immediate Window

Run a Macro from the Immediate Window

You can run a macro from the Immediate Window by typing in the name of the macro and pressing Enter. If your macro contains arguments then you can use the Immediate Window and pass the arguments to the macro through the Immediate Window. The following code shows you how to call a macro named CountWorksheets from the Immediate Window:

CountWorksheets

Using the Immediate Window to Call Macros

After pressing Enter, the result is shown on the worksheet in Cell A1.

Using Debug.Print

You can use Debug.Print as part of your sub procedures and this tells the Immediate Window to display certain information. This is used when you don’t want to display values or results in a cell in the workbook itself or in a message box. The following code uses the Debug.Print statement as part of a sub procedure and displays the results in the Immediate Window.

Sub UsingDebugPrint()

Dim FirstName As String
Dim LastName As String
FirstName = "Jane"
LastName = "Williams"

Debug.Print FirstName & " " & LastName

End Sub

The result when you press F5 to run the macro is shown in the Immediate Window:
Using Debug.Print to Display Results in VBA

Using the Immediate Window When Running Code

You can also use the Immediate Window to set or get a variable’s value while you are stepping through your code:

Sub GettingAndSettingVariableValues()

Dim LName As String
Dim SName As String
Dim Age As Integer

LName = "John"
SName = "Smith"
Age = 31

End Sub

The following code has a  breakpoint that is inserted as shown below:

Getting Variables Using the Immediate Window

If you enter ?SName in the Immediate Window while stepping into your code using F8, at the break point you will get the following result:

Stepping into your code and using VBA

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Introduction

While programming, it is always good to test parts of your code as you are writing it instead of writing the whole program, compiling it and running it — only to find out that it has a bug. In this article, you are going to learn how to use the VBA console, which is also known as the immediate window.

What is the Use of the VBA Immediate Window?

The VBA immediate window is a console; it’s basically like a playground. It’s a place to test code because the process of creating a new module and writing a procedure is fairly time consuming.

If you only want to test a line of code, you don’t need to go through all the packaging and compilation procedures. You can just use the immediate window for that.

It should be noted that the immediate window is not made for testing large scale procedures, it is only intended for one or two lines of code just to make sure that everything is working well as expected.

How Do You Activate the Immediate Window?

The immediate window is not a default feature of the Visual Basic Editor. To activate it, follow the steps below:

Step 1: Select the Developer tab on the Excel menu and click on the Visual Basic option or click on Alt + F11 simultaneously.

Open VBA editor

Step 2: Click on the View tab on the VBE Menu and select “Immediate Window” or press Ctrl + G

Opening the immediate window in VBA

You should have the screenshot below:

VBA immediate window shown in the editor

Note: In the rest of the article, I will use the term VBA console to refer to VBA immediate window.

How Do You Use the VBA Console?

The VBA console can be used in many ways from basic mathematical operations to testing lines of codes. We are going to see some of them in the following examples.

Using the VBA console for basic mathematical operations

Whenever you want to get an answer from the console, you should put the question mark (?) or the command “Print” before the operation. For example, if you want to know the answer of 2 + 3 you should write “? 2 + 3” or “print 2 + 3”. Most people prefer to use the question mark because it is shorter.

If you try it in your own VBA console, you should have the following result:

Testing the immediate window with a math problem

Using the VBA console to interact with a worksheet

If you want to find the value of a cell, you can do so in the console by writing: ? Range(“A1”).value

Display value of a cell in immediate window

You can also use the console to write a value in a cell by writing: Range(“A1”).Value

Printing value to a cell from the console

Note:

  1. For instructions or processes asking for actions, you should not use the question mark “?” or “Print” because it is not an inquiry but an instruction telling VBA to do something such as writing the string “Hello” in cell A1.
  2. The operations done on the VBA console are not permanent. They are deleted once you close the workbook. If you want to preserve your code to run it later, you must write it within a procedure and save it.

Print to the VBA Console from a Procedure

You can print in the VBA console from a procedure body. This is really helpful when you want to keep track of what is going on in a procedure like changes in the value of a certain variable. Here you cannot more use the question mark or print. VBA has an object called Debug for that purpose, and it is the main focus of this article.  Before going into more details, let’s see how it works. Create a new module and write the following procedure:

Sub PrintToConsole()
    Debug.Print 2 * 5
End Sub

Examining console output after using Debug.Print

Note:

  1. Debug is a VBA object just like Worksheet or Workbook. Print is one of the methods of the Debug object. Debug has precisely two methods which are Assert and Print, but our focus here will be the Print method.
  2. The question mark (?) is an alias of Debug.Print but it can only be used in the VBA Console, unlike Debug.Print, which can be used in both a procedure and the VBA console.

Let’s add more lines of code to the previous procedure and see the outcome in the VBA console:

Print multiple lines to the VBA console

Conclusion

The immediate window is a very useful feature of the VBA programming language.  It can be used not only for inquiries but also to give instructions and test lines of code. It is a good idea to acquaint yourself with it if you plan to make a career in VBA programming.

See also: How to Clear the Immediate Window

Like this post? Please share to your friends:
  • Word vba column width
  • Word vba close file
  • Word vba close all documents
  • Word vba cell color
  • Word vba application dialogs