Excel vba окно immediate

Окно Immediate используется в VBA Excel при написании и отладке процедур для тестирования отдельных строк кода, проверки текущих значений переменных и в качестве калькулятора.

Отображается на экране окно Immediate сочетанием клавиш Ctrl+G или через меню редактора VBA: View → Immediate Window.

Чтобы протестировать выполнение отдельных строк кода VBA Excel в окне Immediate необходимо:

  • ввести строку кода в окне Immediate,
  • нажать клавишу Enter.

Код в окне Immediate можно вводить с использованием контекстных подсказок и выбором из них объектов, свойств и методов, точно так же, как и непосредственно в модуле VBA. Можно строку кода скопировать из процедуры и вставить в окно Immediate из буфера обмена. При нажатии клавиши Enter курсор может находиться в любом месте проверяемой строки.

Пример 1
Откройте окно Immediate, вставьте в него строку

Range(«A1:A5») = «Тестируем окно Immediate»

и нажмите Enter. В первые пять ячеек первого столбца активного листа Excel будет записана строка «Тестируем окно Immediate». Таким же образом будет выполняться любая тестируемая строка вашего кода VBA.

Проверка значений переменных

Для отображения в окне Immediate значений переменных используется метод Print класса Debug (Debug.Print). Рассмотрим работу этого метода сразу на примере.

Пример 2

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub Primer2()

Dim a As Byte, b As Byte, c As Byte

a = 15

b = (a + 35) / 5

c = a * b 50

‘Каждая переменная в отдельной строке:

Debug.Print a

Debug.Print b

Debug.Print c

‘Все переменные в одной строке

‘с разделителем «точка с запятой»:

Debug.Print «a = « & a; «b = « & b; _

«c = « & c

‘с разделителем «запятая»:

Debug.Print «a = « & a, «b = « & b, _

«c = « & c

End Sub

Помечаем маркерами строки с методом Debug.Print, кликнув по левому полю напротив нужных строк, чтобы в этих местах остановить исполнение кода. Строка с маркером, на котором остановилась программа, будет выполнена после очередного нажатия кнопки Run Macro или клавиши F5.

Результаты выполнения кода смотрите на изображении:

Проверка значений переменных

Проверка значений переменных

Если при размещении нескольких элементов после метода Debug.Print не указать разделитель, редактор VBA при запуске кода на выполнение автоматически вставит между элементами разделитель «точка с запятой». Сравните с результатом использования в качестве разделителя символа «запятая».

При работе с переменными можно изменять их значение непосредственно в окне Immediate. Введите строку с присвоением переменной нового значения и нажмите клавишу Enter. Значение переменной будет перезаписано.

Пример 3
Пример изменения значения переменной в окне Immediate во время исполнения кода VBA Excel:

Sub Primer3()

Dim a As Variant

a = WorksheetFunction.Pi

Debug.Print a

‘Вводим в окне Immediate строку

‘a = «Сейчас число Пи округлим»

‘нажимаем Enter и далее F5

Debug.Print a

‘Вводим в окне Immediate строку

‘a = 3.14

‘нажимаем Enter и далее F5

Debug.Print a

End Sub

В этом примере переменной a присваивается значение числа Пи. Далее мы непосредственно в окне Immediate дважды меняем значение этой переменной. Маркер остановки исполнения кода ставим на второй и третьей строке Debug.Print a. Результаты смотрите на изображении:

Изменение значения переменной в окне Immediate

Изменение значения переменной в окне Immediate

Окно Immediate как калькулятор

Чтобы воспользоваться окном Immediate как калькулятором введите в нем ключевое слово «Print» или символ «?», затем вычисляемое выражение и нажмите клавишу Enter. При таких вычислениях пробелы в выражениях игнорируются.

Вычисления в окне  Immediate

Вычисления в окне Immediate

Как видно на изображении, в окне Immediate можно вычислять не только математические выражения, но и получать значения встроенных функций VBA и рабочего листа Excel.

Количество строк в окне Immediate

Согласно проведенным опытам, максимальное количество строк в окне Immediate составляет 201 позицию: двести строк с данными и одна — пустая. При заполнении пустой строки, под ней добавляется новая пустая строка, а первая (верхняя) строка с данными исчезает.

Таким образом, максимальная вместимость окна Immediate ограничена 200 строками с данными. Это замечание актуально при выведении больших объемов информации с помощью метода Debug.Print. Допустимое количество знаков в одной строке — 950. Тестирование проводилось в VBA Excel 2016.


На чтение 8 мин. Просмотров 5.3k.

VBA Immediate Window является удивительным инструментом, который позволяет получить моментальные ответы о ваших файлах Excel, и быстро выполнить код. Он встроен в редактор Visual Basic и имеет множество различных применений, которые могут быть очень полезны при написании макросов, отладке кода и отображении результатов кода.

VBA Immediate Window Excel. Определяем количество листов а книге

Каждый пользователь Excel может получить выгоду от Immediate Window, даже если вы не пишете макросы. Эта статья расскажет про 5 различных применений Immediate Window. Как только вы поймете возможности этого инструмента, вы будете использовать его постоянно.

Содержание

  1. Где находитсяImmediate Window?
  2. Эта пустая коробка волшебна!
  3. Открепить Immediate Window
  4. Заключение

Immediate Window
находится в окне редактора Visual Basic.

Как открыть Visual Basic Editor и Immediate Window в Excel и Mac

Самый быстрый способ добраться до Immediate Window — это:

  1. Нажмите Alt + F11 (удерживая клавишу Alt, затем нажмите клавишу F11) из любой места Excel. Откроется окно редактора Visual Basic. (Mac версия Fn + Alt + F11)
  2. Нажатие Ctrl + G открывает окно Immediate и помещает текстовый курсор в него. Начните вводить свой код. (Версия для Mac — Ctrl + Cmd + G)

Когда вы откроете VB Editor (Alt + F11 ), вы можете увидеть, что Immediate Window автоматически появляется в правом нижнем углу. Это его местоположение по умолчанию. Если его там нет, вы можете нажать Ctrl + G или
меню View> Immediate Window.

Эта пустая коробка волшебна!

Когда вы щелкнете внутри Immediate Window, вы увидите пустое
поле с мигающим текстовым курсором. На первый взгляд это не слишком увлекательно,
но Immediate Window может быть очень мощным и полезным инструментом.

Что делает окно Immediate

Думайте об этом, как о пустой ячейке на листе. Довольно скучно, пока вы не добавите формулу, верно?

Итак, давайте рассмотрим 5 примеров, которые помогут вам извлечь максимальную пользу из этой волшебной коробки.

# 1 — Получить информацию об активной книге

Простейшее использование Immediate Window — это быстрое получение информации о Excel-файле, который в данный момент открыт и активен в фоновом режиме. Вы можете проверить любую строку кода VBA в Immediate Window, и она сразу же даст вам результат.

Например, чтобы узнать, сколько листов в активной книге, введите следующую строку кода в Immediate Window и нажмите клавишу «Enter».

?Activeworkbook.Worksheets.Count

Ответ будет отображен в следующей строке Immediate Window,
прямо под кодом.

VBA Immediate Window Excel определяем количество листов через Worksheets.Count

Задайте вопрос, любой вопрос …

Помещение знака вопроса (?) в начале оператора говорит Immediate Window, что мы задаем ему вопрос и ожидаем результата.

В следующем скриншоте показано несколько примеров того, как мы можем использовать Immediate Window для получения значения, формата чисел и цвета заливки активной ячейки.

Excel VBA Immediate Window примеры использования вопросительно знака

Обратите внимание, что Immediate Window отображает интеллектуальные подсказки в тот момент, когда я печатаю. Intellisense — это раскрывающееся меню, в котором отображаются свойства и методы объекта, на который я ссылаюсь. Это позволяет очень быстро и легко вводить код в Immediate Window.

# 2 — Выполнить строку кода VBA

Вам не нужно писать целый макрос, если вам достаточно выполнить одну строку кода в вашей книге.

Удалите знак вопроса в начале оператора, и Immediate Window выполнит эту строку кода.

Выполняем строку кода в VBA Immediate Window

 Selection.HorizontalAlignment = xlCenterAcrossSelection 

На изображении выше показано, как отформатировать выделенные ячейки с помощью выравнивания по центру выделения.

Вы также можете использовать следующую строку кода, чтобы сделать лист «очень скрытым».

Worksheets("Лист1").Visible = xlVeryHidden 

Другой пример — скрыть содержимое ячейки, сделав цвет шрифта
таким же, как цвет заливки (фона).

 Range("A1").Font.Color = Range("A1").Interior.Color

Скрывает значение ячеек с помощью цвета шрифта (Font и Interior.Color)

Я использую эту строку кода в инструменте оглавления Tab Hound, чтобы скрыть некоторые настройки, хранящиеся в ячейке A1. Даже если пользователь изменит цвет заливки листа, содержимое в ячейке A1 все равно будет скрыто после выполнения кода.

# 3 — Запустить макрос

Вы можете запустить макрос из Immediate Window, введя имя
макроса (процедура) и нажав Enter.

Конечно, вы также можете сделать это, нажав клавишу F5 или
кнопку «Выполнить макрос» в VB Editor, но что если ваш макрос содержит
аргументы?

Макрос не может быть запущен изнутри процедуры, если он содержит аргументы. Тем не менее, вы можете вызвать макрос из непосредственного окна.

Пример ниже представляет собой простой макрос, который вводит текущую дату (сейчас) в ячейку и меняет цвет шрифта на синий (Color = vbBlue). Этот макрос требует, чтобы для запуска ему было передано два аргумента: имя листа и адрес ячейки, где будет введена отметка даты.

Запуск VBA Макроса из Immediate Window с использованием аргументов из Excel

Для такого макроса вы обычно будете вызывать его из другого
макроса и указывать аргументы в макросе, который его вызывает. Но если вы
просто хотите протестировать макрос, содержащий аргументы, вы можете
использовать Immediate Window для его вызова.

Это отлично подходит для написания и отладки кода. Возможно,
вы не захотите запускать весь стек процедур (макросов) в коде, но вы можете
использовать Immediate Window, чтобы вызывать только тот конкретный макрос, над
которым вы работаете.

В приведенном выше примере показано, как можно указать
аргументы после имени макроса. Для аргументов, которые являются строковыми
переменными (текст), вам необходимо заключить переменную в кавычки.

Как вы можете видеть на изображении, интеллектуальный помощник доступен в Immediate Window, что позволяет легко указать аргументы для макроса.

# 4 — Просмотр информации об отладке

Вы когда-нибудь видели в Интернете код VBA, в котором есть строка, подобная следующей?

Debug.Print xxxxx

«xxxxx» являются некоторой переменной, которую код вычисляет или производит.

Debug.Print говорит VBA напечатать эту информацию в Immediate Window. Это может быть полезно, когда вы хотите увидеть значение переменной в определенной строке вашего кода, без необходимости хранить переменную где-то в рабочей книге или показывать ее в окне сообщения. Это особенно полезно, когда вы пишете или отлаживаете код.

Пример ниже представляет собой макрос, который проходит по всем листам в книге и проверяет, является ли каждый лист пустым (не используется). Если лист пустой, он отображается в окне Immediate Window с помощью Debug.Print.

Пример работы Debug.Print в VBA Immediate Window

Конечная цель этого макроса может состоять в том, чтобы удалить все пустые листы в книге, но мы могли бы сначала протестировать код перед тем, как фактически удалить какие-либо листы.

Строка Debug.Print создает список пустых листов в Immediate Window, и затем мы можем вручную проверить каждый из этих листов, чтобы убедиться, что они действительно пустые.

# 5 — Получить или установить значение переменной

Immediate
Window также можно использовать для получения ответов о выполняемой в данный
момент процедуре (макросе). Если вы просматриваете свой код (F8) или добавляете
точку останова (F9) или добавляете строку STOP в свой код, тогда код будет
приостановлен. Когда код приостановлен, вы можете использовать Immediate
Window, чтобы получить информацию о любых переменных или объектах, на которые
есть ссылки в коде.

В следующем примере показан макрос, который создает список
всех листов в активной книге. Существует множество различных способов написания
этого кода, но в этом примере я использую переменную «lSht» в цикле «For Next»
для циклического перемещения по рабочим листам, а затем добавляю имя листа на
активный лист.

Excel Макрос вывода списка всех листов - вычисляем значение переменной в Immediate Window

Я добавил точку останова (F9) в коде, чтобы приостановить
код при выполнении этой строки. Когда код приостановлен, Immediate Window можно
использовать для оценки или изменения переменных. На изображении выше я
использовал знак вопроса, чтобы проверить значение переменной lSht. Затем я
использовал переменную, чтобы получить имя листа, который в данный момент
обрабатывается в цикле.

Наконец, я изменил переменную lSht на 5, используя знак равенства (lSht = 5). Это эффективно пропустит некоторые листы в цикле, потому что я изменил переменную с 2 на 5.

Это простой пример, но Immediate Window может пригодиться при пошаговом выполнении кода.

Если вы хотите узнать, как я заставил Immediate Window
плавать поверх приложения Excel на некоторых скриншотах.

Этот скринкаст покажет вам, как вы можете отсоединить
Immediate Window.

Закрепление VBA Immediate Window

Вот
пошаговые инструкции:

  1. Щелкните левой кнопкой мыши и удерживайте
    верхнюю панель Immediate Window.
  2. Перетащите его из окна VB Editor. Immediate
    Window становится свободным плавающим окном, которое вы можете поместить поверх
    Excel.
  3. Чтобы повторно закрепить его, дважды щелкните на
    верхней панели окна.

Вы можете сделать это с любым из окон в редакторе VB,
включая окна Project, Properties, Locals и Watch. Многие разработчики
настраивают VB Editor не так, как макет по умолчанию. Некоторые предпочитают,
чтобы окна проекта и свойств располагались справа, а не слева. Окно VB Editor
дает вам большую гибкость для настройки вашего представления.

Заключение

Immediate Window — очень универсальный инструмент, который действительно может помочь при написании и отладке макросов. Это отличный способ получить быстрые ответы о вашем файле или приложении. Если вы новичок в VBA, Immediate Window будет очень полезен, когда вы начнете изучать и писать код.

The VBA Immediate Window is a great tool that can help any Excel user, even if you are not writing macros. Learn how to get answers about your Excel file, quickly run macros, debug your code, and more. Free file to download contains VBA code samples.

The VBA Immediate Window is an awesome tool that allows you to get immediate answers about your Excel files, and quickly execute code.  It is built into the Visual Basic Editor, and has many different uses that can be very helpful when writing macros, debugging code, and displaying the results of your code.

VBA Immediate Window Excel Worksheets Count

Every Excel user can benefit from the Immediate Window, even if you’re not writing macros.  This post will explain 5 different uses for the Immediate Window.  Once you understand the capabilities of this tool, you will find yourself using it all the time.

Where is the Immediate Window?

The Immediate window is located in the Visual Basic Editor window.

Open Visual Basic Editor and Immediate Window Excel Mac

The fastest way to get to the Immediate Window is to:

  1. Press Alt+F11 (hold Alt key, then press F11 key) from anywhere in Excel.  The Visual Basic Editor window will open.  (Mac version is Fn+Alt+F11)
  2. Pressing Ctrl+G opens the Immediate Window and places the text cursor in it.  Begin typing your code.  (Mac version is Ctrl+Cmd+G)

When you open the VB Editor (Alt+F11) you might see the Immediate Window automatically appear in the bottom right corner.  This is its default location.  If it’s not there you can press Ctrl+G or View menu > Immediate Window.

This Blank Box is Magical!

When you click inside the Immediate Window you will just see a blank box with the text cursor flashing.  At first glance this doesn’t look too exciting, but the Immediate window can be a very powerful and useful tool.

What Does the Immediate Window Do

Think of it like a blank cell in a worksheet.  It’s pretty boring until you add a formula to it, right?  Well the Immediate Window is very similar, so let’s look at 5 examples that will help you get the most out of this magical box.

#1 – Get Info About The Active Workbook

The simplest use for the Immediate window is to quickly get information about the workbook that you currently have open and active in the background.  You can evaluate any line of VBA code in the Immediate Window, and it will immediately give you the result.

For example, to find out how many sheets are in the active workbook, type the following line of code in the Immediate window and then press the Enter key.

?Activeworkbook.Worksheets.Count

The answer will be displayed on the next line of the Immediate window, directly under the code.

VBA Immediate Window Excel Worksheets Count

Ask a question, any question…

Putting the question mark (?) at the beginning of the statement tells the Immediate window that we are asking it a question, and expecting a result.

The following screencast shows a few examples of how we can use the Immediate window to get the value, number format, and fill color of the active cell.

Excel VBA Immediate Window Question Mark Examples

Notice that the Immediate Window displays the intellisense as I type.  Intellisense is the drop-down menu that displays the properties, methods, and members of the object I’m referencing.  This makes it very fast and easy to type code in the Immediate Window.

You can download the free sample workbook that contains a few more useful examples.

#2 – Execute a Line of VBA Code

You don’t have to write a whole macro if you just need to perform one line of code to your workbook.

Remove the question mark at the front of the statement and the Immediate Window will execute or perform that line of code.

VBA Immediate Window Execute Line of Code in Excel
Selection.HorizontalAlignment = xlCenterAcrossSelection
The image above shows how to format the selected cells with the Center Across Selection alignment.

You can also use the following line of code to make a worksheet “very hidden”.

Worksheets(“Sheet1”).Visible = xlVeryHidden

Another example is to hide the contents of a cell by making its font color the same as its fill (background) color.

Range(“A1”).Font.Color = Range(“A1”).Interior.Color
Hide Cell Contents with Font and Interior Color

I use this line of code in Tab Hound’s Table of Contents tool to hide some settings stored in cell A1.  Even if the user changes the fill color of the sheet, the contents in cell A1 will still be hidden after the code is run.

#3 – Run a Macro

You can run a macro from the Immediate Window by typing the name of the macro (procedure), and pressing Enter.

Of course you can also do this by pressing the F5 key or the Run Macro button in the VB Editor, but what if your macro contains arguments?

A macro cannot be run from within the procedure if it contains arguments.  However, you can call the macro from the Immediate Window.

The example below is a simple macro that enters the current date (Now) in the cell , and changes the font color to blue (Color = vbBlue).  This macro requires two arguments to be passed to it to run, the worksheet name and cell address where the date stamp will be entered.

Run VBA Macro from Immediate Window with Arguments Excel

For a macro like this you will typically be calling it from another macro and specifying the arguments in the macro that is calling it.  But if you just want to test the macro that contains arguments, you can use the Immediate Window to call it.

This is great for writing and debugging code.  You might not want to run the entire stack of procedures (macros) in the code, but you can use the Immediate Window to only call that specific macro you’re working on.

The example above shows how you can specify the arguments after the macro name.  For arguments that are string variables (text), you will need to wrap the variable in quotation marks.

As you can see in the image, the intellisense is available in the Immediate Window, which makes it easy to specify the arguments for the macro.

The code in the image above is included in the free sample file you can download below.

#4 – View Debug.Print Info

Have you ever seen VBA code on the internet that contains a line similar to the following?

Debug.Print xxxxx

With that “xxxxx” being some variable that the code is calculating or producing.

Debug.Print is telling VBA to print that information in the Immediate Window.  This can be useful when you want to see the value of a variable in a certain line of your code, without having to store the variable somewhere in the workbook or show it in a message box.  It is especially useful when you are writing or debugging code.

The example below is a macro that loops through all the sheets in the workbook and checks to see if each sheet is empty (not used).  If the sheet is empty then it is listed in the Immediate Window using Debug.Print.

Excel VBA Immediate Window Debug Print List All Empty Sheets Example

The ultimate goal of this macro may be to delete all empty (blank) sheets in the workbook, but we might want to test the code first before actually deleting any sheets.  The Debug.Print line creates a list of empty sheets in the Immediate Window, and we can then manually check each of those sheets to make sure they are really blank.

#5 – Get or Set a Variable’s Value

The Immediate Window can also be used to get answers about the procedure (macro) that is currently running.  If you are stepping through your code (F8) or add a break point (F9) or add a STOP line in your code, then the code will pause.  When the code is paused you can use the Immediate Window to get information about any variables or objects that are referenced in the code.

The following example is a macro that creates a list of all the sheets in the active workbook.  There are plenty of different ways to write this code, but in this example I use the “lSht” variable in a For Next loop to loop through the worksheets and then add the sheet name to the active sheet.

Excel VBA Macro List All Sheets - Evaluate Variable Immediate Window

I added a break point (F9) in the code to pause the code when that line is executed.  With the code paused, the Immediate Window can be used to evaluate or change variables.  In the image above I used the question mark to check the value of the lSht variable.  Then I used the variable to get the sheet name of the sheet that is currently being processed in the loop.

Finally I changed the lSht variable to 5 by using the equals sign (lSht = 5).  This will effectively skip some of the sheets in the loop because I changed the variable from 2 to 5.

This is a simple example, but the Immediate Window can come in handy when stepping through code.

Pete asked a great question in the comments below.  He wanted to know how I made the Immediate Window float on top of the Excel application in some of the screenshots.

This screencast shows you how you can undock the Immediate Window.

Docking the VBA Immediate Window

Here are the step-by-step instructions:

  1. Left-click and hold on the top bar of the immediate window.
  2. Drag it out of the VB Editor window. The immediate window becomes a free floating window that you can put on top of Excel.
  3. To re-dock it, double-click on the top bar of the immediate window.

You can do this with any of the windows in the VB Editor including the Project, Properties, Locals, and Watch windows.  Many developers will setup their VB Editor differently than the default layout.  Some prefer to have the project and properties windows on the right side instead of the left.  The VB Editor window gives you a lot of flexibility to customize your view.

Download

You can download the workbook that contains the code for all these examples in the link below.

Conclusion

The Immediate Window is a very versatile tool that can really help when writing and debugging macros.  It’s a great way to get some quick answers about your file or application.  If you are new to VBA, the Immediate Window will be very useful as you start learning and writing code.

What do you use the Immediate Window for?  Please leave a comment below with your suggestions, or any questions.

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!

‘Immediate window’ can be a useful tool to use when working with VBA in Excel.

The Immediate window allows you to quickly do things such as:

  • Get information about Excel files (such as sheet count in a workbook or name of the workbook)
  • Get Debug.Print information quickly
  • Run a line of code in seconds
  • Run a macro (or call a function)
  • Get information about variables (or set the value or variables)

While you don’t need to use immediate window to work with VBA in Excel, knowing how to use it well can make you a lot more efficient.

In this tutorial, I will cover all that you need to know about the immediate window and how to best use it (explained with examples).

Let’s get started!

What is an Immediate Window in Excel VBA?

Immediate Window is a part of the VB Editor which you can use to do some quick stuff.

To give you an example, if you have a workbook with some hidden worksheets and you want to quickly know the count of total worksheets, you can do that in a few seconds with the Immediate window.

Immediate Window does a lot more (as you’ll see later in this tutorial). But to begin with, let’s just think of immediate window as a tool to help you speed up your work in Excel VBA.

Where to Find the Immediate Window?

When you open the Excel VB-Editor, you may already see the immediate window as a part of the VB Editor. And if you don’t see it already, you can easily make it show up.

This is Immediate Window in Excel VB Editor

Below are the steps to open the VB Editor and make the Immediate Window visible:

  1. Click the ‘Developer’ tab in the Excel ribbon (if you don’t see the developer tab, click here to learn how to get it)Click the Developer Tab
  2. In the Code Group, click on ‘Visual Basic’. This will open the VB EditorClick on Visual Basic option
  3. In the VB Editor, click on the ‘View’ option in the menuClick on the View Option in the menu
  4. Click on Immediate Window. This will make the immediate window show up in the VB Editor.Click on the Immediate Window Option

If you’re more comfortable with shortcuts, below are some to speed up the above steps:

  • To open the VB Editor – ALT + F11 (this works even if you don’t have the Developer tab in the ribbon)
  • To show the immediate window – Control + G (use this one the VB Editor is open)

Examples of Using Immediate Window in Excel VBA

Now that you know where to find the immediate window, let’s see some awesome examples where you can use it when working with Excel VBA.

Get Information About the Files/Workbooks

The ‘Immediate Window’ is a place where you can ask questions about the workbooks and it will give you the answer right away.

For example, suppose you have a workbook and you want to know how many sheets are there in the workbook, you can type the below code in the immediate window and hit the enter key.

?ActiveWorkbook.Sheets.Count

This will instantly tell you the total number of sheets in the active workbook.

Get Sheet Count in Immediate Window with a single line

This can be useful when you have a workbook that has a lot of sheets and you can’t count it manually (or don’t want to), or when you have a workbook where there are hidden sheets and you want to know the total count.

The ? (question mark) is supposed to be used before the query so that VBA can understand that you’re asking a question. If you don’t use this question mark, immediate window will not give you the detail/answer.

Now, this is a really simple example where Immediate Window gives you some information and saves time.

Below are some more examples:

To get the name of the active workbook

?ActiveWorkbook.Name

To get the name of the active sheet

?Activesheet.Name

To get the path of the Workbook (the address where it’s saved)

?ActiveWorkbook.Path

So if you need something about an object (such as Workbook, sheets, charts, shapes, range, etc.), you can use immediate window to quickly get this information.

Get Debug.Print Information

In Excel VBA, Debug.Print is used to show the value of a variable instantly in the immediate window.

For example, the below code would instantly show the message “Good Morning” in the immediate window.

Sub DisplayMessage()
Debug.Print "Good Morning"
End Sub

Debug.Print instantly shows the result in immediate window

You can use the Debug.Print line in your code to quickly get some data in the immediate window or to debug your code.

For example, if you want to get the names of all the sheets in a workbook, you can use the below code:

Sub GetSheetNames()
For Each sh In ActiveWorkbook.Sheets
    Debug.Print sh.Name
Next sh
End Sub

The above code goes through each sheet in the active workbook and gives the name in the immediate window.

Get Sheet names in the immediate window

Debug.Print is a useful technique to debug your code. For example, if you’re running a loop and want to see how many times the loop was run, you can simply place a Debug.Print line that simply shows the incrementing numbers when each loop runs.

If you’re using Debug.Print to debug the code, remember to remove it when you’re done.

Run a macro (or a function)

While there are various ways to run a macro in Excel, one of the quick ways is using the immediate window.

To run a macro, all you need to do is enter the name of the macro in the immediate window and hit the enter key (the cursor should be at the end of the macro name for this to work).

Below is an example, where as-soon-as you enter the name of the macro in the immediate window, it runs the code (where the code displays the message “Good Morning” in the immediate window).

Run a Macro code from Immediate Window by typing the name

This can be useful when you have a code and want to check whether it’s performing as expected or not. You can have one or more Debug.Print lines in the code and run the macro from the immediate window.

It will instantly show you the values in the immediate window and you can check whether everything is working fine or not.

You can also use the immediate window to execute custom functions as well.

For example, in the below example, a function is created to check whether a number is even or odd. You can run this function from the immediate window by typing the function with the argument it takes. You need to use the question mark in this case as you’re asking it t return a value stored in the function.

Execute a Formula from Immediate Window

Execute a Line of Code (or Multiple Lines of Code)

With immediate window, you can also run a line of code (or multiple lines of codes).

The best part about this is that you can simply open the immediate window, run the code and close (unlike a macro which you have to put in a module window and then execute).

A use-case where this can be useful is when want to quickly unhide all the sheets in the workbook.

Below is the code that you can place in the immediate window to unhide all the sheets in the workbook. Place the cursor at the end of the line and as soon as you hit the enter key, it will unhide all the sheets.

For each Sheet in Thisworkbook.Sheets: Sheet.Visible=True: Next Sheet

Unhide all sheets from immediate window by using a loop

Note that although this looks like a single line of code, it’s made up of three parts.

Each part is separated with a : (colon), which acts like a line break. This allows you to use the For Next loop in the immediate window to go through each sheet and change the visible property to TRUE (which unhides any hidden sheet).

Get Variable Values

As you start creating complex VBA codes, you would have to rely on variables to do the job.

A variable is something that holds a value and this value can change when the code is running. You can use an immediate window to check these variable values.

Below is a simple code which gives the sum of the first 10 positive integers and shows the result in the immediate window.

Sub AddFirstTenNumbers()
Dim Var As Integer
Dim i As Integer
Dim k As Integer
For i = 1 To 10
    k = k + i
Next i
Debug.Print i, k
End Sub

As soon as you run this code, you will see the below result in the immediate window. This instantly tells you that the code is working fine and is giving the expected result.

Debug the code using immediate window

In case it isn’t giving the expected results, you can debug the code.

A lot of people use a message box while debugging the code. While it works fine, I find it a little intrusive as it takes me to the Excel workbook and shows a message box. On the other hand, using immediate window to debug is a lot smoother and keeps me in the Visual Basic editor itself.

Note: If you’re working with a complex code and have multiple variables that you need to track, it’s better to use a Watch Window. A Watch Window allows you to add a variable and then you can see how that variable changes in real-time (or as you step through the code).

Set Variable Value when Debugging

This is a little advanced use of the Immediate window, but if you use it, it can be a huge time saver when debugging the code.

You can use the immediate window to set the value of a variable while you run the code in the debug mode (where you set a breakpoint so the code doesn’t execute fully – but up to a specific line).

For example, if you have a loop that runs for 10 times and you want to check what happens when the loop runs for the 8th time, you don’t need to step through the loop seven times to get to the eighth iterations. You can simply add a breakpoint before the loop and change the loop variable to 8. Now, when you run the code, it will show you what happens when the loops run for the 8th time.

This becomes a lot more useful when you’re writing complex codes and want to debug specific loops.

Suppose you have a code as shown below:

Sub UnhideSheets()
For i = 1 To Worksheets.Count
    Debug.Print Sheets(i).Name
Next i
End Sub

The above code simply lists the sheet names of all the sheets in the workbook in the immediate window.

If you don’t want to list the names of all the sheets, but only the sheets after the 10th sheet, you can place a breakpoint in the second line of the loop (so that nothing after that line is executed) and then change the variable ‘i’ to 11.

To change the variable name in immediate window, enter the following line:

i=11

This will ensure that the first 10 times of the loop are ignored and your variable value is set to 11.

Setting the variable using immediate window

Docking/Undocking the Immediate Window

You can have immediate window docked to the VB Editor – which means that it remains at one place in the VB Editor and moves and sizes with it.

And you can also have it un-docked, which means it’s independent of the VB Editor and can be moved as a standalone window.

Below is how you can change the docking settings for the immediate window:

  1. Click the Tools option in the menu in the VB EditorClick the Tools option in the VB Editor
  2. Click on ‘Options’Click on Options in the Tools drop-down
  3. In the Options dialog box, click on the last tab – Docking
  4. Check the Immediate Window option to make it dockable and uncheck it to make it un-dockable.Make the VB Windows dockable
  5. Click OK

Alternatively, if the immediate window is visible, you can also right-click and change the dockable property of it.

Dockable means that the immediate window would become a part of the existing window by placing itself in certain places, such as the left of the window or at the bottom. This allows the docked windows to move and size together.

Immediate Window is Not Showing – Here are Some Ways to Get It

There could be multiple reasons for this happening.

The most common reason that you don’t see an immediate window is that it has not made visible. It may not be visible by default and to make it appear, you need to go to the View option in the menu and click on the Immediate Window option. This will make sure it’s visible in the VB Editor.

You can also use the keyboard Control + G to make the immediate window show up. Use this keyboard shortcut while you are in the VB Editor.

Another reason you may not see the immediate window is that it’s been minimized is now so closed that you can’t see it (as reported here). Just do a quick scan and check if you see a small blue/red square lurking somewhere. You can hover the cursor over it and you will see some option to resize it.

If you can’t see the immediate window at all, here is something that has worked for a lot of people (this often happens because of screen resolution changes):

  1. Open the VB Editor
  2. Press Ctrl-G to give focus to the immediate window (or click the View option in the menu and then click on immediate window)
  3. Hold the ALT key and then press the spacebar key. This will show drop-down options for the immediate window.
  4. Press M (for Move)
  5. Use the arrow keys to move the window
  6. Once you figure out where it is, make it bigger

I got this from a forum here and also noticed the same being suggested as a solution for VBA immediate window not showing up.

Another thing you can try is making the immediate window undockable (go to Tools –> Options –> Docking and uncheck the immediate window option). This has worked for some people.

You may also like the following articles:

  • Excel Personal Macro Workbook | Save & Use Macros in All Workbooks
  • Excel VBA Loops: For Next, Do While, Do Until, For Each (with Examples)
  • Working with Worksheets using Excel VBA
  • Creating a User Defined Function (UDF) in Excel VBA

Понравилась статья? Поделить с друзьями:
  • Excel vba найти текст на листе
  • Excel vba одинаковые строки
  • Excel vba найти первую пустую строку
  • Excel vba объект лист
  • Excel vba найти одинаковые значения в