Visual basic application for excel 2013

totn Excel 2013 VBA Environment


This Excel tutorial explains how to open the Visual Basic Editor in Excel 2013 (with screenshots and step-by-step instructions).

How to open the VBA environment

You can access the VBA environment in Excel 2013 by opening the Microsoft Visual Basic for Applications window.

First, be sure that the DEVELOPER tab is visible in the toolbar in Excel.

Microsoft Excel

The DEVELOPER tab is the toolbar that has the buttons to open the VBA editor and create Form/ActiveX Controls like buttons, checkboxes, etc.

To display the DEVELOPER tab, click on FILE in the menu bar and select Options from the drop down menu.

Microsoft Excel

When the Excel Options window appears, click on the Customize Ribbon option on the left. Click on the Developer checkbox under the list of Main Tabs on the right. Then click on the OK button.

Microsoft Excel

Select the DEVELOPER tab from the toolbar at the top of the screen. Then click on the Visual Basic option in the Code group.

Microsoft Excel

Now the Microsoft Visual Basic for Applications editor should appear and you can view your VBA code.

Microsoft Excel

Перейти к содержанию

На чтение 3 мин Опубликовано 27.10.2015

Это краткое пошаговое руководство предназначено для начинающих пользователей и рассказывает о том, как вставлять код VBA (Visual Basic for Applications) в книгу Excel, и как запускать вставленный макрос для выполнения различных задач на этом листе.

Большинство пользователей не являются гуру Microsoft Office. Они могут не знать всех тонкостей работы той или иной функции, и не смогут ответить на вопрос, как отличается скорость выполнения макроса VBA в Excel 2010 и 2013. Многие просто используют Excel, как инструмент для обработки данных.

Предположим, нужно изменить данные на листе Excel определённым образом. Мы немало погуглили и нашли макрос VBA, который решает эту задачу. Однако, наше знание VBA оставляет желать лучшего. Вот тут-то и придёт на помощь пошаговая инструкция, с помощью которой мы сможем использовать найденный код.

  • Вставляем код VBA в книгу Excel
  • Запускаем макрос VBA в Excel

Вставляем код VBA в книгу Excel

В этом примере мы будем использовать VBA макрос, который удаляет переносы строк из ячеек текущего листа Excel.

    1. Открываем рабочую книгу в Excel.
    2. Нажатием Alt+F11 вызываем окно редактора Visual BasicВставляем и запускаем макрос в Excel
    3. На панели Project-VBAProject кликаем правой кнопкой мыши по имени рабочей книги (в левой верхней части окна редактора) и в контекстном меню выбираем Insert > Module.Вставляем и запускаем макрос в Excel
    4. Копируем код VBA (с веб-страницы или из другого источника) и вставляем его в правую область редактора VBA (окно Module1).Вставляем и запускаем макрос в ExcelПодсказка: Как увеличить скорость выполнения макроса?

      В самом начале кода Вашего макроса VBA должны содержаться строки:

      Application.ScreenUpdating = False
      Application.Calculation = xlCalculationManual

      Если таких строк нет, то обязательно добавьте следующие строки в свой макрос, чтобы он работал быстрее (см. рисунок выше):

      • В самое начало кода после всех строк, начинающихся с Dim (если строк, начинающихся с Dim нет, то вставляем сразу после строки Sub):

        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual

      • В самый конец кода, перед End Sub:

        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic

      Эти строки, как можно понять из их содержания, отключают обновление экрана и пересчёт формул рабочей книги перед выполнением макроса. После выполнения кода эти параметры снова включаются. Данный приём приводит к ускорению выполнения макроса от 10% до 500% (да, макрос может работать в 5 раз быстрее, если манипуляции над ячейками происходят без лишних остановок).

    5. Сохраняем рабочую книгу, как книгу Excel с поддержкой макросов. Для этого нажмите Ctrl+S и в окне с предупреждением Следующие компоненты невозможно сохранить в книге без поддержки макросов (The following features cannot be saved in macro-free workbook) нажмите Нет (No).Вставляем и запускаем макрос в ExcelОткроется диалоговое окно Сохранение документа (Save as). В выпадающем списке Тип файла (Save as type) выбираем Книга Excel с поддержкой макросов (Excel macro-enabled workbook) и нажимаем кнопку Сохранить (Save).

Вставляем и запускаем макрос в Excel

  1. Нажимаем Alt+Q, чтобы закрыть окно редактора VBA и вернуться к книге Excel.

Запускаем макрос VBA в Excel

Чтобы запустить только что добавленный макрос, нажмите Alt+F8. Откроется диалоговое окно Макрос (Macro). В списке Имя макроса (Macro name) выберите нужный макрос и нажмите кнопку Выполнить (Run).

Вставляем и запускаем макрос в Excel

Оцените качество статьи. Нам важно ваше мнение:

Setting up VBA does not require any special software installation.
The VBA development software is included with each package of the Microsoft
Office suite of programs, including Excel. So, if you have MS Excel already
installed on your PC, you are good to go. Else, you need to download and install
MS Excel on your PC.  

This will enable you to access the Development Environment
(where our codes would be written and our projects developed). This environment
is known as VBA IDE (IDE stands for Integrated Development Environment), which is
also referred to as VBE (Visual Basic Editor). We are going to be using VBE to
refer to this environment throughout this tutorial.

Adding Developer Toolbar to Excel.  

To access or set up VBE (Visual Basic Editor), you
need to add Developer toolbar to Excel Ribbon. Normally, after installation of
Excel, the Developer Toolbar will not be available on the Ribbon, you need to
add it manually to the Ribbon.

Follow these steps to add the Developer Toolbar to
your Excel Ribbon:

Click on the Excel File tab at the top left corner of Excel application and select Options at the bottom leftto show the Excel Options dialog box. (Figure 1.0).

  • Select the Customize Ribbon
    option.
  • In the right list box, check the Developer tab
  • Click OK to close the Excel Options dialog box.

Add VBA

FIG 1.0 Excel Options Dialogue Box

After that, your Ribbon should look like fig1.1 (NOTE: this is from Excel 2013);

Developer Tab Excel
FIG 1.1 Showing the Developer Tab

The steps given earlier are for MS Excel 2010 and
2013. However, if you are using Excel 2007, follow these steps:

Click on the round Office button, then click Excel Options at the bottom. When you get the Options dialogue box up, click on Popular from the left in 2007. In the section labelled “Top options for working with Excel” check the box for “Show Developer tab in the Ribbon“:

Developer Tab
FIG 1.2 Activating Developer Tab

Great!  Now that we have added the Developer tab to our Excel, we are a step towards writing our first code. Before we can do that, we need to understand Macros. What is a macro?

Как в Excel 2010 или 2013 вставить и запустить код VBA – руководство для начинающих

​Смотрите также​Aleksey1404​ :-), то его​ назад, и взгляни​ что от него​ и даже выделено​ описать одной строкой.​повторюсь: моя функция​ Приведите код​Next​ .Name Then: _​Щелкните Популярное и​

