In this Article
The VBA Immediate Window is used to quickly run lines of individual Excel code, as well as get information about Excel files. 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 Window.
You should see the following:
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)
The result is:
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:
The result is:
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:
After pressing Enter, the result is shown on the worksheet in Cell A1.
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 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:
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: