Excel adding to a macro

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 More…Less

If you have tasks in Microsoft Excel that you do repeatedly, you can record a macro to automate those tasks. A macro is an action or a set of actions that you can run as many times as you want. When you create a macro, you are recording your mouse clicks and keystrokes. After you create a macro, you can edit it to make minor changes to the way it works.

Suppose that every month, you create a report for your accounting manager. You want to format the names of the customers with overdue accounts in red, and also apply bold formatting. You can create and then run a macro that quickly applies these formatting changes to the cells you select.

How?

Icon image

Before you record a macro    

Macros and VBA tools can be found on the Developer tab, which is hidden by default, so the first step is to enable it. For more information, see Show the Developer tab.

Developer tab on the ribbon

Icon image

Record a macro    

  1. In the Code group on the Developer tab, click Record Macro.

  2. Optionally, enter a name for the macro in the Macro name box, enter a shortcut key in the Shortcut key box, and a description in the Description box, and then click OK to start recording.

    Record Macro

  3. Perform the actions you want to automate, such as entering boilerplate text or filling down a column of data.

  4. On the Developer tab, click Stop Recording.

    Stop Recording

Icon image

Take a closer look at the macro    

You can learn a little about the Visual Basic programming language by editing a macro.

To edit a macro, in the Code group on the Developer tab, click Macros, select the name of the macro, and click Edit. This starts the Visual Basic Editor.

See how the actions that you recorded appear as code. Some of the code will probably be clear to you, and some of it may be a little mysterious.

Experiment with the code, close the Visual Basic Editor, and run your macro again. This time, see if anything different happens!

Next steps

  • To learn more about creating macros, see Create or delete a macro.

  • To learn about how to run a macro, see Run a macro.

How?

Icon image

Before you record a macro    

Make sure the Developer tab is visible on the ribbon. By default, the Developer tab is not visible, so do the following:

  1. Go to Excel > Preferences… > Ribbon & Toolbar.

  2. In the Customize the Ribbon category, in the Main Tabs list, select the Developer check box, and then click Save.

Icon image

Record a macro    

  1. On the Developer tab, click Record Macro.

  2. Optionally, enter a name for the macro in the Macro name box, enter a shortcut key in the Shortcut key box, and a description in the Description box, and then click OK to start recording.

  3. Perform the actions you want to automate, such as entering boilerplate text or filling down a column of data.

  4. On the Developer tab, in the Code group, click Stop Recording.

Icon image

Take a closer look at the macro    

You can learn a little about the Visual Basic programming language by editing a macro.

To edit a macro, in the Developer tab, click Macros, select the name of the macro, and click Edit. This starts the Visual Basic Editor.

See how the actions that you recorded appear as code. Some of the code will probably be clear to you, and some of it may be a little mysterious.

Experiment with the code, close the Visual Basic Editor, and run your macro again. This time, see if anything different happens!

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.


Download Article


Download Article

This wikiHow teaches you how to enable, create, run, and save macros in Microsoft Excel. Macros are miniature programs which allow you to perform complex tasks, such as calculating formulas or creating charts, within Excel. Macros can save significant amounts of time when applied to repetitive tasks, and thanks to Excel’s «Record Macro» feature, you don’t have to know anything about programming in order to create a macro.

Things You Should Know

  • Macros make it easy to automatic tasks in Microsoft Excel.
  • To create macros yourself, you’ll need to enable macros in the Developer menu of Excel.
  • Saving a macro-enabled spreadsheet is a little different than saving a spreadsheet without macros.
  1. Image titled Use Macros in Excel Step 1

    1

    Open Excel. Double-click the Excel app icon, which resembles a white «X» on a green box, then click Blank workbook.

    • If you have a specific file which you want to open in Excel, double-click that file to open it instead.
  2. Image titled Use Macros in Excel Step 2

    2

    Click File. It’s in the upper-left side of the Excel window.

    • On a Mac, click Excel in the upper-left corner of the screen to prompt a drop-down menu.

    Advertisement

  3. Image titled Use Macros in Excel Step 3

    3

    Click Options. You’ll find this on the left side of the Excel window.

    • On a Mac, you’ll click Preferences… in the drop-down menu.
  4. Image titled Use Macros in Excel Step 4

    4

    Click Customize Ribbon. It’s on the left side of the Excel Options window.[1]

    • On a Mac, click instead Ribbon & Toolbar in the Preferences window.
  5. Image titled Use Macros in Excel Step 5

    5

    Check the «Developer» box. This box is near the bottom of the «Main Tabs» list of options.

  6. Image titled Use Macros in Excel Step 6

    6

    Click OK. It’s at the bottom of the window. You can now use macros in Excel.

    • On a Mac, you’ll click Save here instead.
  7. Advertisement

  1. Image titled Use Macros in Excel Step 7

    1

    Enter any necessary data. If you opened a blank workbook, enter any data which you want to use before proceeding.

    • You can also close Excel and open a specific Excel file by double-clicking it.
  2. Image titled Use Macros in Excel Step 8

    2

    Click the Developer tab. It’s at the top of the Excel window. Doing so opens a toolbar here.

  3. Image titled Use Macros in Excel Step 9

    3

    Click Record Macro. It’s in the toolbar. A pop-up window will appear.

  4. Image titled Use Macros in Excel Step 10

    4

    Enter a name for the macro. In the «Macro name» text box, type in the name for your macro. This will help you identify the macro later.

  5. Image titled Use Macros in Excel Step 11

    5

    Create a shortcut key combination if you like. Press the Shift key along with another letter key (e.g., the E key) to create the keyboard shortcut. You can use this keyboard shortcut to run the macro later.

    • On a Mac, the shortcut key combination will end up being Option+ Command and your key (e.g., Option+ Command+T).
  6. Image titled Use Macros in Excel Step 12

    6

    Click the «Store macro in» drop-down box. It’s in the middle of the window. Doing so prompts a drop-down menu.

  7. Image titled Use Macros in Excel Step 13

    7

    Click This Workbook. This option is in the drop-down menu. Your macro will be stored inside your spreadsheet, making it possible for anyone who has the spreadsheet to access the macro.

  8. Image titled Use Macros in Excel Step 14

    8

    Click OK. It’s at the bottom of the window. Doing this saves your macro settings and begins recording.

  9. Image titled Use Macros in Excel Step 15

    9

    Perform the macro’s steps. Any step you perform between clicking OK and clicking Stop Recording while be added to the macro. For example, if you wanted to create a macro which turns two columns’ worth of data into a chart, you would do the following:

    • Click and drag your mouse across the data to select it.
    • Click Insert
    • Select a chart shape.
    • Click the chart that you want to use.
  10. Image titled Use Macros in Excel Step 16

    10

    Click Stop Recording. It’s in the Developer toolbar. This will save your macro.

  11. Advertisement

  1. 1

    Understand why you have to save the spreadsheet with macros enabled. If you don’t save your spreadsheet as a macro-enabled spreadsheet (XLSM format), the macro won’t be saved as part of the spreadsheet, meaning that other people on different computers won’t be able to use your macro if you send the workbook to them.

  2. Image titled Use Macros in Excel Step 18

    2

    Click File. It’s in the upper-left corner of the Excel window (Windows) or the screen (Mac). Doing so will prompt a drop-down menu.

  3. Image titled Use Macros in Excel Step 19

    3

    Click Save As. This option is on the left side of the window (Windows) or in the drop-down menu (Mac).

  4. Image titled Use Macros in Excel Step 20

    4

    Double-click This PC. It’s in the column of save locations near the left side of the window. A «Save As» window will open.

    • Skip this step on a Mac.
  5. Image titled Use Macros in Excel Step 21

    5

    Enter a name for your Excel file. In the «Name» text box, type in the name for your Excel spreadsheet.

  6. Image titled Use Macros in Excel Step 22

    6

    Change the file format to XLSM. Click the «Save as type» drop-down box, then click Excel Macro-Enabled Workbook in the resulting drop-down menu.[2]

    • On a Mac, you’ll replace the «xlsx» at the end of the file’s name with xlsm.
  7. Image titled Use Macros in Excel Step 23

    7

    Select a save location. Click a folder in which you want to save the Excel file (e.g., Desktop).

    • On a Mac, you must first click the «Where» drop-down box.
  8. Image titled Use Macros in Excel Step 24

    8

    Click Save. It’s at the bottom of the window. Doing so will save your Excel spreadsheet to your selected location, and your macro will be saved along with it.

  9. Advertisement

  1. Image titled Use Macros in Excel Step 25

    1

    Open the macro-enabled spreadsheet. Double-click the spreadsheet that has the macro in it to open the spreadsheet in Excel.

  2. Image titled Use Macros in Excel Step 26

    2

    Click Enable Content. It’s in a yellow bar at the top of the Excel window. This will unlock the spreadsheet and allow you to use the macro.

    • If you don’t see this option, skip this step.
  3. Image titled Use Macros in Excel Step 27

    3

    Click the Developer tab. This option is at the top of the Excel window.

    • You can also just press the key combination you set for the macro. If you do so, the macro will run, and you can skip the rest of this method.
  4. Image titled Use Macros in Excel Step 28

    4

    Click Macros. You’ll find it in the Developer tab’s toolbar. A pop-up window will open.

  5. Image titled Use Macros in Excel Step 29

    5

    Select your macro. Click the name of the macro which you want to run.

  6. Image titled Use Macros in Excel Step 30

    6

    Click Run. It’s on the right side of the window. Your macro will begin running.

  7. 7

    Wait for the macro to finish running. Depending on how large your macro is, this can take several seconds.

  8. Advertisement

Add New Question

  • Question

    Can I use a macro that I create in other spreadsheets and future spreadsheets on the same pc?

    Community Answer

    Yes, you can use a macro that you crate in other spreadsheets and future spreadsheets on the same pc.

  • Question

    How can I write macros that will change a spreadsheet as soon as I create it?

    Community Answer

    You will first need a basic understanding of VBA. There are many tutorials on this.

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

  • Macros are generally useful for automating tasks which you must perform often, such as calculating payroll at the end of the week.

Thanks for submitting a tip for review!

Advertisement

  • Although most macros are benign, some macros can maliciously change or delete information on your computer. Never open a macro from a source which you don’t trust.

Advertisement

About This Article

Article SummaryX

1. Enable Developer options in Excel.
2. Click the Developer tab.
3. Click Record Macro.
4. Enter the macro name and details.
5. Click OK.
6. Perform the macro’s steps.
7. Click Stop Recording.

Did this summary help you?

Thanks to all authors for creating a page that has been read 710,278 times.

Is this article up to date?

#Руководства

  • 23 май 2022

  • 0

Как с помощью макросов автоматизировать рутинные задачи в Excel? Какие команды они выполняют? Как создать макрос новичку? Разбираемся на примере.

Иллюстрация: Meery Mary для Skillbox Media

Ксеня Шестак

Рассказывает просто о сложных вещах из мира бизнеса и управления. До редактуры — пять лет в банке и три — в оценке имущества. Разбирается в Excel, финансах и корпоративной жизни.

Макрос (или макрокоманда) в Excel — алгоритм действий в программе, который объединён в одну команду. С помощью макроса можно выполнить несколько шагов в Excel, нажав на одну кнопку в меню или на сочетание клавиш.

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

Например, если нужно добавить название компании в несколько десятков документов и отформатировать его вид под корпоративный дизайн, можно делать это в каждом документе отдельно, а можно записать ход действий при создании первого документа в макрос — и затем применить его ко всем остальным. Второй вариант будет гораздо проще и быстрее.

В статье разберёмся:

  • как работают макросы и как с их помощью избавиться от рутины в Excel;
  • какие способы создания макросов существуют и как подготовиться к их записи;
  • как записать и запустить макрос начинающим пользователям — на примере со скриншотами.

Общий принцип работы макросов такой:

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

Макросы могут выполнять любые действия, которые в них запишет пользователь. Вот некоторые команды, которые они умеют делать в Excel:

  • Автоматизировать повторяющиеся процедуры.

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

  • Объединять работу нескольких программ Microsoft Office.

    Например, с помощью одного макроса можно создать таблицу в Excel, вставить и сохранить её в документе Word и затем отправить в письме по Outlook.

  • Искать ячейки с данными и переносить их в другие файлы.

    Этот макрос пригодится, когда нужно найти информацию в нескольких объёмных документах. Макрос самостоятельно отыщет её и принесёт в заданный файл за несколько секунд.

  • Форматировать таблицы и заполнять их текстом.

    Например, если нужно привести несколько таблиц к одному виду и дополнить их новыми данными, можно записать макрос при форматировании первой таблицы и потом применить его ко всем остальным.

  • Создавать шаблоны для ввода данных.

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

  • Создавать новые функции Excel.

    Если пользователю понадобятся дополнительные функции, которых ещё нет в Excel, он сможет записать их самостоятельно. Все базовые функции Excel — это тоже макросы.

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

В Excel и других программах Microsoft Office макросы создаются в виде кода на языке программирования VBA (Visual Basic for Applications). Этот язык разработан в Microsoft специально для программ компании — он представляет собой упрощённую версию языка Visual Basic. Но это не значит, что для записи макроса нужно уметь кодить.

Есть два способа создания макроса в Excel:

  • Написать макрос вручную.

    Это способ для продвинутых пользователей. Предполагается, что они откроют окно Visual Basic в Еxcel и самостоятельно напишут последовательность действий для макроса в виде кода.

  • Записать макрос с помощью кнопки меню Excel.

    Способ подойдёт новичкам. В этом варианте Excel запишет программный код вместо пользователя. Нужно нажать кнопку записи и выполнить все действия, которые планируется включить в макрос, и после этого остановить запись — Excel переведёт каждое действие и выдаст алгоритм на языке VBA.

Разберёмся на примере, как создать макрос с помощью второго способа.

Допустим, специальный сервис автосалона выгрузил отчёт по продажам за три месяца первого квартала в формате таблиц Excel. Эти таблицы содержат всю необходимую информацию, но при этом никак не отформатированы: колонки слиплись друг с другом и не видны полностью, шапка таблицы не выделена и сливается с другими строками, часть данных не отображается.

Так выглядят таблицы с продажами автосалона в первоначальном виде
Скриншот: Skillbox Media

Пользоваться таким отчётом неудобно — нужно сделать его наглядным. Запишем макрос при форматировании таблицы с продажами за январь и затем применим его к двум другим таблицам.


Готовимся к записи макроса

Кнопки для работы с макросами в Excel находятся во вкладке «Разработчик». Эта вкладка по умолчанию скрыта, поэтому для начала разблокируем её.

В операционной системе Windows это делается так: переходим во вкладку «Файл» и выбираем пункты «Параметры» → «Настройка ленты». В открывшемся окне в разделе «Основные вкладки» находим пункт «Разработчик», отмечаем его галочкой и нажимаем кнопку «ОК» → в основном меню Excel появляется новая вкладка «Разработчик».

В операционной системе macOS это нужно делать по-другому. В самом верхнем меню нажимаем на вкладку «Excel» и выбираем пункт «Параметры…».

Нажимаем сюда, чтобы вызвать панель с дополнительными параметрами Excel в macOS
Скриншот: Skillbox Media

В появившемся окне нажимаем кнопку «Лента и панель».

Выбираем параметр «Лента и панель»
Скриншот: Skillbox Media

Затем в правой панели «Настроить ленту» ищем пункт «Разработчик» и отмечаем его галочкой. Нажимаем «Сохранить».

Отмечаем пункт «Разработчик» и сохраняем изменения
Скриншот: Skillbox Media

Готово — вкладка «Разработчик» появилась на основной панели Excel.

Теперь можно работать с макросами
Скриншот: Skillbox Media

Чтобы Excel смог сохранить и в дальнейшем использовать макрос, нужно пересохранить документ в формате, который поддерживает макросы. Это делается через команду «Сохранить как» на главной панели. В появившемся меню нужно выбрать формат «Книга Excel с поддержкой макросов».

Перед записью макросов нужно сохранить документ в формате с их поддержкой
Скриншот: Skillbox Media

Перед началом записи макроса важно знать об особенностях его работы:

  • Макрос записывает все действия пользователя.

    После старта записи макрос начнёт регистрировать все клики мышки и все нажатия клавиш. Поэтому перед записью последовательности лучше хорошо отработать её, чтобы не добавлять лишних действий и не удлинять код. Если требуется записать длинную последовательность задач — лучше разбить её на несколько коротких и записать несколько макросов.

  • Работу макроса нельзя отменить.

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

  • Макрос выполняет свой алгоритм только для записанного диапазона таблиц.

    Если при записи макроса пользователь выбирал диапазон таблицы, то и при запуске макроса в другом месте он выполнит свой алгоритм только в рамках этого диапазона. Если добавить новую строку, макрос к ней применяться не будет. Поэтому при записи макроса можно сразу выбирать большее количество строк — как это сделать, показываем ниже.

Для начала записи макроса перейдём на вкладку «Разработчик» и нажмём кнопку «Записать макрос».

Нажимаем сюда, чтобы начать запись макроса
Скриншот: Skillbox Media

Появляется окно для заполнения параметров макроса. Нужно заполнить поля: «Имя макроса», «Сохранить в», «Сочетание клавиш», «Описание».

Так выглядит окно с параметрами макроса
Скриншот: Skillbox Media

«Имя макроса» — здесь нужно придумать и ввести название для макроса. Лучше сделать его логически понятным, чтобы в дальнейшем можно было быстро его найти.

Первым символом в названии обязательно должна быть буква. Другие символы могут быть буквами или цифрами. Важно не использовать пробелы в названии — их можно заменить символом подчёркивания.

«Сохранить в» — здесь нужно выбрать книгу, в которую макрос сохранится после записи.

Если выбрать параметр «Эта книга», макрос будет доступен при работе только в этом файле Excel. Чтобы макрос был доступен всегда, нужно выбрать параметр «Личная книга макросов» — Excel создаст личную книгу макросов и сохранит новый макрос в неё.

«Сочетание клавиш» — здесь к уже выбранным двум клавишам (Ctrl + Shift в системе Windows и Option + Cmd в системе macOS) нужно добавить третью клавишу. Это должна быть строчная или прописная буква, которую ещё не используют в других быстрых командах компьютера или программы Excel.

В дальнейшем при нажатии этих трёх клавиш записанный макрос будет запускаться автоматически.

«Описание» — необязательное поле, но лучше его заполнять. Например, можно ввести туда последовательность действий, которые планируется записать в этом макросе. Так не придётся вспоминать, какие именно команды выполнит этот макрос, если нужно будет запустить его позже. Плюс будет проще ориентироваться среди других макросов.

В нашем случае с форматированием таблицы заполним поля записи макроса следующим образом и нажмём «ОК».

Заполняем поля и жмём «ОК», чтобы начать запись
Скриншот: Skillbox Media

После этого начнётся запись макроса — в нижнем левом углу окна Excel появится значок записи.

Началась запись макроса — теперь в него попадут все клики мышки и нажатия клавиш
Скриншот: Skillbox Media

Пока идёт запись, форматируем таблицу с продажами за январь: меняем ширину всех столбцов, данные во всех ячейках располагаем по центру, выделяем шапку таблицы цветом и жирным шрифтом, рисуем границы.

Важно: в нашем случае у таблиц продаж за январь, февраль и март одинаковое количество столбцов, но разное количество строк. Чтобы в случае со второй и третьей таблицей макрос сработал корректно, при форматировании выделим диапазон так, чтобы в него попали не только строки самой таблицы, но и строки ниже неё. Для этого нужно выделить столбцы в строке с их буквенным обозначением A–G, как на рисунке ниже.

Так макрос будет работать и для таблиц с большим количеством строк
Скриншот: Skillbox Media

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

Так макрос отформатирует только выбранные строки: если в других таблицах строк окажется больше, они останутся в первоначальном виде
Скриншот: Skillbox Media

После всех манипуляций с оформлением таблица примет такой вид:

Так выглядит таблица после форматирования
Скриншот: Skillbox Media

Проверяем, все ли действия с таблицей мы выполнили, и останавливаем запись макроса. Сделать это можно двумя способами:

  • Нажать на кнопку записи в нижнем левом углу.
  • Перейти во вкладку «Разработчик» и нажать кнопку «Остановить запись».

Нажимаем сюда, чтобы остановить запись макроса
Скриншот: Skillbox Media

Готово — мы создали макрос для форматирования таблиц в границах столбцов A–G. Теперь его можно применить к другим таблицам.


Запускаем макрос

Перейдём в лист со второй таблицей «Февраль_2022». В первоначальном виде она такая же нечитаемая, как и первая таблица до форматирования.

Так выглядит таблица до запуска макроса
Скриншот: Skillbox Media

Отформатируем её с помощью записанного макроса. Запустить макрос можно двумя способами:

  • Нажать комбинацию клавиш, которую выбрали при заполнении параметров макроса — в нашем случае Option + Cmd + Ф.
  • Перейти во вкладку «Разработчик» и нажать кнопку «Макросы».

Нажимаем сюда, чтобы вызвать панель для выбора макроса
Скриншот: Skillbox Media

Появляется окно — там выбираем макрос, который нужно запустить. В нашем случае он один — «Форматирование_таблицы». Под ним отображается описание того, какие действия он включает. Нажимаем «Выполнить».

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

Готово — вторая таблица с помощью макроса форматируется так же, как и первая.

За пару секунд с помощью макроса исходная таблица принимает такой вид
Скриншот: Skillbox Media

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

Научитесь: Excel + Google Таблицы с нуля до PRO
Узнать больше

What is MACRO in Excel?

A macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data.  For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.

There are two methods to create the macros – The first is when you can record the macro, where Excel records every step automatically and then repeats it. The second is coding with VBAVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more, which requires good subject knowledge

Before recording a macro, the user has to activate the Developer tab in Excel. The Developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more is a built-in option in Excel to create macros, generate VBA applications, design forms, import or export XML files, etc. Since it is disabled in Excel by default, it has to be enabled before creating and recording the macrosRecording macros is a method whereby excel stores the tasks performed by the user. Every time a macro is run, these exact actions are performed automatically. Macros are created in either the View tab (under the “macros” drop-down) or the Developer tab of Excel.
read more
.

Table of contents
  • What is MACRO in Excel?
    • Enable the Developer tab
    • Examples of Macros in Excel
    • Example #1
    • Example #2
    • Adding the Macro Button
    • How to View the Code of Macros?
    • Creating Macro by Writing VBA Code
    • How to Save the Recorded Macro in Excel?
    • How to Enable “Macro Security Settings”?
    • Frequently Asked Questions (FAQs)
    • Recommended Articles

Let us learn the method to enable the Developer tab in Excel.

Enable the Developer tab

Below are the steps to activate the Developer tab in the Excel toolbar.

  1. Click on “options” in the File menu (as shown in the succeeding image).

    Activate developer Tab step 1

  2. On clicking the “options”, the “Excel options” window will pop up.

    Activate developer Tab step 2

  3. Select “customize ribbon” in the “Excel options” which provides a list of options in a dialog box.
    Under “customize the ribbon”, select “main tabs”. Among the list of checkboxes, select “developer” and click “ok”.

    Activate developer Tab step 3

  4. The worksheet displays the Developer tab, as highlighted in the succeeding image.

    Activate developer Tab step 4

  5. The user can view options like “visual basic”, “macros”, “record macro”, etc. on the ribbon of Developer tab (as displayed in the image below).

    Activate developer Tab step 5

Examples of Macros in Excel

Let us understand how to add macros in excel with the help of the following example.

Example #1

A list of data with different names is available in the table below. Some names have “.” symbol. We want to replace the “.” symbol with “_” by using macros in Excel.

You can download this Macro Excel Template here – Macro Excel Template

Macro Example 1

The steps to add an excel macro are listed as follows:

  • Click the “record macro” option in the Developer tab.

Macro Example 1-1

  • The “record macro” window will pop out. Name the macro “ReplaceDotin the “macro name” box. To assign a keyboard shortcutAn Excel shortcut is a technique of performing a manual task in a quicker way.read more, type “Ctrl+q” in the “shortcut key” box.

Select the option “This Workbook” in the “store macro in” box, which will ensure the macro is stored in the particular workbook.

It is optional to fill the “description” box explaining the task. Finally, click the “ok” button.

Macro Example 1-2

  • The “ReplaceDot” macro will start recording the user actions in Excel. The user will observe the “stop recording” button appearing in the Developer tab.

Macro Example 1-3

  • Let us now start replacing the “.(dot)” in the names with “_(underscore)” by using the “find and replace” option. Enter “.” in the “find” and “ _” in the “replace” option, respectively. Then click the “replace all” button.

Note: Use the shortcut key “Ctrl+H” to use “find and replace” option.

Shortcut key to Find

Macro Example 1-4

  • The “replace all” option replaces all the “.” (dots) with the “_” (underscores). The number of replacements and the resulting output is shown in the succeeding image.

Macro Example 1-5

  • The final output is displayed in the below image.

Macro Example 1-6

  • In the end, click the “stop recording” button on the Developer tab to stop the macro recording.

Example #2

We want to run the same task for a new list of names (displayed in the below image). We will run the macro “ReplaceDot,” created in the Developer ribbon.

Macro Example 1-7

  • Select the “enable macro” option from the Developer ribbon to view the list of macros created in the Macro window. The users can choose and run the macros based on their requirement.

The succeeding image shows the result of macros running on the new list of names.

Macro Example 1-8

Adding the Macro Button

Let us assign a button to the macro instead of choosing the “enableTo enable macros simply means to run or execute a macro in a particular file in order to save the time spent on repetitive actions. To enable macros, select “enable all macros” from the “trust center” of the File tab (in the “options” button).
read more
macroTo enable macros simply means to run or execute a macro in a particular file in order to save the time spent on repetitive actions. To enable macros, select “enable all macros” from the “trust center” of the File tab (in the “options” button).
read more
” option.

There are many groups like Add-ins, Controls, and XML under the Developer ribbon.

Macro Example 1-9

  • The user can choose the type of button to be created. Select the first button from “form controls” in the Controls tab.

Macro Example 1-10

  • Drag the selected button anywhere in the Excel sheet. The “assign macro” dialogue box opens. The macros to be assigned are listed in the “macro name” box.
  • Select the macro “ReplaceDot,” appearing in the list and click “ok”. 

Macro Example 1-11

  • A button appears in the worksheet. Right click the button and use “edit text” option to change the button text as “Button 3.” It is created on the right-hand side of the sheet, as shown in the below image.

Macro Example 1-12

  • Select the new name list to implement the same task by running macros, as indicated in the previous section.

Macro Example 1-13

  • Click the “Button 3” to run the assigned macro “ReplaceDot”.

Macro Example 1-14

  • To change the button name, use the “edit text” option to replace the text “Button 3” with “ReplaceDot”.

Macro Example 1-15

Using the above steps, we can create, record, and assign the macro for various tasks and automate it.

How to View the Code of Macros?

The users can view the code for a recorded macro. Excel generates the code based on the steps carried out while recording the macro.

We can access the code using the shortcut “Alt+F11” or by editing the macro that was created earlier.

Let us view the code for the “ReplaceDot” macro using the following steps:

  • Open the worksheet that contains the “ReplaceDot” macro. In the View tab, click the option “macros”. Select the “ReplaceDot” macro from the list and click the “edit” button.

Macro Example 1-16

  • The “Microsoft Visual Basic for Applications” will be launched.  The user can write or edit the code using this application. The below image shows the code of the “ReplaceDot” macro.

Macro Example 1-17

Creating Macro by Writing VBA Code

Before writing the VBA code, let us understand the “head” and “tail” of macros, which are the “sub” and “end sub.”

Macro Example 2-1

The user places the lines of VBA codes in the keyword “sub”. It executes the instructions in the code. The “end sub” keyword stops the execution of the “sub.”

Generally, there are two types of macros.

  1. “System Defined Function” –  It performs actions like creating a link of all the worksheet names, deleting all worksheets and so on.
  2. “User-Defined Function” – To create a User Defined Function User Defined Function in VBA is a group of customized commands created to give out a certain result. It is a flexibility given to a user to design functions similar to those already provided in Excel.read more(UDF) in macro, the user uses the “function and end function” as the “head” and “tail” of the codes.

Note: A function returns a value, whereas the sub does not.

A macro is written on the Visual Basic EditorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more (VBE) of the “Microsoft Visual Basic for Applications”.

Let us learn the steps to write a simple macro in the VBA.

  • Click the “module 1” in the “module” properties displayed on the left-hand side panel of the VBE window, and start writing the macro.

Macro Example 2

  • Begin with “sub” followed by the macro name and end with “end sub”. The code is written between the “sub” and “end sub.”

The below image shows the “sub” and “end sub” for the macro named “simplemacro ( )”.

Macro Example 2-1

  • Write code to display text in the message box. The “MsgBoxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more” displays an input text message. All text in VBAText is a worksheet function in excel but it can also be used in VBA while using the range property. It is similar to the worksheet function and it takes the same number of arguments. These arguments are the values which needs to be converted.read more should be enclosed in double quotes.

For example,  the code:  MsgBox “Good Morning” (shown in the below image) displays the message “Good Morning” in the text box.

Macro Example 2-2

  • The output is displayed in the succeeding image.

Macro Example 2-3

Hence, the same macro can be assigned buttons to automate the task.

How to Save the Recorded Macro in Excel?

After recording, the user saves the macro to reuse in any other worksheet in the future.

Let us follow the below-mentioned steps to save the macro:

  • In the macro-enabled workbook,  click “save as.”
  • Select the “Excel macro-enabled workbook” option in the “save as type” box while saving the file.
  • Finally, save the macros with the “.xlsm” file extension.

Save Macro

The guidelines for saving the macro names are stated as follows:

  • Make sure that the name of recorded macros should start with letters (alphabets) or underscore.
  • Use letters, numeric, and underscore characters.
  • Avoid space, symbols, or punctuation marks.
  • Maintain a maximum length of about 80 characters.

Note: When the user saves a macro’s name with space, Excel issues a warning (as shown in the succeeding image).

Macro Warning

How to Enable “Macro Security Settings”?

In this section, let us learn to enable the “Macros security settings”.

When a user opens a workbook containing macros, a security warning – “Macros have been disabled” is displayed under the ribbon.  Choose the “enable content” option in the box.

Macro Security Warning

To eliminate the security warning, we need to change the “trust center settings” by using the following steps:

  • Under the “trust center settings” in the File options, click “macro settings”.
  • Choose the button, “Disable all macros with notification.”
  • The security is enabled in the “Macro Security” of the Developer ribbon.

Macro Security

Note 1: The user can create absolute macros (functioning from cell A1) that help to reuse the macro in other worksheets.

Note 2: The usage of directional keys (rather than a mouse) for navigation in macros is reliable to add, delete, and change the data in the worksheet.

Frequently Asked Questions (FAQs)

1. What are macros in Excel?

Macros are a set of simple programs or instructions to automate the common and repetitive tasks performed in the Excel worksheet. It can be recorded, saved, and run multiple times as per the user’s requirement.

It is a time-saving tool involved in preparing data reports and manipulating data carried out frequently in a worksheet.

2. How to enable macros in Excel?

The users can eliminate the security warning in the worksheet and enable macros by using the following steps:
• Click “options” in the File tab.
• Select “trust center” in the “options” window.
• Choose the option “trust center settings”.
• Click “macro settings” on the left side of the navigation pane.
• Select “enable all macros” and click “ok”.

3. What is the difference between macro and VBA?

The difference between macro and VBA is stated as follows.
• Macros are programming codes that function in the Excel worksheet to perform automated and repetitive tasks. It saves the user’s time and extends the efficiency of Excel.
• Visual Basic for Applications (VBA) is a programming language of Excel used for creating macros.

Recommended Articles

This has been a tutorial to Macros in Excel. Here we discuss how to add Macros in Excel along with , along with practical examples and a downloadable template. You may also look at these useful functions in Excel –

  • Excel Open XMLXML (Extensible Markup Language) is a text-based mark-up language that stores & organizes data in a human & machine-readable format. As it follows a specific script, you need to fulfill a particular set of prerequisites for importing the data into Excel or opening Excel Data into this format. read more
  • VBA MacrosVBA Macros are the lines of code that instruct the excel to do specific tasks, i.e., once the code is written in Visual Basic Editor (VBE), the user can quickly execute the same task at any time in the workbook. It thus eliminates the repetitive, monotonous tasks and automates the process.read more
  • MsgBox in Excel VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more

Введение

Всем нам приходится — кому реже, кому чаще — повторять одни и те же действия и операции в Excel. Любая офисная работа предполагает некую «рутинную составляющую» — одни и те же еженедельные отчеты, одни и те же действия по обработке поступивших данных, заполнение однообразных таблиц или бланков и т.д. Использование макросов и пользовательских функций позволяет автоматизировать эти операции, перекладывая монотонную однообразную работу на плечи Excel. Другим поводом для использования макросов в вашей работе может стать необходимость добавить в Microsoft Excel недостающие, но нужные вам функции. Например функцию сборки данных с разных листов на один итоговый лист, разнесения данных обратно, вывод суммы прописью и т.д.

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

В принципе, существует великое множество языков программирования (Pascal, Fortran, C++, C#, Java, ASP, PHP…), но для всех программ пакета Microsoft Office стандартом является именно встроенный язык VBA. Команды этого языка понимает любое офисное приложение, будь то Excel, Word, Outlook или Access.

Способ 1. Создание макросов в редакторе Visual Basic

Для ввода команд и формирования программы, т.е. создания макроса необходимо открыть специальное окно — редактор программ на VBA, встроенный в Microsoft Excel.

  • В старых версиях (Excel 2003 и старше) для этого идем в меню Сервис — Макрос — Редактор Visual Basic (Toos — Macro — Visual Basic Editor).
  • В новых версиях (Excel 2007 и новее) для этого нужно сначала отобразить вкладку Разработчик (Developer). Выбираем Файл — Параметры — Настройка ленты (File — Options — Customize Ribbon) и включаем в правой части окна флажок Разработчик (Developer). Теперь на появившейся вкладке нам будут доступны основные инструменты для работы с макросами, в том числе и нужная нам кнопка Редактор Visual Basic (Visual Basic Editor)



    macro1.png:

К сожалению, интерфейс редактора VBA и файлы справки не переводятся компанией  Microsoft на русский язык, поэтому с английскими командами в меню и окнах придется смириться:

macro2.png

Макросы (т.е. наборы команд на языке VBA) хранятся в программных модулях. В любой книге Excel мы можем создать любое количество программных модулей и разместить там наши макросы. Один модуль может содержать любое количество макросов. Доступ ко всем модулям осуществляется с помощью окна Project Explorer в левом верхнем углу редактора (если его не видно, нажмите CTRL+R). Программные модули бывают нескольких типов для разных ситуаций:

  • Обычные модули — используются в большинстве случаев, когда речь идет о макросах. Для создания такого модуля выберите в меню Insert — Module. В появившееся окно нового пустого модуля можно вводить команды на VBA, набирая их с клавиатуры или копируя их из другого модуля, с этого сайта или еще откуда нибудь:

    macro3.png

  • Модуль Эта книга — также виден в левом верхнем углу редактора Visual Basic в окне, которое называется Project Explorer. В этот модуль обычно записываются макросы, которые должны выполнятся при наступлении каких-либо событий в книге (открытие или сохранение книги, печать файла и т.п.):

    macro4.png

  • Модуль листа — доступен через Project Explorer и через контекстное меню листа, т.е. правой кнопкой мыши по ярлычку листа — команда Исходный текст (View Source). Сюда записывают макросы, которые должны выполняться при наступлении определенных событий на листе (изменение данных в ячейках, пересчет листа, копирование или удаление листа и т.д.)

    macro5.png

 Обычный макрос, введенный в стандартный модуль выглядит примерно так:

macro6.png

Давайте разберем приведенный выше в качестве примера макрос Zamena:

  • Любой макрос должен начинаться с оператора Sub, за которым идет имя макроса и список аргументов (входных значений) в скобках. Если аргументов нет, то скобки надо оставить пустыми.
  • Любой макрос должен заканчиваться оператором End Sub.
  • Все, что находится между Sub и End Sub — тело макроса, т.е. команды, которые будут выполняться при запуске макроса. В данном случае макрос выделяет ячейку заливает выделенных диапазон (Selection) желтым цветом (код = 6) и затем проходит в цикле по всем ячейкам, заменяя формулы на значения. В конце выводится окно сообщения (MsgBox).

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

Способ 2. Запись макросов макрорекордером

Макрорекордер — это небольшая программа, встроенная в Excel, которая переводит любое действие пользователя на язык программирования VBA и записывает получившуюся команду в программный модуль. Если мы включим макрорекордер на запись, а затем начнем создавать свой еженедельный отчет, то макрорекордер начнет записывать команды вслед за каждым нашим действием и, в итоге, мы получим макрос создающий отчет как если бы он был написан программистом. Такой способ создания макросов не требует знаний пользователя о программировании и VBA и позволяет пользоваться макросами как неким аналогом видеозаписи: включил запись, выполнил операци, перемотал пленку и запустил выполнение тех же действий еще раз. Естественно у такого способа есть свои плюсы и минусы:

  • Макрорекордер записывает только те действия, которые выполняются в пределах окна Microsoft Excel. Как только вы закрываете Excel или переключаетесь в другую программу — запись останавливается.
  • Макрорекордер может записать только те действия, для которых есть команды меню или кнопки в Excel. Программист же может написать макрос, который делает то, что Excel никогда не умел (сортировку по цвету, например или что-то подобное).
  • Если во время записи макроса макрорекордером вы ошиблись — ошибка будет записана. Однако смело можете давить на кнопку отмены последнего действия (Undo) — во время записи макроса макрорекордером она не просто возрвращает Вас в предыдущее состояние, но и стирает последнюю записанную команду на VBA.

Чтобы включить запись необходимо:

  • в Excel 2003 и старше — выбрать в меню Сервис — Макрос — Начать запись (Tools — Macro — Record New Macro)
  • в Excel 2007 и новее — нажать кнопку Запись макроса (Record macro) на вкладке Разработчик (Developer)

Затем необходимо настроить параметры записываемого макроса в окне Запись макроса:

macro7.png

  • Имя макроса — подойдет любое имя на русском или английском языке. Имя должно начинаться с буквы и не содержать пробелов и знаков препинания.
  • Сочетание клавиш — будет потом использоваться для быстрого запуска макроса. Если забудете сочетание или вообще его не введете, то макрос можно будет запустить через меню Сервис — Макрос — Макросы — Выполнить (Tools — Macro — Macros — Run) или с помощью кнопки Макросы (Macros) на вкладке Разработчик (Developer) или нажав ALT+F8.
  • Сохранить в… — здесь задается место, куда будет сохранен текст макроса, т.е. набор команд на VBA из которых и состоит макрос.:
    • Эта книга — макрос сохраняется в модуль текущей книги и, как следствие, будет выполнятся только пока эта книга открыта в Excel
    • Новая книга — макрос сохраняется в шаблон, на основе которого создается любая новая пустая книга в Excel, т.е. макрос будет содержаться во всех новых книгах, создаваемых на данном компьютере начиная с текущего момента
    • Личная книга макросов — это специальная книга Excel  с именем Personal.xls, которая используется как хранилище макросов. Все макросы из Personal.xls загружаются в память при старте Excel и могут быть запущены в любой момент и в любой книге.

После включения записи и выполнения действий, которые необходимо записать, запись можно остановить командой Остановить запись (Stop Recording).

Запуск и редактирование макросов

Управление всеми доступными макросами производится в окне, которое можно открыть с помощью кнопки Макросы (Macros) на вкладке Разработчик (Developer) или — в старых версиях Excel — через меню Сервис — Макрос — Макросы (Tools — Macro — Macros):

macro8.png

  • Любой выделенный в списке макрос можно запустить кнопкой Выполнить (Run).
  • Кнопка Параметры (Options) позволяет посмотреть и отредактировать сочетание клавиш для быстрого запуска макроса.
  • Кнопка Изменить (Edit) открывает редактор Visual Basic (см. выше) и позволяет просмотреть и отредактировать текст макроса на VBA.

Создание кнопки для запуска макросов

Чтобы не запоминать сочетание клавиш для запуска макроса, лучше создать кнопку и назначить ей нужный макрос. Кнопка может быть нескольких типов:

Кнопка на панели инструментов в Excel 2003 и старше

Откройте меню Сервис — Настройка (Tools — Customize) и перейдите на вкладку Команды (Commands). В категории Макросы легко найти веселый желтый «колобок» — Настраиваемую кнопку (Custom button):

macro9.gif

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

macro10.gif

Кнопка на панели быстрого доступа в Excel 2007 и новее

Щелкните правой кнопкой мыши по панели быстрого доступа в левом верхнем углу окна Excel и выберите команду Настройка панели быстрого доступа (Customise Quick Access Toolbar):

macro11.png

Затем в открывшемся окне выберите категорию Макросы и при помощи кнопки Добавить (Add) перенесите выбранный макрос в правую половину окна, т.е. на панель быстрого доступа:

macro12.png

Кнопка на листе

Этот способ подходит для любой версии Excel. Мы добавим кнопку запуска макроса прямо на рабочий лист, как графический объект. Для этого:

  • В Excel 2003 и старше — откройте панель инструментов Формы через меню Вид — Панели инструментов — Формы (View — Toolbars — Forms)
  • В Excel 2007 и новее — откройте выпадающий список Вставить (Insert) на вкладке Разработчик (Developer) 

Выберите объект Кнопка (Button):

macro13.png

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

Создание пользовательских функций на VBA

Создание пользовательских функций или, как их иногда еще называют, UDF-функций (User Defined Functions) принципиально не отличается от создания макроса в обычном программном модуле. Разница только в том, что макрос выполняет последовательность действий с объектами книги (ячейками, формулами и значениями, листами, диаграммами и т.д.), а пользовательская функция — только с теми значениями, которые мы передадим ей как аргументы (исходные данные для расчета).

Чтобы создать пользовательскую функцию для расчета, например, налога на добавленную стоимость (НДС) откроем редактор VBA, добавим новый модуль через меню Insert — Module и введем туда текст нашей функции:

macro14.png

Обратите внимание, что в отличие от макросов функции имеют заголовок Function вместо Sub и непустой список аргументов (в нашем случае это Summa). После ввода кода наша функция становится доступна в обычном окне Мастера функций (Вставка — Функция) в категории Определенные пользователем (User Defined):

macro15.png

После выбора функции выделяем ячейки с аргументами (с суммой, для которой надо посчитать НДС) как в случае с обычной функцией:

macro16.png

Понравилась статья? Поделить с друзьями:
  • Excel adding range of cells
  • Excel adding numbers with text
  • Excel adding not working
  • Excel adding drop downs
  • Excel adding columns to a table