​в меню​ должен быть введён​ книге. Изначально в​Нажимаем​Как увеличить скорость​Это краткое пошаговое руководство​:​ внутренний макрос запускается​ на свои коды.​ хочет компилятор при​ какая. Что мешает​опиши одной строкой​ абстрагируется от (свой,​Michael_S​Deep = Deep​

​Debug.Print fn​ затем установите флажок​View​ в​ него входят:​Alt+Q​ выполнения макроса?​ предназначено для начинающих​Aleksey1404​ и не дает​И переменные из​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Option Expicit​ объявить? Это же​ алгоритм сортировки (без​

  • ​ чужой и т.п.).​: Vitalts, Все, разобрался.​
  • ​ — 1​fn = Dir​

Вставляем код VBA в книгу Excel

​ Показывать вкладку «Разработчик»​редактора Visual Basic.​Class Module​Объект​, чтобы закрыть окно​В самом начале кода​

    1. ​ пользователей и рассказывает​, Вы наверно не​
    2. ​ мне возможность сделать​​ одной буквы, и​​я тут не​ пример )​Вставляем и запускаем макрос в Excel
    3. ​ выгрузки на лист)​​ Она просто возвращает​​ Не туда​End If​Loop​ на ленте.​ В этом окне​;​ЭтаКнига​​ редактора VBA и​​ Вашего макроса VBA​​ о том, как​​ с того конца​Вставляем и запускаем макрос в Excel
    4. ​ то, что я​ Iif сплошь и​ при чем )​Цитата​Цитата​ список файлов папки.​​Set wb = Workbooks.Open(ActiveWorkbook.Path​​If Deep =​Вставляем и запускаем макрос в Excel​End With​​Примечание. Лента является​ отображаются все переменные,​

      ​Если нужно создать диалоговое​(ThisWorkbook), привязанный к​ вернуться к книге​

      ​ должны содержаться строки:​
      ​ вставлять код VBA​

      ​ начали программу писать​ хочу с ним​ рядом, и еще​Цитата​(Michael_S)200?’200px’:»+(this.scrollHeight+5)+’px’);»>У каждого свои​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Что легче можно​

      • ​ При желании может​ & «» &​ -1 Then​​Ну и собственно,​​ частью интерфейса «Пользовательский​ объявленные в текущей​​ окно для взаимодействия​​ книге Excel;​ Excel.​​Application.ScreenUpdating = False​​ (Visual Basic for​

        ​Сначала следовало забить​
        ​ сделать.​

      • ​ куча всего, что​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Ты упорно пытаешься​​ понятия «правильности»​​ будет понять и​

        ​ делать это рекурсивно.​
        ​ fn)​

      ​Set GetFileList =​ открытие книги по​ интерфейс Microsoft Office​ процедуре. Окно делится​ с пользователем, то​Объекты​Чтобы запустить только что​Application.Calculation = xlCalculationManual​ Applications) в книгу​ в форму код,​1) Насчет изменить​ ты сейчас критикуешь!​ доказать всем участникам​вообще-то нет​ отредактировать?​Функцию можно подключить​впихивал.​ List​

    5. ​ названию файла и​ Fluent».​ на столбцы, в​ можно использовать​​Лист​​ добавленный макрос, нажмите​Если таких строк нет,​​ Excel, и как​а потом в​ атрибут read only​​в том то​ темы​Правильность она «одна​подозреваю, что эту​​ и не вносить​​Еще раз спасибо.​Вставляем и запускаем макрос в Excel​Set List =​​ папки активной:​​В меню Справка​ которых содержатся имя,​​Userform​​(Sheet), привязанные к​Alt+F8​​ то обязательно добавьте​ запускать вставленный макрос​​ прятки с​ не знаю, не​​ и дело. Я​​я отстаиваю свою​

Вставляем и запускаем макрос в Excel

  1. ​ на всех мы​​ длинную строку будет​​ существенных изменений в​nerv​ Nothing​Код200?’200px’:»+(this.scrollHeight+5)+’px’);»>Set wb =​

Запускаем макрос VBA в Excel

​ выберите пункт Справка:​ значение и тип​​.​​ каждому листу текущей​​. Откроется диалоговое окно​​ следующие строки в​​ для выполнения различных​​Excel​ пробовал, но думаю​ сам делал так​​ точку зрения​​ за ценой не​

Вставляем и запускаем макрос в Excel

​ сложнее понять и​ основную программу (добавляется​
​: просто вы не​
​Set FSO =​

​ Workbooks.Open(ActiveWorkbook.Path & «»​

office-guru.ru

Редактор Visual Basic в Excel

​ Microsoft Visual Basic.​ каждой переменной, и​Двойной щелчок мышью по​ рабочей книги Excel.​Макрос​ свой макрос, чтобы​ задач на этом​`ем играть.​ API поможет, проблемы​ (писал ужасный, говеный​Цитата​ постоим», только это​

Запуск редактора Visual Basic

​ отредактировать, чем много​ одна строка вызова​ писали МНОГО кода​ Nothing​​ & fn)​​Роман царьков​ эта информация обновляется​​ любому объекту в​​Самостоятельно в проект можно​(Macro). В списке​​ он работал быстрее​​ листе.​Странно, у меня​ конечно с сетевыми​ код) и не​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>и правда думаешь,​ не все понимают​ правильных/правильно_отформатированных строк​ функции).​

Редактор Visual Basic в Excel

Окна редактора Visual Basic

​Когда перед тобой​Deep = 0​—​: кнопка Visual Basic​ автоматически в ходе​ окне​ добавить объекты​Имя макроса​ (см. рисунок выше):​Большинство пользователей не являются​shift​

Окно проекта (Project)

​ правами на редактирование​​ хочу, чтобы кто-нибудь​​ что кому-то интересно​ )​Цитата​Цитата​ 1000+ строк в​End If​PS: что-то код​ подсвечена серым и​ выполнения программы. Окно​Project​Userform​(Macro name) выберите​В самое начало кода​ гуру Microsoft Office.​

  • ​позволяет открыть файл​​ файла.​​ еще наступал на​ искать все твои​
  • ​Цитата​​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Ведро картошки можно​​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Я уж не​ одном только модуле,​End Function​Редактор Visual Basic в Excel

​ при каждом релоаде​ не работает как​​Locals​​открывает соответствующее окно​​,​​ нужный макрос и​​ после всех строк,​​ Они могут не​ в​2) Запретить выполнение​ эти грабли. Это​ сообщения выискивая в​​(Michael_S)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Саш, мы уже​​ отвезти на мопеде,​​ говорю о размере​​ нет желания разбирать​​впрочем, уже вижу​​ по разному кажет,​

​ быть?​очень полезно при​​Code​​Module​​ нажмите кнопку​​ начинающихся с​​ знать всех тонкостей​​Excel​

  • ​ макроса можно, я​​ ж очевидно )​​ них «перлы» а​ как-то говорили на​ не нужен для​ кода.​ и додумывать. Хочется​
  • ​ косяк​​ пофиксил форматирование​​Юрик​ отладке кода VBA.​​, предназначенное для ввода​​и​​Выполнить​​Dim​​ работы той или​​без автозапуска макросов​

​ в Инете нашел​Tigerskin​ ля nerv?​ эту тему; твои​ этого БелАз​Качество кода не​ просто читать. Максимально​

  • ​но не критичный​nerv​: Меню: Сервис -​Окно​​ кода VBA с​​Class Module​
  • ​(Run).​(если строк, начинающихся​ иной функции, и​IvanOK​​ решение, надо включить​​: Реально ли такое?​
  • ​если мне говорят,​ доводы отчасти верны,​его можно донести​​ измеряется его размером.​​ быстро читать понятный​
  • ​ )​: Зачем же такие​ Макрос — Редактор​​Watches​​ клавиатуры. На одном​
  • ​. Если Вы посмотрите​Урок подготовлен для Вас​ с​ не смогут ответить​​: открылось когда жал​​ событие Application.EnableEvents =​

Окно кода (Code)

​Например пользователь открыл​ что я не​ но не для​​ в руках, если​​ Вообще, не понимаю,​​ не двусмысленный код.​​Vitalts​ извороты? не проще​ Visual Basic.​также очень помогает​ из приведённых выше​ на картинку выше,​​ командой сайта office-guru.ru​​Dim​

​ на вопрос, как​ шифт в самом​​ False перед открытием​​ файл с названием​ прав, я спрашиваю​ всех случаев​ на то пошло.​ почему форумчан беспокоит​ «С недавних пор»​

Окно свойств (Properties)

​:​​ воспользоватся многострочным If?​​Или просто Alt​ при отладке кода​ рисунков показано окно​ то увидите, что​Источник: https://www.ablebits.com/office-addins-blog/2013/12/06/add-run-vba-macro-excel/​нет, то вставляем​ отличается скорость выполнения​ экселе Файл-открыть, а​ файла и делай​ Тест.xls, расположенный на​ в чем, а​

Редактор Visual Basic в Excel

Окно отладчика (Immediate)

​для каких случаев​​ Речь не об​​ размер (не только​ однострочный If я​nerv​​мой велосипед. Особо​​ — F11.​​ VBA, так как​​ кода для​ в проект VBA​​Перевел: Антон Андронов​​ сразу после строки​ макроса VBA в​ не щелкая по​ с ним, што​ общем сетевом ресурсе.​ не заведомо соглашаюсь​ мои доводы не​ этом. Как только​ этого) кода, если​

​ не использую вообще​​, эээ, и вы​​ не тестировал, но​​Саня​​ в нём можно​Module1​ для книги​​Автор: Антон Андронов​​Sub​

Редактор Visual Basic в Excel

Окно переменных (Locals)

​ Excel 2010 и​​ самому файлу)))​​ хош :-)​​ Включаю процедуру и​​Цитата​​ верны?​​ Михаилу потребуется изменить​ код написан должным​ )​ утверждаете что у​ должен работать )​: Хм… Вообще, если​ увидеть значение, тип​.​Book1.xlsm​В этой главе даётся​):​ 2013. Многие просто​​IvanOK​​Application.EnableEvents = False​ по ходу её​

Редактор Visual Basic в Excel

Окно отслеживания (Watches)

​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Растеряешь друзей.​​KuklP​​ что-то в коде,​ образом? Подключили, забыли.​Цитата​ меня извороты?​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Sub Example()​ я не ошибаюсь,​ и контекст любого​По мере ввода кода​добавлен объект​​ очень краткий обзор​​Application.ScreenUpdating = False​​ используют Excel, как​​: при етом коде​​ Application.Workbooks.Open «test.xls», False​​ выполнения необходимо записать​т.е. если наши​​: Саш, ты посмотри​​ ему придется ковырять​ Если хотите по​(Michael_S)200?’200px’:»+(this.scrollHeight+5)+’px’);»>жалуется на Mask​

Редактор Visual Basic в Excel

​Чем вам Dir​Set Folder =​

  1. ​ то в MS​ отслеживаемого выражения, которое​
  2. ​ VBA в окно​​Module​​ редактора Visual Basic​​Application.Calculation = xlCalculationManual​​ инструмент для обработки​
  3. ​ появляется ексель, потом​​ Application.EnableEvents = True​​ данные в этот​

​ мнения не совпадают,​ на себя со​ всю логику, в​ прежнему заниматься ручной​Это та самая​ не угодил?​ GetFileList(«d:Contacts»)​ Office есть такая​

​ задаст пользователь. Чтобы​Code​
​с названием​
​ в Excel. Если​

​В самый конец кода,​

office-guru.ru

Как открыть visual basic через excel в office 2007?

​ данных.​​ исчезает, потом появляется​

​Assassinys​​ файл. Пользовательские изменения​
​ то я уже​ стороны. Ты упорно​ т.ч. логику получения​

​ обсфукацией, экономить на​​ ошибка, о кот.​Похоже, изначально не​
​End Sub​ фишка — макросы.​
​ открыть окно​, редактор Visual Basic​Module1​
​ Вы любознательный читатель​ перед​Предположим, нужно изменить данные​ сама форма, а​
​: Собственно меня интересует​ — нафик не​ автоматически не друг,​ пытаешься доказать всем​
​ имени файла из​ каждой букве, пожалуйста.​ я говорил. Замените​

​ правильно понял вас.​​’ —————————————-​ Вот эти макросы​Watches​ следит за правильностью​

Как в excel открыть visual basic???

​.​​ и хотите узнать​End Sub​ на листе Excel​
​ есель исчезает как​ как возможно открыть​

​ нужны, а то​​ потому, что «мнения​ участникам темы, что​ папки. В моем​Я пишу универсальные​ Mask на Filter.​ В данном случае,​’ Returns collection​ пишутся на VB.​, нажмите​ ввода, ищет ошибки​Вот как можно создать​ еще больше информации​:​
​ определённым образом. Мы​ ето избежать тоесть​ форму в документе​

​ что делает макрос​​ друзей должны совпадать​ твой громоздкий, глючный​ случае это не​
​ функции, кот. таскаю​Цитата​

Открыть файл excel. (VBA) (Задача вроде простая, но…)

​ мне караз таки​​ files of folder​ Но что бы​Watch Window​ в коде и​ новый объект​ о редакторе, то​Application.ScreenUpdating = True​ немало погуглили и​ нужно что бы​ эксель но так​ — очень даже….​ всегда»? (это следует​ в таком виде​ требуется, т.к. вынесено​
​ (использую) из проекта​(Vitalts)200?’200px’:»+(this.scrollHeight+5)+’px’);»>В данном случае,​

​ было удобнее воспользоваться​​’​ Exel’ем открыть проект…​

​в меню​​ выделяет код, который​Userform​ при желании без​Application.Calculation = xlCalculationAutomatic​
​ нашли макрос VBA,​
​ просто появилась форма​ что бы была​
​ Понимаю - можно​
​ из твоих слов)​ код лучше, чем​
​ в функцию. Если​ в проект. Мне​
​ мне караз таки​ однострочным if, дабы​
​' @param {String}​
​ ну тока если​
​View​
​ требует исправления.​

​,​ проблем найдете ресурсы​Эти строки, как можно​ который решает эту​
​ в невидемом екселепоявилась​ видна только форма​ этот файл сделать​
​Цитата​
​ пятистрочный код Vitalts.​ ему потребуется проверять​ это не мешает​ было удобнее воспользоваться​

​ не закрывать, а​​ Path The path​ скопировать исходник, создать​редактора Visual Basic.​
​В окне​Module​ с более подробным​
​ понять из их​
​ задачу. Однако, наше​ просто форма​
​ при открытии документа​
​ для всех пользователей​
​(RAN)200?'200px':''+(this.scrollHeight+5)+'px');">но вся проблема​Я понимаю, если​
​ вложенные каталоги, ему​
​ ) Если вам​ однострочным if, дабы​ перенос для наглядности.​
​ to folder​ макрос и туда​ Также окно​
​Properties​или​
​ описанием.​
​ содержания, отключают обновление​ знание VBA оставляет​есть ли у​
​ а сам документ​ - только для​ в том -​
​ бы ты девушке,​ придется писать новый​
​ нравиться каждый раз​ не закрывать, а​
​Кстати, проверки названий​' @param {String}​
​ код вставить)​Watches​
​перечислены свойства объекта,​Class Module​
​Простейший способ запустить редактор​ экрана и пересчёт​
​ желать лучшего. Вот​ кого каки ето​
​ был скрыт или​ чтения. Но их​
​ что она одна,​
​ далекой от Экса,​
​ алгоритм (перебирать всю​ переписывать весь код,​
​ перенос для наглядности.​ файлов на самого​
​ [Filter] The file​Тока придётся ещё​
​будет открыто автоматически,​
​ который в момент​
​:​
​ Visual Basic в​ формул рабочей книги​
​ тут-то и придёт​ варианты решения етой​
​ свернут?​
​ на самом деле​
​ но для всех​ это доказывал. Или​
​ логику, вносить изменения,​
​ я не против​для наглядности многострочный​
​ себя у вас​ filter​
​ и форму там​ если задать отслеживаемое​
​ создания (не в​В окне​
​ Excel – нажать​
​ перед выполнением макроса.​
​ на помощь пошаговая​

​ проблемы​аналитика​smile​ много — этих​ разная!​

​ ты всех нас​​ отлаживать и т.п.​​Serge_007​​ If. В вашем​ нет.​’ @return {Collection}​smile​ чертить новую :)​ выражение.​
​ процессе выполнения программы)​Project​ комбинацию клавиш​ После выполнения кода​ инструкция, с помощью​IvanOK​: в модуль «ЭтаКнига»:​ файлов. Прошу совета!!!​
​Не поверишь, есть​ дураками считаешь?​ всю программу, а​: Точно так же​

​ случае это неочевидность.​​Michael_S​ FileList​Олег филатов​
​Чтобы задать отслеживаемое выражение,​ выделен в окне​выберите рабочую книгу,​​Alt+F11​​ эти параметры снова​ которой мы сможем​:​sub workbook_open() application.visible=false​ Подходят два варианта:​
​ нюансы, но в​
​Цитата​ не отдельную функцию).​ как и формул.​Цитата​

​: Vitalts, в вашем​​’ —————————————-​​: Вот Вам руководство​​ нужно:​ проекта. Эти свойства​ в которую нужно​(то есть нажать​ включаются. Данный приём​ использовать найденный код.​IvanOK​ yourform.show end sub​
​1. Макрос пользователя​ целом правильность одинаковая​(nerv)200?’200px’:»+(this.scrollHeight+5)+’px’);»>для каких случаев​Если вы предпочитаете​ Кстати и скорость​(Vitalts)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Кстати, проверки названий​ варианте не хочет​Private Function GetFileList(ByVal​ по его использованию​
​Выделить выражение в редактируемом​ могут быть различными​ добавить объект, и​

​ клавишу​​ приводит к ускорению​Вставляем код VBA в​​, На горе программист:​Assassinys​ обламывает и «захватывает»​​Я общаюсь не​
​ мои доводы не​

​ закладывать фундамент дома​​ тоже от длинны​ файлов на самого​smile​ открывать файл (error)​ Path As String,​ (в приложении) :​ коде VBA.​ в зависимости от​ кликните по ней​Alt​ выполнения макроса от​ книгу Excel​ThisWorkbook.Windows.Application.Visible = False​: не работает(​ права на изменение​
​ только (и уже​​ верны? — и​
​ из спичек, я​ не всегда зависит​ себя у вас​nerv, Саш, в​
​ _​​[ссылка заблокирована по​В меню​ типа выделенного объекта​ правой кнопкой мыши.​и, удерживая её,​ 10% до 500%​
​Запускаем макрос VBA в​ UserForm1.Show​Assassinys​
​ файла. Возможно ли?​​ не столько) на​ правда думаешь, что​ не против, но​Однако ты прав,​
​ нет.​ вашем варианте жалуется​Optional ByVal Filter​ решению администрации проекта]​Debug​ (лист, книга, модуль​В появившемся меню кликните​ нажать клавишу​ (да, макрос может​

​ Excel​​eagl69​:​2. Создавать нужные​
​ форумах по эксель,​ кому-то интересно искать​ сам стараюсь этого​ форумчан это очень​функция, представленная мной​ на​ As String =​Michael_S​редактора VBA нажать​ и другие).​

​Insert​​F11​ работать в 5​В этом примере мы​smile​:​Assassinys​ файлы (создавать макросами)​
​ и почему то​​ все твои сообщения​ не делать​ беспокоит​
​ возвращает список файлов​Mask​ «*») As Collection​: Все, что об​Quick Watch​Окно​и в раскрывшемся​
​). После этого откроется​ раз быстрее, если​ будем использовать VBA​inv.DS​, работает.​ и сразу при​
​ везде (кроме известных​​ выискивая в них​Цитата​Мы все тут​
​ заданной папки. Понятия​и что он​Static List As​ этом файле известно​.​Immediate​ меню выберите​ окно редактора Visual​ манипуляции над ячейками​ макрос, который удаляет​,​Код надо поместить​
​ этом ставить «только​ мне форумов по​ «перлы» а ля​(Serge_007)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Кстати и скорость​ хотим размер покороче​ «самого себя» здесь​ должен делать мне​ New Collection​ — он находится​smile

​Нажать​​можно отобразить в​Userform​ Basic, как показано​ происходят без лишних​ переносы строк из​
​inv.DS​ куда и сказано​ для чтения», при​
​ эксель) правильность одна.​ nerv? Хочешь быть​ тоже от длинны​ и даже соревнуемся​ нет, т.к. функции​ не понятно. У​biggrin

​Static FSO As​​ в той же​Add​ редакторе Visual Basic​,​ на картинке ниже.​ остановок).​ ячеек текущего листа​, неа ефекто тот​ -​ этом за макросом​ Я никому не​ нарциссом — ради​ не всегда зависит​ в этом постоянно​​ все равно, откуда​​ меня задача -​ Object​biggrin

​ папке, где и​​.​ через меню​smile
​Module​​ Имейте ввиду, что​Сохраняем рабочую книгу, как​ Excel.​ же….​в модуль «Эта книга»​
​ должно оставаться право​ навязывал, даже не​ Бога. Растеряешь друзей.​
​зависит от алгоритма,​​ в специально созданном​ она вызывается. Думаю,​ открыть файл.​
​Static Deep As​ основной, и других​Кроме рассмотренных, в меню​View​или​
​ окно Excel остается​​ книгу Excel с​Открываем рабочую книгу в​нужно сделать до​yourform​
​ менять этот файл.​ обсуждал этот вопрос​RAN​ а не от​ для этого разделе​ несложно удалить из​За помощь спасибо.​ Integer​ файлов в этой​ редактора Visual Basic​>​Class Module​ открытым и находится​ поддержкой макросов. Для​ Excel.​ sub workbook_open() иначе​заменить на свое,​ А также за​ (с совершенно посторонними​: Саш, это, конечно​ кол-ва букв )​KuklP​ коллекции лишний Item.​
​зы. кстати, везде,​Dim SubFolder As​ папке нет. И​ в Excel существует​Immediate Window​.​smile
​ позади окна редактора.​​ этого нажмите​Нажатием​ ефект полюбому останется….​
​ например, у меня​ главным юзером -​ людьми), но исходя​
​ правильно​​Цитата​: Еще как измеряется.​KuklP​ где возможно, я​ Object​ что он -​
​ ещё множество параметров​smile

​или нажатием комбинации​​Для каждого из описанных​В процессе работы в​
​Ctrl+S​Alt+F11​ потому что сначала​Userform1​ то бишь мной​ из их сообщений,​

​но вся проблема​​(Serge_007)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Мы все тут​ Можно написать на​sad

​: Саша, ты из​​ тоже предпочитаю однострочный​Dim Folder As​smile​ эксель. Ни имя​ и команд, используемых​ клавиш​ выше объектов предусмотрено​ редакторе Visual Basic​и в окне​
​вызываем окно редактора​​ открываеться ексель а​Aleksey1404​
​ ) Как это​smile​ очевидно, что правильность​ в том -​ хотим размер покороче​ 10 страниц «правильного»​ пушки по воробьям​ If.​
​ Object​​ и расширение файла,​ при создании, выполнении​Ctrl+G​ специальное окно, в​ в Excel могут​ с предупреждением​
​ Visual Basic​ потом он выполняет​: Да заработало ,​

​ сделать?​​ одна. Это видно​ что она одна,​ и даже соревнуемся​ кода, а можно​ стреляешь. Миша пишет:​Vitalts​Dim File As​ а также имя​ и отладке кода​
​. Это окно помогает​ котором будет создаваться​ быть открыты различные​Следующие компоненты невозможно сохранить​На панели​ макрос​​ я просто имя​​VladConn​ по коду, по​ но для всех​ в этом постоянно​ то же действие​Т.е. первый же​:​ Object​ и расположение папки​ VBA.​ при отладке кода.​

​ и храниться новый​​ окна. Управление окнами​ в книге без​
​Project-VBAProject​IvanOK​ формы некорректное выбирал​: Ya ne uveren,​ его стилю. Т.е.​
​ разная!​ в специально созданном​ описать одной строкой.​
​ файл с несовпадающим​Michael_S​If FSO Is​ не известны.​Урок подготовлен для Вас​ Оно выполняет роль​
​ код VBA. Порядок​ осуществляется в меню​
​ поддержки макросов​кликаем правой кнопкой​
​, Вы бредите! Все​

​Апострофф​​ chto eto to,​ все хорошие прогеры​Ты откатись чуть​ для этого разделе​ Что легче можно​ именем — нужный.​
​, что значит не​
​ Nothing Then​Возможно? Если возможно​
​ командой сайта office-guru.ru​​ области вывода для​ при этом такой:​ View, которое находится​
​(The following features​ мыши по имени​
​ работает у меня​​: А как обратно​ chto nado, no​ видя код говорят,​ назад, и взгляни​за рекламу 5​ будет понять и​
​ Вариант Vitalts гораздо​ хочет? Без кода​Set FSO =​ — как?​Источник: http://www.excelfunctions.net/Visual-Basic-Editor.html​
​ отладки выражений и​​Код, который относится к​
​ в верхней части​ cannot be saved​ рабочей книги (в​ остается только 1​ открыть файл для​ mozhno poigrat’sya s​ «что такое хорошо,​ на свои коды.​
​Michael_S​​ отредактировать? Ведро картошки​ лучше подходит для​ я не могу​ CreateObject(«Scripting.FileSystemObject»)​nerv​
​Перевел: Антон Андронов​ позволяет вычислять отдельные​ рабочей книге, должен​smile​ окна редактора VBA.​ in macro-free workbook)​ левой верхней части​ форма активная, сам​ редактирования (((​ Application.​ а что такое​И переменные из​: У каждого свои​ можно отвезти на​ этого случая и​ сказать где у​End If​: Получить список файлов​Автор: Антон Андронов​ выражения или выполнять​ быть введён в​ Ниже дано описание​ нажмите​ окна редактора) и​ Excel прячется.​Aleksey1404​AutomationSecurity​ плохо». Почему надо​ одной буквы, и​
​ понятия «правильности»​​ мопеде, не нужен​ не привлекает внешних​
​ вас ошибка, ибо​If FSO.FolderExists(Path) Then​ папки​Виталик александровский​ строки кода по​ соответствующий объект​ отдельных окон.​smile
​Нет​​ в контекстном меню​inv.DS​: Разве не очевидно?​
​100g​ делать так, а​ Iif сплошь и​Саш, мы уже​ для этого БелАз.​ библиотек. Я уж​
​ код замечательно работает.​Set Folder =​Vitalts​: Alt плюс F11​ одной.​ЭтаКнига​Окно​(No).​ выбираем​

excelworld.ru

Открыть файл Excel-я макросом и взять его на редактирование

​, ето вы просто​​ Application.Visible = True​
​: Создаешь новую книгу,​ не иначе.​ рядом, и еще​ как-то говорили на​ Но если тебе​ не говорю о​ Ни один год​ FSO.GetFolder(Path)​: Все названия Excel​Gkp090​Например, введите выражение «​(ThisWorkbook);​Project​Откроется диалоговое окно​Insert​ не замечаете не​Апострофф​ сохраняешь и ставишь​Цитата​ куча всего, что​ эту тему; твои​ так​
​ размере кода.​ пользуюсь подобными методами.​For Each File​ файлов в папке​
​: VBA​?j​Код, который относится к​открывается в левой​Сохранение документа​>​ мощном ПК, а​: Может есть какое-то​ пароль на запись,​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Хочешь быть нарциссом​ ты сейчас критикуешь!​ доводы отчасти верны,​нравитЬся​

​nerv​​Попробуйте вывести название​ In Folder.Files​ активной книги, исключая​в настройках выставить​» и нажмите​​ рабочему листу, должен​

​ части редактора VBA​​(Save as). В​Module​ я говорю делоВ​ сочетание клавиш, позволяющее​
​ закрываешь:​ — ради Бога​Мне Вася уронил​
​ но не для​

​, я тоже не​​: Я ни в​ файла, который пытаетесь​If File.Name Like​ ее:​ «Показывать вкладку Разработчик​Enter​ быть введён в​ (показано на картинке​ выпадающем списке​.​ продолжение темы:​
​ открыть файл без​Workbooks.Add ActiveWorkbook.SaveAs Filename:=»C:Text1.xls»,​Хоть Жераром Депардье​ молоток на голову!​ всех случаев.​ против​ кого не стреляю,​ открыть, возможно, лимит​
​ Filter Then​200?’200px’:»+(this.scrollHeight+5)+’px’);»>​ на ленте»​– в результате​ соответствующий объект​ выше). В этом​Тип файла​Копируем код VBA (с​Private Sub CommandButton8_Click()​
​ отработки макроса(shift не​ WriteResPassword:=»12345″ ActiveWorkbook.CloseКогда надо​ или психом в​

CyberForum.ru

Как открыть форму, а Excel скрыть или вовсе не открывать

​И что вы​​Michael_S​nerv​ я животных люблю​ исчерпан, и идет​List.Add File​Dim fn As​Александр к​ будет выведено текущее​Лист​ окне для каждой​

​(Save as type)​​ веб-страницы или из​
​ Application.Visible = False​ помогает), т.к. у​

​ редактировать открываешь так:​​ белой рубашке с​

​ ему сказали?​​: То же не​​: чуть меньше неверно,​​Я привел написанный​
​ попытка открыть файл​End If​ String​​: На вкладке Разработчик​
​ значение переменной​​(Sheet);​ открытой рабочей книги​​ выбираем​

​ другого источника) и​​ End Sub Private​ меня отображается форма,​Workbooks.Open Filename:=»C:Text1.xls», WriteResPassword:=»12345″​

​ пеной у рта​​Ты…, Вася…, неправ!!!!!!!!!​ работает​ чем полностью​

​ мной ранее код​​ с пустым названием.​Next​

​With ActiveWorkbook​​ щелкните Visual Basic.​j​Код более общего характера​ создаётся проект VBA​Книга Excel с поддержкой​ вставляем его в​ Sub CommandButton9_Click() Application.Visible​ но я не​R1001​ (в ваших глазах).​nerv​nerv​

​Цитата​​ (под свои нужды)​​ Не совершенство кода,​​For Each SubFolder​fn = Dir(.Path​Если Вкладка Разработчик​
​.​ должен быть введён​
​ (VBA Project). Проект​ макросов​​ правую область редактора​​ = True End​
​ могу добавить код​​: Я сталкивался с​​ Моя точка зрения​: об единственной опечатке​​: Захотелось кнопку «Ok»​​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Можно написать на​

​Цитата​​ написанного на скорую​ In Folder.SubFolders​ & «*.xls*»)​ не отображена:​Чтобы открыть окно​

​ в​​ VBA – это​(Excel macro-enabled workbook)​ VBA (окно​ SubЛист скрывается а​ по причине отсутствия​ проблемой, когда открываешь​ останется при мне​ я предупредил сразу.​ нажать​ 10 страниц «правильного»​
​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Т.е. первый же​ руку :(​Deep = Deep​Do Until fn​

​Нажмите кнопку Microsoft​​Locals​​Module​​ набор всех объектов​
​ и нажимаем кнопку​Module1​

​ вот при открытии​​ окна екселя… код​​ программно файл XLS​​Цитата​
​ Это раз. Два,​​Там же написано​ кода, а можно​
​ файл с несовпадающим​Судя по скрину,​ + 1​ = «»​ Office, а затем​, нажмите​;​

​ и модулей VBA,​​Сохранить​).​ появляется еще какой​ не большой написан,​ (ну типа test.xls​​(RAN)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Ты откатись чуть​​ кто-то не знает,​ «Переменная не определена»​ то же действие​ именем — нужный​ так и есть.​
​GetFileList SubFolder.Path, Mask​If fn <>​ — Параметры Excel.​Locals Window​Код для нового объекта​ привязанных к текущей​(Save).​Подсказка:​ то лист пустой​

CyberForum.ru

​ просто стало интересно)​

Written by Puneet for Excel 2007, Excel 2010, Excel 2013, Excel 2016, Excel 2019, Excel for Mac

KEY POINTS

  • Visual Basic Editor is a code editor for VBA.
  • It’s a separate application but you can only use it with Excel.
  • You need to have the developer tab on the ribbon to access it.
  • You can also use the keyboard shortcut (Alt + F11).
  • It also stores the macros that you recode with the macro recorder.
  • It has multiple tools to help you to write and manage all the codes.

The world of VBA starts with the Visual Basic Editor (VBE).

It’s the place where you write and manage all the macro codes and if you ask me about VBE, I’d say if you are serious about learning VBA you need to understand all the components of VBE.

That’s why it’s part of our VBA tutorial and in this guide, we have covered every single aspect of Visual Basic Editor to make you understand its functionality.

So, let’s get started.

I will be using different words (VBA editor, VB editor, or VBE) in this guide for referring to the Visual Basic Editor, so don’t be confused with it.

What is the Visual Basic Editor?

Visual Basic Editor is an application (a separate one) in which you can write and save all the VBA codes. In simple words, it’s a code editor for Excel in which you can write all the macros and store them. Even though it is a separate application (VB Editor) you can only use it with Excel.

Yes, that’s right. You can’t run VBE separately; there must be an Excel workbook open for using VBE.

Visual Basic Editor is the only way to write a VBA code in Excel. In fact, all Microsoft applications that host VBA use the Visual Basic Editor for script writing (writing code).

Below is the VBE:

Microsoft Windows

A screenshot of a social media post

Description automatically generated

Mac

VBA is one of the ADVANCED EXCEL SKILLS and to master the VBA; you need to learn all the aspects of Visual Basic Editor.

Open the Visual Basic Editor

From the developer tab

To open the visual basic editor, you need to have the developer tab on the ribbon and to activate the developer tab (steps to add).

A screenshot of a cell phone

Description automatically generated

Now on the developer tab, in the code group, there is a button called “Visual Basic” and when you click on this button it opens the VB editor.

A picture containing clock

Description automatically generated

Shortcut Key (Window)

You can also use the keyboard shortcut key Alt + F11 to open the VBE in windows and Opt + F11 or Fn + Opt + F11 for MAC.

Even if you don’t have the developer tab on the ribbon, this shortcut key will still work and open the editor.

Edit a Macro from the List

If you want to open the VBA editor to edit a specific macro, then you can open the macros list from the developer tab.

A screenshot of a cell phone

Description automatically generated

And click on the edit button to open the VB editor to edit that specific macro.

A screenshot of a cell phone

Description automatically generated

On Quick Access Toolbar

You can also add a button on the quick access toolbar to open the VBA editor. For this, you need to click on the drop-down on the quick access toolbar and open more commands.

A screenshot of a cell phone

Description automatically generated

And then select the developer tab from “Choose Commands From” and then add the visual basic editor to the quick access toolbar by clicking on the add button.

A screenshot of a cell phone

Description automatically generated

Now you can open the visual basic editor from the button that you have on the QAT.

A picture containing clock

Description automatically generated

From the Worksheet Tab

You can also open the VBA editor by right-clicking on the worksheet tab and clicking on the view code. It will instantly take you to the code window of that worksheet.

A screenshot of a cell phone screen with text

Description automatically generated

Components of Visual Basic Editor

When you open the VBA editor first time it looks like an old application and to understand how it works you need to go component by component.

The user interface is the same (almost) for all the Excel versions in the last more than 15 years, so no matter which Excel version you are using, you can learn about Visual Basic Editor from this guide. Yes, VBE has different components which can help you in different ways, so let’s explore them one by one.

  1. Menu Bar
  2. Tool Bar
  3. Project Window
  4. Properties Window
  5. Code Window
  6. Immediate Window
  7. Watch Window
  8. Object Browser
  9. Find and Replace
  10. Locals Window

Just like any other application VBA editor has a menu bar where you can find all the options that are available to the user.

Now in the menu bar, each tab is a category of options that are available to use. Let’s suppose, in the edit menu, you can see all the options from cut-copy-paste, find and replace, and adding indent and outdent. 

A screenshot of a computer

Description automatically generated

Along with all the options (most of them), you can find the shortcut keys to use those options.

2. Tool Bar

Just below the menu bar, you have the toolbar which is a collection of some of the options that a normal user needs to use more frequently. When you open the visual basic editor first time you will only have the standard toolbar, just like the image below.

But there are total four toolbars that you can add and use.

  1. Debug
  2. Edit
  3. Standard
  4. User Form

If you go to the view tab in the menu bar you have the option to add or remove these toolbars.

A screenshot of a cell phone

Description automatically generated

And you can also add or remove buttons from the toolbar if you want.

A screenshot of a cell phone

Description automatically generated

You can also move a toolbar just by dragging and dropping from the small dots on the right side.

3. Project Window/ Project Explorer

The project window is the place where you can see all the ongoing projects. Whenever you open a file and then open the visual basic editor you can see the hierarchy of that file in the project window.

A screenshot of a cell phone

Description automatically generated

Every project further has a collection of objects:

  • Worksheet: Each worksheet in a workbook lists as an object.
  • The Workbook: It represents the workbook itself as an object.
  • Module: It’s the place where you write code or recorded macros stores.
  • Chart Sheet: Chart sheet in the workbook will also be listed there.

When you open the VB editor, you’ll find the project window there by default. But if it’s not there somehow you can add it from the View (Menu Bar) or you can use the shortcut key Control + R.

Each object that is listed on the project window has its own code window which you can open by double click on it or you can right-click and select the view code option.

A screenshot of a cell phone

Description automatically generated

The project window is the best way to navigate through all the ongoing projects and when you start working with the editor you will get to know more about it.

4. Properties Window

As the name suggests the properties window gives you access to the properties of the selected object. Each object, for example, a worksheet has its own properties that you can see and make changes in it.

A screenshot of a cell phone

Description automatically generated

For each property, there is a drop-down on the right side from where you can change or edit that property.

A screenshot of a cell phone

Description automatically generated

Quick Tip: You can change the name of a project from the properties window.

A screenshot of a cell phone

Description automatically generated

And, if the properties window is not there by default you can activate it from the view (menu bar), or you can also use the shortcut key F4.

A screenshot of a cell phone

Description automatically generated

5. Code Window

The code window is the place where you write codes and do most of your work (editing, writing, and testing). In simple words, the code window is the place where you do all the programming.

A screenshot of a social media post

Description automatically generated

When you first see it, it looks like a simple text editor, but it has Intellisense that can help you while programming.

There is no way I have found to add line number in the code window as other code editors have but still, VB editor indicates you the line number of the code.

Note

There’s no way I have found to add line number in the code window as other code editors have but still, VB editor indicates you the line number of the code.

6. Immediate Window

Immediate Window is the place where you can debug your code. You can type a line of code and test how it works. Let’s say if you want to test the following code:

Range("A1").Value = 9999

All you need to do is enter type a question mark and then paste the code there and HIT enter. It will immediately show the result of the code.

A screenshot of a cell phone

Description automatically generated

The other way is to add Debug.Print before the code and get its result value in the immediate window.

Sub Macro1()
Debug.Print Range("A1").Value = "Yes"
End Sub

By default, the immediate window won’t be there when you open the visual basic editor, so you need to activate it from the view tab in the menu bar. You can also use the shortcut key Control + G.

7. Watch Window

Just like Excel Watch Window, the visual basic editor also has a watch window where you can add expressions to track them. You simply need to select the expression and then right-click and go to add a watch.

A screenshot of a cell phone

Description automatically generated

In the below example, I have added the Selection.Value to the add watch.

A screenshot of a cell phone

Description automatically generated

Now, to activate the watch window, go to the view menu and click on the watch window option.

A screenshot of a cell phone

Description automatically generated

And here you have the watch window tracking the added expression.

A screenshot of a social media post

Description automatically generated

8. Object Browser

VBA has its own object browser which can help you to work with all the objects by finding all the properties and which you can use.

A screenshot of a cell phone

Description automatically generated

Imagine if you want to use the range object, the object browser will tell you about all the properties and method that comes with it. Look at the below example.

A screenshot of a cell phone

Description automatically generated

To open the object browser, use the shortcut key F2 or you can also go to the view tab and click on the object browser to open it.

9. Find and Replace

Just like the find and replace in Excel, the VBA editor has its own find and replace option that you can use to find and replace values from procedures. To open the FIND option, you can use the shortcut key Control + F, and to open the replace you can use the shortcut key Control + H.

A screenshot of a cell phone

Description automatically generated

Otherwise, you can open both options from the edit menu.

A screenshot of a cell phone

Description automatically generated

The find and replace option in VBE gives you different search patterns, like, if you want to find and replace something from the current procedure, from the current module, or from the current project.

You can also use the CASE SENSITIVE search and decide the direction of the search as well.

10. Locals Window

You can use the Locals window in VBE to displays all declared variables in the current procedure and their present values.

Using VB Editor to Write a Code

At this point, you know all the major components of the VBA editor, so now let’s learn how to add code in it.

Module Code Window Vs Object Code Window

There are two different types of code windows and both look just the same but there is a difference that you need to know.

  1. Module Code Window: Code in the normal module can be executed manually or you can also call it from a separate procedure.
  2. Object Code Window: Code in the object code window can be executed by using an event. Let’s suppose you want to run code when you double click on a cell, in that case, you need to use the double click event and you need to add code to that worksheet.

2. Module Code Window

You will be writing most of the VBA code in a module. To add code in a module you need to use the SUB procedure or the FUNCTION procedure.

  • Sub procedure
  • Function procedure

The difference between a sub and a function procedure is sub procedure can’t return a value, on the other hand, a function procedure can return a value.

When you record a macro that code goes straight into a module that VBA inserts automatically when you use the macro recorder.

Insert a Module

When you need to write code, you have to insert a module and for this, you simply need to go to the project window and right-click on the project name, and from that menu go to insert and select module.

A screenshot of a cell phone

Description automatically generated

Remove a Module

You can also remove a module if it doesn’t require anymore so you just simply need to right-click on the module and select remove.

A screenshot of a cell phone

Description automatically generated

And when you click on remove, it asks you if you want to back up that module before removing it. There is also an option where you can export a module to save it as a file in your system.

3. Object Code Window

Open the code window for the object you simply need to double click on it and in its the code window, there is a dropdown from where you can select the event that you want to use to execute the code.

A screenshot of a social media post

Description automatically generated

Imagine if you want to write the code and want to execute on the double click then you need to select “BeforeDoubleClick” from the dropdown.

Understanding Design Mode, Run Mode, and Debug Mode

You can use the visual basic editor in three different modes depending on the face of programming, writing the code, locating an error, and fixing an error.

  • Design Mode: Normally, when you are working in VB editor on a code you are in the design mode. Even then you just writing the code instead of designing a user form or a form you are in the design mode, like typing a code. This is also called design time.
  • Run Mode: When you run a code to test a code that is how it works you are in the run mode. The best example to define this mode is when you execute a code using the Run button from the toolbar. This is also called runtime.
  • Break Mode: When a code is running and in between the execution is suspended, at that time you are in break mode. In this mode, you can run a code step by step. This is also called debugging.

Tips to work with VB editor like a PRO

Just like any other programming language in VBA you can also use comments to define how that code works. Using comments is a good habit and it can help you in so many ways.

  • Track Changes
  • Contact Details of the Programmer
  • How to Troubleshoot the Code
  • And much more

To add a comment, you need to type an apostrophe and then the line of code.

Related Tip: VBA Comment Block

Quick Info

Now, look at the below example where I am adding add a VBA function (VBA LEFT Function), and the moment I type the name of the function, it shows me a tooltip for all the arguments which I need to define.

A screenshot of a cell phone

Description automatically generated

You can also use the shortcut key Control + I or use the quick info option from the EDIT menu.

A screen shot of a smart phone

Description automatically generated

Auto List Members

Each object in VBA comes with some properties and methods and when you insert an object or a command in the code window and then you enter (.) it shows you the complete list of properties and methods which come with that object.

A screenshot of a cell phone

Description automatically generated

In the above example, when I added a (.) after the borders property of the range, it showed me all the available properties that are available to access.

List Constants

While defining expressions for a property or a method you can use the list of constants available. In the below example, while using the Border Around method it showed me all the constants which are available for the weight argument.

A screenshot of a cell phone

Description automatically generated

You can use the shortcut key Control + Shift + J to get the list of constants or you can also go to the edit menu and use the option from there.

A screenshot of a cell phone

Description automatically generated

Activate Option Explicit

While writing VBA codes you will need to use variables and one of the most important things while using variables is to declare their data type. And there’s a chance that you could forget to declare it.

But when you use the option explicit statement, then you have to declare the data type for every single variable which you are using, and if you fail to do so VBA will show an error message. It’s like forcing yourself to declare every single variable with its data type. For this, you can go to the tools menu and open the options.

And from the options, tick mark “Require Variable Declaration” and click OK.

A screenshot of a cell phone

Description automatically generated

Now every module will have an Option Explicit statement at the beginning, and you have to declare every single variable.

A screenshot of a cell phone

Description automatically generated

Change the Code Window View

When you can write multiple codes in a single code window and VBA separate them with a divider, but if you want to have a more focused view, you can change the view of the code window. Below I have the codes in a single module.

A screenshot of a cell phone

Description automatically generated

But I can change this view from the view buttons from the bottom left of the window.

A screenshot of a cell phone

Description automatically generated

Now I have only active code visible.

Run a Code Step by Step

When you write a VBA code there could be a chance that that code has a bug or an error that can come while executing it. In that case, the best way is to execute that code step by step and validate each line of code.

A screenshot of a cell phone

Description automatically generated

For this, you can use shortcut key F8 to execute a code line by line or use step into option from the debug menu.

A screenshot of a cell phone

Description automatically generated

And there is also a button on the debug toolbar that you can use.

A screenshot of a cell phone

Description automatically generated

Code Indenting

When you write lengthy and complex codes then it’s important to structure them in the right way so that you can understand them later. For this, there’s one thing which comes handy, INDENTING. Indenting is basically structuring the code using tabs, below is an example.

A screenshot of a cell phone

Description automatically generated

To add indenting in a line you can use the TAB key from the keyboard, or you can also use the indent/outdent buttons from the toolbar.

A screenshot of a cell phone

Description automatically generated

Get Code from a Text File

The visual basic editor allows you to import VBA codes from a text file without copy-pasting. Once you insert a module you can go to the insert menu and select the file option from there.

A screenshot of a cell phone

Description automatically generated

It opens the dialog box where you can locate the text file and import all the codes from it to the current module.

R1C1 Reference Style

If you ever worked with the R1C1 reference style, then I’m sure you can agree on this point that way easier to write codes with it.

R1C1 Reference Style

Line Break

Even though you can adjust the width of the code window and make it wide but there could be a situation when you will be dealing with long lines of code that makes it hard to read.

The best way to deal with this problem is to add a line break. Basically, a line break is something when you break a line into two lines using the line break character.

Use a SPACE & UNDERSCORE and hit enter to add a line break.

A picture containing room, orange, holding, black

Description automatically generated

Formatting

When it comes to user interface visual basic editor is not that good looking. But there are few formatting options that you can use to customize it or change its look the way you want.

From the Tools Menu Options Editor Format, you can access the formatting option where you can change the font style size or background color as well

A screenshot of a social media post

Description automatically generated

Check out this video on customizing the VBA editor for a dark theme.

Personal Macro Workbook

There could be some macros that you need to access within all the workbooks that you use.

In that case, you can use the Personal Macro Workbook that can help you to store all the important codes in one place and you can access them from all the workbooks.

A screenshot of a cell phone

Description automatically generated

Using Bookmarks

The visual basic editor allows you to add bookmarks to a line from Right Click Toggle Bookmark.

A screenshot of a cell phone

Description automatically generated

And then you can also navigate between bookmarks from the option from the edit menu.

A screenshot of a cell phone

Description automatically generated

Syntax Checking

When you write codes in the code window VBA check for the syntax error and notify you when you make a syntax error. This option is activated by default, but you can also turn it off if you don’t want VBA to notify you every time you make an error.

Tools Menu ➤ Options ➤ Editor Tab ➤ Auto Syntax Check.

A screenshot of a cell phone

Description automatically generated

But I would recommend you not to deactivate it because it can help you to identify all the syntax errors that you make while writing codes.

List of Macros

If you have a lot of macros in a module, there is an option that you can use to see all the macros (Tools ➤ Macro).

A screenshot of a cell phone

Description automatically generated

There’s one big benefit of using this list option is that you can run a macro, delete it, and edit it without navigating to that procedure.

Locking a Project with a Password

Visual Basic Editor also gives you an option to lock a module with a password. So, if you don’t want the users to know the code and don’t want them to make a change in the code, you can use this option.

A screenshot of a cell phone

Description automatically generated

Tools Menu ➤ VBAProject Properties ➤ Protection Tab

A screenshot of a cell phone

Description automatically generated

Important Shortcut Keys

  • Shift + F7: Object browser.
  • F5: Run macro.
  • Tab: Add an indent.
  • Alt + Q: Close.
  • F8: Step into.
  • Control + H: Find and replace.
  • Control + G: Immediate Window.
  • Control + R: Project Explorer.
  • F4: Properties window.

Learn some AMAZING Keyboard Shortcuts: Excel Keyboard Shortcuts Cheat Sheet

Alternative to Visual Basic Editor

Well, I have tried quite a few other editors to write a macro but the problem which I have found is that without the Intellisense it’s really hard to use anything other than the visual basic editor itself.

VBA editor works along with Excel, you can test your codes instantly and you can save them into the workbook. But are a few names to try.

Visual Studio Code | Ultra Edit

Points to Remember

  • You can maximize or minimize the code window.
  • You can change a project’s name anytime.
  • The project window is the best way to navigate through the editor.
  • It will make a line red if there’s an error in it while writing the code.
  • You can also add a bookmark to a line of code from the Right-Click Menu Toggle Bookmark.
  • You cannot use the visual basic editor without opening an Excel workbook.

More on VBA

  • VBA Functions
  • VBA to Add a New Sheet
  • VBA Code to Activate a Worksheet
  • VBA IF Then Statement
  • VBA User Defined Function
  • VBA Message Box
  • VBA to Extract Hyperlink
  • Macro to Highlight Duplicate Values
  • VBA to Create a Pivot Table

[icon name=”bell” class=”” unprefixed_class=””] VBA is one of the Advanced Excel Skills

Should I need to install the Visual Basic Editor?

No. You don’t need to install the visual basic editor. It comes pre-installed with the Microsoft Office applications.

What if I don’t have the Developer Tab on the Ribbon?

If you don’t have the developer tab on the Excel ribbon, you can activate it from the Excel ribbon.

Is there an alternative to the Visual Basic Editor?

Not really. The IntelliSense that you have in the VBE makes it perfect to use to write VBA codes.

Понравилась статья? Поделить с друзьями:
  • Visual basic 2010 and excel
  • Vista and microsoft word
  • Visiting interesting places word
  • Visio конвертировать в excel
  • Visio drawing in word