What are excel macros for

Excel Macro is a record and playback tool that simply records your Excel steps and the macro will play it back as many times as you want. VBA Macros save time as they automate repetitive tasks. It is a piece of programming code that runs in an Excel environment but you don’t need to be a coder to program macros. Though, you need basic knowledge of VBA to make advanced modifications in the macro.

In this Macros in Excel for beginners tutorial, you will learn Excel macro basics:

  • What is an Excel Macro?
  • Why are Excel Macros Used in Excel?
  • What is VBA in a Layman’s Language?
  • Excel Macro Basics
  • Step by Step Example of Recording Macros in Excel

Why are Excel Macros Used in Excel?

As humans, we are creatures of habit. There are certain things that we do on a daily basis, every working day. Wouldn’t it be better if there were some magical way of pressing a single button and all of our routine tasks are done? I can hear you say yes. Macro in Excel helps you to achieve that. In a layman’s language, a macro is defined as a recording of your routine steps in Excel that you can replay using a single button.

For example, you are working as a cashier for a water utility company. Some of the customers pay through the bank and at the end of the day, you are required to download the data from the bank and format it in a manner that meets your business requirements.

You can import the data into Excel and format. The following day you will be required to perform the same ritual. It will soon become boring and tedious. Macros solve such problems by automating such routine tasks. You can use a macro to record the steps of

  • Importing the data
  • Formatting it to meet your business reporting requirements.

What is VBA in a Layman’s Language?

VBA is the acronym for Visual Basic for Applications. It is a programming language that Excel uses to record your steps as you perform routine tasks. You do not need to be a programmer or a very technical person to enjoy the benefits of macros in Excel. Excel has features that automatically generated the source code for you. Read the article on VBA for more details.

Excel Macro Basics

Macros are one of the developer features. By default, the tab for developers is not displayed in Excel. You will need to display it via customize report

Excel Macros can be used to compromise your system by attackers. By default, they are disabled in Excel. If you need to run macros, you will need to enable running macros and only run macros that you know come from a trusted source

If you want to save Excel macros, then you must save your workbook in a macro-enabled format *.xlsm

The macro name should not contain any spaces.

Always fill in the description of the macro when creating one. This will help you and others to understand what the macro is doing.

Step by Step Example of Recording Macros in Excel

Now in this Excel macros tutorial, we will learn how to create a macro in Excel:

We will work with the scenario described in the importance of macros Excel. For this Excel macro tutorial, we will work with the following CSV file to write macros in Excel.

Introduction to Macros in Excel

You can download the above file here

Download the above CSV File & Macros

We will create a macro enabled template that will import the above data and format it to meet our business reporting requirements.

Enable Developer Option

To execute VBA program, you have to have access to developer option in Excel. Enable the developer option as shown in the below Excel macro example and pin it into your main ribbon in Excel.

Step 1)Go to main menu “FILE”

Select option “Options.”

How to Write Macros in Excel

What is VBA?

Step 2) Now another window will open, in that window do following things

  • Click on Customize Ribbon
  • Mark the checker box for Developer option
  • Click on OK button

How to Write Macros in Excel

Step 3) Developer Tab

You will now be able to see the DEVELOPER tab in the ribbon

How to Write Macros in Excel

Step 4) Download CSV

First, we will see how we can create a command button on the spreadsheet and execute the program.

  • Create a folder in drive C named Bank Receipts
  • Paste the receipts.csv file that you downloaded

How to Write Macros in Excel

Step 5) Record Macro

  1. Click on the DEVELOPER tab
  2. Click on Record Macro as shown in the image below

How to Write Macros in Excel

You will get the following dialogue window

Introduction to Macros in Excel

  1. Enter ImportBankReceipts as the macro name.
  2. Step two will be there by default
  3. Enter the description as shown in the above diagram
  4. Click on “OK” tab

Step 6) Perform Macro Operations/Steps you want to record

  • Put the cursor in cell A1
  • Click on the DATA tab
  • Click on From Text button on the Get External data ribbon bar

You will get the following dialogue window

How to Write Macros in Excel

  1. Go to the local drive where you have stored the CSV file
  2. Select the CSV file
  3. Click on Import button

You will get the following wizard

Introduction to Macros in Excel

Click on Next button after following the above steps

Introduction to Macros in Excel

Follow the above steps and click on next button

Introduction to Macros in Excel

  • Click on Finish button
  • Your workbook should now look as follows

Introduction to Macros in Excel

Step 7) Format the Data

Make the columns bold, add the grand total and use the SUM function to get the total amount.

How to Write Macros in Excel

Step 8) Stop Recording Macro

Now that we have finished our routine work, we can click on stop recording macro button as shown in the image below

How to Write Macros in Excel

Step 9) Replay the Macro

Before we save our work book, we will need to delete the imported data. We will do this to create a template that we will be copying every time we have new receipts and want to run the ImportBankReceipts macro.

  • Highlight all the imported data
  • Right click on the highlighted data
  • Click on Delete
  • Click on save as button
  • Save the workbook in a macro enabled format as shown below

How to Write Macros in Excel

  • Make a copy of the newly saved template
  • Open it
  • Click on DEVELOPER tab
  • Click on Macros button

You will get the following dialogue window

Introduction to Macros in Excel

  1. Select ImportBankReceipts
  2. Highlights the description of your macro
  3. Click on Run button

You will get the following data

Introduction to Macros in Excel

Congratulations, you just created your first macro in Excel.

Summary

Macros simplify our work lives by automating most of the routine works that we do. Macros Excel are powered by Visual Basic for Applications.

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

При записи макроса все действия в записи макроса записываются Visual Basic для приложений (VBA) коде. Эти действия могут включать ввод текста или чисел, выбор ячеек или команд на ленте или в меню, форматирование ячеек, строк или столбцов или даже импорт данных из внешнего источника, скажем, Microsoft Access. Visual Basic Приложение (VBA) — это подмножество мощного Visual Basic программирования, которое входит в большинство Office приложений. Хотя VBA позволяет автоматизировать процессы как в приложениях, так и между Office, необязательно знать код VBA или программирование на компьютере, если оно делает то, что вам нужно.

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

Макросы и средства VBA находятся на вкладке Разработчик, которая по умолчанию скрыта, поэтому сначала нужно включить ее. Дополнительные сведения см. в статье Отображение вкладки «Разработчик».

Вкладка "Разработчик" на ленте

Запись макроса

Перед записью макросов полезно знать следующее:

  • Макрос, записанный для работы с диапазоном Excel, будет выполняться только для ячеек этого диапазона. Поэтому если вы добавите в диапазон новую строку, макрос не будет применяться к ней.

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

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

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

  1. На вкладке Разработчик в группе Код нажмите кнопку Запись макроса.

    -ИЛИ-

    Нажмите ALT+T+M+R.

    Команда "Записать макрос" в группе "Код" на вкладке "Разработчик"

  2. В поле Имя макроса введите название макроса. Сделайте имя понятным, чтобы можно было быстро найти нужный макрос.

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

  3. Чтобы назначить сочетание клавиш для запуска макроса, в поле Сочетание клавиш введите любую строчную или прописную букву. Рекомендуется использовать сочетания клавиш с CTRL+SHIFT, так как они будут заменять собой совпадающие с ними стандартные сочетания клавиш в Excel, пока открыта книга, содержащая макрос. Например, если назначить сочетание клавиш CTRL+Z (Отменить), вы не сможете использовать его для функции «Отменить» в данном экземпляре Excel.

  4. В списке Сохранить в выберите книгу, в которой вы хотите сохранить макрос.

    Как правило, макрос сохраняется в расположении Эта книга, но если вы хотите, чтобы макрос был доступен при использовании Excel, выберите Личная книга макроса . При выборе личнойкниги макроса Excel создает скрытую личную книгу макроса (Personal.xlsб), если она еще не существует, и сохраняет макрос в этой книге.

  5. В поле Описание при необходимости введите краткое описание действий макроса.

    Хотя поле «Описание» является необязательным, рекомендуется его заполнить. Кроме того, желательно ввести понятное описание, которое будет полезно вам и всем, кто запускает макрос. Если у вас много макросов, описания помогут быстро определить, для чего они нужны.

  6. Чтобы начать запись макроса, нажмите кнопку ОК.

  7. Выполните действия, которые нужно записать.

  8. На вкладке Разработчик в группе Код нажмите кнопку Остановить запись Изображение кнопки.

    -ИЛИ-

    Нажмите ALT+T+M+R.

Работа с макросами, записанными в Excel

На вкладке Разработчик щелкните Макросы, чтобы просмотреть макросы, связанные с книгой. Кроме того, можно нажать клавиши ALT+F8. При этом откроется диалоговое окно Макрос.

Диалоговое окно "Макрос"

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

Ниже приведены дополнительные сведения о работе с макросами в Excel.

Задача

Описание

Изменение параметров безопасности макросов в Excel

Сведения о параметрах безопасности макросов и их значении.

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

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

Изменение макроса

С помощью редактора Visual Basic можно изменять макросы, присоединенные к книге.

Копирование модуля макроса в другую книгу

Если книга содержит макрос VBA, который нужно использовать где-либо еще, этот модуль можно скопировать в другую книгу с помощью редактора Microsoft Visual Basic.

Назначение макроса объекту, фигуре или графическому элементу

  1. Щелкните правой кнопкой мыши объект, рисунок, фигуру или элемент, которому вы хотите назначить существующий макрос, и выберите пункт Назначить макрос.

  2. В поле Назначить макроса выберите макрос, который вы хотите назначить.

Назначение макроса кнопке

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

Назначение макроса для элемента управления на листе

Вы можете назначать макросы формам и элементам ActiveX на листе.

Включение и отключение макросов в файлах Office

Узнайте, как включать и отключать макросы в файлах Office.

Открытие редактора Visual Basic

Нажмите клавиши ALT+F11.

Поиск справки по использованию редактора Visual Basic

Узнайте, как найти справку по элементам Visual Basic.

Работа с записанным кодом в редакторе Visual Basic (VBE)

С помощью редактора Visual Basic (VBE) вы можете добавлять в записанный код собственные переменные, управляющие структуры и другие элементы, которые не поддерживает средство записи макросов. Так как средство записи макросов фиксирует почти каждый шаг, выполняемый во время записи, может также потребоваться удалить ненужный код. Просмотр записанного кода — отличный способ научиться программировать на VBA или отточить свои навыки.

Пример изменения записанного кода можно найти в статье Начало работы с VBA в Excel.

Запись макроса

Перед записью макросов полезно знать следующее:

  • Макрос, записанный для работы с диапазоном Excel, будет выполняться только для ячеек этого диапазона. Поэтому если вы добавите в диапазон новую строку, макрос не будет применяться к ней.

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

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

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

  1. Перейдите в Excel > параметры…> ленты & панель инструментов.

  2. В категории Настроить ленту в списке Основные вкладки установите флажок Разработчик, а затем нажмите кнопку Сохранить.

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

  1. На вкладке Разработчик нажмите кнопку Запись макроса.

  2. В поле Имя макроса введите название макроса. Сделайте имя понятным, чтобы можно было быстро найти нужный макрос.

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

  3. В списке Сохранить в выберите книгу, в которой вы хотите сохранить макрос.

    Как правило, макрос сохраняется в расположении Эта книга, но если вы хотите, чтобы макрос был доступен при использовании Excel, выберите Личная книга макроса. При выборе личнойкниги макроса Excel создает скрытую личную книгу макроса (PERSONAL.XLSB), если она еще не существует, и сохраняет макрос в этой книге. Книги в этой папке открываются автоматически при Excel, и любой код, сохраненный в личной книге макроса, будет указан в диалоговом окну Макрос, которое объясняется в следующем разделе.

  4. Чтобы назначить сочетание клавиш для запуска макроса, в поле Сочетание клавиш введите любую строчную или прописную букву. Рекомендуется использовать сочетания клавиш, которые еще не назначены другим командам, так как они будут переопределять совпадающие с ними стандартные сочетания клавиш в Excel, пока открыта книга, содержащая макрос.

  5. В поле Описание при необходимости введите краткое описание действий макроса.

    Хотя поле «Описание» является необязательным, рекомендуется его заполнить. Полезно ввести содержательное описание со всеми сведениями, которые могут быть полезны вам или другим пользователям, которые будут запускать макрос. Если у вас много макросов, описания помогут быстро определить, для чего они нужны.

  6. Чтобы начать запись макроса, нажмите кнопку ОК.

  7. Выполните действия, которые нужно записать.

  8. На вкладке Разработчик щелкните Остановить запись.

Работа с макросами, записанными в Excel

На вкладке Разработчик щелкните Макросы, чтобы просмотреть макросы, связанные с книгой. При этом откроется диалоговое окно Макрос.

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

Ниже приведены дополнительные сведения о работе с макросами в Excel.

Задача

Описание

Включение и отключение макросов

Узнайте, как включать и отключать макросы в Excel для Mac.

Копирование модуля макроса в другую книгу

Если книга содержит макрос VBA, который нужно использовать где-либо еще, этот модуль можно скопировать в другую книгу с помощью редактора Microsoft Visual Basic.

Назначение макроса объекту, фигуре или графическому элементу

  1. Щелкните правой кнопкой мыши объект, рисунок, фигуру или элемент, которому вы хотите назначить существующий макрос, и выберите пункт Назначить макрос.

  2. В поле Назначить макроса выберите макрос, который вы хотите назначить.

Назначение макроса кнопке

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

Назначение макроса для элемента управления на листе

Вы можете назначать макросы формам и элементам ActiveX на листе.

Открытие редактора Visual Basic

На вкладке Разработчик щелкните Visual Basic или выберите Сервис > Макрос > Редактор Visual Basic.

Поиск справки по использованию редактора Visual Basic

Узнайте, как найти справку по элементам Visual Basic.

Дополнительные сведения

Вы всегда можете задать вопрос специалисту Excel Tech Community или попросить помощи в сообществе Answers community.

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

  • 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
Узнать больше

You work in Excel every day and do the same things again and again. Why not automate those tasks? Or, maybe, you want Excel to do most of the work for you? Read on to learn what Excel macros are and how they can help you.

What are macros in Excel?

Excel is an extremely powerful tool for processing data in the form of spreadsheets. While most users use formulas, there is another way to manipulate data in Excel.

Excel macros are pieces of code that describe specific actions or contain a set of instructions. Every time you launch the macro, Excel follows those instructions step-by-step.

Why learn macros in Excel?

Macros are a must-have tool for an advanced Excel user. By using Excel macros you can avoid dull, repetitive actions or even create your own order management system for free.

Simple macros in Excel that will make things easier

There are lots of simple Excel macros that take just a few lines of code, but can save you hours. Excel can perform certain operations instantly, where it would take you a very long time to do the job manually.

For example, this macro will sort all worksheets alphabetically:

Sub SortSheetsTabName()
Application.ScreenUpdating = False
Dim ShCount As Integer, i As Integer, j As Integer
ShCount = Sheets.Count
For i = 1 To ShCount - 1
For j = i + 1 To ShCount
If Sheets(j).Name < Sheets(i).Name Then
Sheets(j).Move before:=Sheets(i)
End If
Next j
Next i
Application.ScreenUpdating = True
End Sub

The following code will unhide all hidden worksheets:

Sub UnhideAllWoksheets()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws
End Sub

To unhide all rows and columns on a worksheet, use:

Sub UnhideRowsColumns()
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
End Sub

Advanced Excel macros that can significantly improve your workflow

If you are running a business, you have to store and manipulate data. Small companies can keep records by hand and large enterprises can buy specialized software (which is rather expensive). But what about medium-sized businesses that can no longer settle for manual record-keeping, but still cannot afford costly software? This is where Excel with macros shines.

By combining advanced Excel macros you can create a CRM (Customer Relationship Management) system which will help you provide better services. If you sell goods, you need an inventory management tool and Excel spreadsheets enhanced with macros will fit your needs.

If your data is contained in multiple Excel workbooks, you can use Coupler.io to move them around. You can even add third-party sources, like  Google Sheets, Airtable, BigQuery, etc. Data integration with Coupler.io does not require any programming skills and can be done in just a few clicks.

1 excel integrations coupler

Check out the available integrations with Excel.

Other Excel macros examples

Below are a few examples of useful Excel macros.

Sometimes you might accidentally add extra spaces to the data in cells. This mistake will cause errors, thereby preventing you from making correct calculations. To remove unnecessary spaces from the selected cells, use the following code:

Sub TrimTheSpaces()
Dim MyRange As Range
Dim MyCell As Range
Set MyRange = Selection
For Each MyCell In MyRange
If Not IsEmpty(MyCell) Then
MyCell = Trim(MyCell)
End If
Next MyCell
End Sub

It is often the case that you need to protect your workbook with a password. You can do that in the user interface of Excel. However, if you use the same password for all of your workbooks, you have to re-enter it every time. This macro will do the job for you (don’t forget to replace “1234” with your own password!):

Sub ProtectSheets()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Protect Password:="1234"
Next ws
End Sub

Using macros in Excel

As macros are programs that can do literally anything on your computer, using macros from untrusted sources is very risky. That’s why, when you open a workbook with macros in Excel, they will be disabled and you will see the following notification:

1 macros security warning

If you trust the source of the file, click Enable Content. That will add the workbook to the list of trusted documents and turn on its macros. The next time you open that workbook, there will be no warning.

You will see the above notification each time you open a workbook if it has been saved to an untrusted location. That can be a folder for temporary files or browser downloads. To avoid that, move the file to another folder or enable macros in the Excel Trust Center.

How to enable macros in Excel

If you do not want to see the security warning when opening Excel workbooks, you can permanently enable macros in the Trust Center.

To enable macros in the Excel Trust Center:

  1. In the upper-left corner, click the File tab and then select Options:

2 Excel options selection

  1. In the Excel Options window, select Trust Center and then click Trust Center Settings:

3 excel trust center selection

  1. In the Trust Center, go to Macro Settings and then select Enable all macros:

4 enable macros

Warning! Enabling macros for all workbooks is potentially risky because files from external sources may contain malicious code. If you open such a workbook, the macros may run automatically and corrupt your data or even cause hardware malfunctions.

How to use macros in Excel

If your workbook contains macros, you can run them by pressing Alt+F8. In the Macro window that opens, select the macro you need and click Run:

5 select the macro you need and click Run

If you want to create new macros, you need to enable the Developer tab first.

To enable the Developer tab:

  1. In the upper-left corner, click the File tab and then select Options.
  2. In the Excel Options window, select Customize Ribbon and then enable the Developer checkbox in the Main Tabs area:

6 enable developer tab

  1. Click OK to apply the changes.

In the Developer tab you can run existing macros by clicking the Macros button or create a new macro. For details on creating macros in Excel, see the following sections.

7 developer tab

How to delete macros in Excel

To delete a macro in Excel:

  1. Open the Macro window in one of the following ways:
    • Press Alt+F8.
    • Select the Developer tab and click Macros.
  2. Select the macro that you want to delete and click Delete.

8 delete macro

  1. Click Yes in the confirmation window that opens.

How to disable macros in Excel

Enabling Excel macros can make your computer vulnerable. Some macros will run when you open a workbook, which is especially dangerous if you have downloaded the workbook from an untrusted source. To prevent that, you can disable macros in Excel either with or without a notification.

To disable macros in Excel:

  1. In the upper-left corner, click the File tab and then select Options.
  2. In the Excel Options window, select Trust Center and then click Trust Center Settings.
  3. In the Trust Center, go to Macro Settings and then select one of the following options:
    • Disable all macros without notification. Macros will be disabled and you will not see a security warning when opening a workbook with macros.
    • Disable all macros with notification. Macros will be disabled but you will see a security warning when opening a workbook with macros and will be able to allow macros, if needed.

9 disable macros

Writing macros in Excel

In Excel you can not only run ready-to-use macros, but also write your own macros to automate your daily tasks. We will provide a few methods below for creating macros in Excel. Anyone can write macros in Excel: from a complete beginner to an advanced user with programming skills.

How to record a macro in Excel

If you are unfamiliar with programming languages, the easiest way to create your own Excel macro is to record it.

To record a macro in Excel:

  1. In the Developer tab, click Record Macro:

10 record macro

  1. Enter the macro name and click OK:

11 enter macro name

Excel will start recording the macro.

  1. Perform the actions, that need to be included in the macro, then click Stop Recording:

12 stop macro record

The macro will be saved to the workbook.

Creating VBA macros in Excel

If you can write code in any programming language, you can easily learn the basics of Visual Basic for Applications and create Excel macros in the VBA editor.

To open the editor, click Visual Basic in the Developer tab.

Each workbook is a VBA project in the editor. The project contains worksheets as objects and modules with macros:

13 VBA project

By default, macros recorded in the Developer tab are saved to Module1. For example, here is the macro that we recorded in the previous section:

14 sample macro

As you can see in the picture above, a macro starts with Sub followed by the macro name and (). You can insert the macro description in the comment lines. Be sure to indent the macro body for better readability. The End Sub string designates the end of the macro.

Excel macros language

Macros in Excel are written in VBA (Visual Basic for Applications). This programming language is used not only in Excel, but also in other MS office applications.

VBA provides many of the tools that are available in advanced programming languages. For example, to create Excel macros, you can use the following:

  • Variables
  • ‘If’ statements
  • ‘For’ cycles
  • Loops
  • Arrays
  • Events
  • Functions

Being an object-oriented language, VBA lets you manipulate the following objects:

  • Application object
  • Workbook object
  • Worksheet object
  • Range object

If you decide to turn your Excel worksheet into something much more powerful, like a CRM system, you can even create a graphical user interface with message boxes and user forms. To learn more about VBA, check out the official documentation.

Editing macros in Excel VBA editor

When creating macros in Excel, it may be difficult to get the desired result on the first try. By editing Excel macros and running them again, you can resolve errors and make your system work as expected.

To edit a macro in Excel VBA editor:

  1. In the Developer tab, click Visual Basic:

15 open VBA editor

  1. In the VBA project tree, double-click the module with the macro that you want to edit:

16 select module

  1. Edit the macro code, then save changes by clicking the Save button or pressing Ctrl+S.

The workbook with the macro will be saved.

You can press F5 or click Run in the editor to launch the macro:

17 run macro from editor

Note: If a macro changes workbook data, those changes cannot be reversed using the Undo command in Excel.

The VBA editor has a built-in debugger that highlights errors in code. The line that follows the error is highlighted:

18 VBA debugger

An easy way of learning how to create macros in Excel

In Excel you can record a macro by using the Record Macro button in the Developer tab. Then you can open the recorded macro in Excel VBA editor.

This is the easiest way to learn the VBA programming language. Just perform actions in the Excel user interface and see how they are interpreted in the macro code. Then you can change values and methods in the code to see how that affects the macro behavior.

Do I need Excel macros?

As you can see, macros can drastically enhance Excel features in many ways. By using macros, you can automate your daily operations and save yourself hours of time. Excel macros can even save you money if you decide to create an Excel-based order management system instead of buying costly software.

When you finish customizing your Excel workbook with macros, you may need to migrate your data from other sources, like Google Sheets or BigQuery.

  • Zakhar Yung

    A content manager at Coupler.io whose key responsibility is to ensure that the readers love our content on the blog. With 5 years of experience as a wordsmith in SaaS, I know how to make texts resonate with readers’ queries✍🏼

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

Skip to content

How to Create Macros in Excel: Step-by-Step Tutorial (2023)

How to Create Macros in Excel: Step-by-Step Tutorial (2023)

Get ready to have your mind blown! 🤯

Because in this tutorial, you learn how to create your own macros in Excel!

That’s right! And you don’t need to know VBA (Visual Basic for Applications)!

Instead, you will use the Excel macro recording feature to send your spreadsheet experience into overdrive! 🚀

So, read on and try it out yourself using this practice Excel workbook.

What are Excel macros?

A macro is a small program or set of actions that you can run repeatedly. Excel macros are used to automate repetitive tasks to save a lot of time and hassle.

For example, open and take a look at the practice Excel workbook.

Excel Macro Tutorial Workbook

Businesses would often have lists like this one. These are potential customers they might want to reach out to and market their products.

Notice how Columns C to H are just pieces of information extracted from Columns A & B.
(Learn how to extract strings from texts in this tutorial!)

To streamline the worksheet, you can hide Columns A & B. You can also hide the rest of the columns on the right starting from Column I.

Let’s do this using Excel macros!

How to record Excel macros

1. Click on the View tab in the Excel ribbon

The View tab can be found on the Excel ribbon

2. Next, click on the Macros button on the right side of the View ribbon

Macros drop-down button

3. This will open the Macros drop-down.

Click Record Macro.

Record Macro button

4. Enter a name for your macro, something like Hide_Columns.

Macro names should relate to their functions

Excel macros can be stored in the Personal Macro Workbook. This is saved in the system files of Microsoft Excel and macros saved here can be used in other workbooks.

Select Personal Macro Workbook if want to use the macro in other workbooks

For this Excel macro tutorial, you only need to save the macros in the current Excel file.

Kasper Langmann, Microsoft Office Specialist

4. Select Store macro in: This Workbook then click the OK button.

Excel is now recording your actions to create a macro.

5. Select Columns A & B and then right-click on the highlighted Column Bar to Hide them.

Right-click on the columns and select Hide

6. Then select Column I and press Ctrl + Shift + Right Arrow to include all remaining columns on the right.

Ctrl + Shift + Right Arrow expands the current selection to include all cells/columns on the right

7. Right-click on the highlighted Column Bar then click on Hide.

Your worksheet should now look like this:

The unnecessary rows are now all hidden

To end the macro recording:

8. On the View ribbon, click on Macros and select Stop Recording.

Excel records all actions until the recording is stopped

Good job! 👏

You have created your first macro in Excel!

But wait, where is the recorded macro?

To view all of the available Excel macros :

1. Select View Macros.

Click on View Macros on the View tab ribbon

2. This opens the Macro window. Saved macros will be listed here and you can Run whichever one you need.

You can also click on Edit to view the VBA code window.

You can run, delete, and edit macros from this window

3. The VBA code editor opens.

VBA code is used in creating macros

Notice the Hide_Columns Sub procedure. You don’t have to write or edit VBA code for the macro.

Excel automatically generated each code line based on the recorded keystrokes and mouse clicks.

The Record Macro feature is powerful enough for general spreadsheet automation needs.

But if you want to customize your own VBA macro, you can learn more about Visual Basic for Applications (VBA) here.

Using the Developer tab

Let’s record another macro to Unhide the hidden columns.

This time, you can record the macro from the Developer tab.

The Developer tab gives you access to a lot of useful Microsoft Excel features such as the Visual Basic Editor. It also allows you to quickly insert form controls such as buttons and checkboxes.

However, the Developer tab is not visible in the Excel ribbon by default.

To add it:

1. Right-click on the Excel ribbon.

Select Customize the Ribbon.

To customize the ribbon, you can also click File > More... > Options > Customize Ribbon tab

2. This opens the Customize Ribbon window.

On the right side, check the Developer tab checkbox.

You can customize the ribbon to include features like the Developer tab and Add-Ins tab

3. You should now see the Developer tab.

The Developer tab features tools for Visual Basic and macros

To start recording the Unhide macro:

1. Click on the Record Macro button in the Developer tab.

Click to start recording

2. Name this macro Unhide_Columns.

You can add a description to briefly explain the macro

3. Click OK.

The recording has started.

4. Press Ctrl + A twice to select all cells.

5. Right-click anywhere on the Column Bar then click Unhide.

This unhides all columns on the worksheet

6. Click on the Stop Recording macro button to finish up.

Click to stop recording for the macro

Great work! 👌

Now you have two recorded macros that can be executed.

How to run an Excel macro

To run your macros:

1. Click on the Macros button from the Developer tab.

This will open the Macro window

2. In the Macro window, select the macro Hide_Columns and click on Run.

You can also double-click the corresponding macro name to run it

The macro executes the actions recorded earlier and hides the unnecessary columns.

You can also run macros from the View ribbon.

Run Excel macro from the View tab

This time, run the Unhide_Columns to show all the columns.

1. On the View ribbon, click the Macros button and select View Macros.

2. Select the Unhide_Columns macro and Run it.

Run selected macro

This unhides all the columns in the worksheet.

As you can see, the Macro window allows you to quickly run all the available macros.

But you can execute them even faster by using buttons and shortcuts ❗

Run Excel macro from a button

For this next example, you will assign macros to buttons which will be located on top of the table.

1. Insert 2 rows above the table headers. Select Row 1 then press Ctrl + Shift + Plus Sign(+) twice.

Ctrl + Shift + Plus Sign(+) adds one row above the currently selected row

2. To create a button, click on Insert > Illustrations > Shapes.

Then select the Rectangle.

Macros can be assigned to objects such as shapes and icons

3. Draw a rectangle and format it as you’d like. Label it “HIDE”.

Name your buttons to describe their function

This will be your HIDE button. Place it between columns A & B so it will be hidden with the columns when the macro runs.

4. To assign a macro, right-click the shape and select Assign Macro.

Assigning a macro to a shape makes it a button

5. In the Assign Macro window, select Hide_Columns and click OK.

Only one macro can be assigned per button but a macro can be assigned to multiple buttons

The Hide button now works!

Now, do the same for the Unhide_Columns macro.

6. Create another rectangle button and label it “UNHIDE”.

Right-click on a shape and select Style to quickly change its appearance

7. Repeat Steps 4 & 5 but this time, assign the Unhide_Columns macro.

Alright! 👍

Now you can quickly run your macros using the HIDE and UNHIDE buttons.

Keep in mind the positions of your buttons when hiding entire columns

Run Excel macro from a shortcut key

It is sometimes better to run macros using a keyboard shortcut.

For this next example, you want to quickly highlight people on the list that expressed interest in the business.

To create a macro for this:

1. Select any cell within the table.

You can select the person that will be marked as interested

2. On the Developer tab, toggle ON the Use Relative References button.

Use Relative References should be ON when recording macros that will be ran on different cells

3. Start recording with the Record Macro button on the Developer tab.

Or, you can also click the Record Macro button on the Status Bar.

The Status Bar is at the bottom left corner of the Excel window

4. Name the macro Mark_Interested.

Then assign a shortcut key. For example, Ctrl + Q.

You can use any letter for the shortcut key but try to avoid using built-in Excel shortcuts such as Ctrl + A

Click OK. The recording has now started.

4. Highlight the row of the Active Cell using the keyboard shortcut Shift + Space Bar.

Shift + Space Bar selects the entire row of the current active cell

When selecting cells or expanding selections while recording a macro, it is best to use keyboard shortcuts.

This is so that Excel can record the selections as relative references.

For example, if you select Row 4 by clicking on the Row Bar, Excel will record this as an absolute reference. This means it will always select Row 4 regardless of the currently Active Cell.

When you use the Shift + Space Bar shortcut instead, it tells Excel to select the row of the current Active Cell.

Kasper Langmann, Microsoft Office Specialist

5. Apply the formatting:

  • Fill using the color Green
  • Change font color to White
Macros are made to automate repetitive tasks like formatting

6. End the macro recording from the Status Bar

Stop Recording button

All done!

Try to use the shortcut Ctrl + Q to quickly apply formatting to entire rows.

Now you only need to press the shortcut key to completely format a row

Saving macro-enabled workbooks

If you save the practice workbook, this window will pop up:

If you click "Yes", the macros will not be saved

This is because the practice workbook is currently saved with the .xlsx file extension which does not support macro features.

To save properly, change it to the .xlsm file extension for macro-enable workbooks.

Keep this in mind when saving your work.

Congratulations! 🤩

You are now familiar with Excel macros.

Try to record your own macros and start saving time ⏱️ on your work!

That’s it – Now what?

The examples above are very useful though they are quite simple.

You can record macros for more complex functions. Such as creating custom charts or selectively copying rows of data to another workbook.

But recording and playing macros is just the tip of the iceberg.

With VBA programming, you get access to a whole different level of Excel automation. 🤖

And while Visual Basic may seem overwhelming at first, you can start slow with basic variables and IF statements. These are much easier than you might think!

Learn all that and much more in my free 30-minute online VBA course here.

Other resources

If you want to know more about the inner workings of the record macro feature, check out my Excel macro tutorial for beginners on YouTube.

You can also dive right into VBA by reading this article or watching this introductory video on VBA and macros!

Hope you enjoyed this article!

Kasper Langmann2023-01-19T12:25:15+00:00

Page load link


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,423 times.

Is this article up to date?

Spreadsheets are infinitely flexible—especially in Excel, one of the most powerful spreadsheet apps. Most people use only a small percentage of their seemingly countless possibilities, however. Yet it doesn’t take years of training to take advantage of spreadsheets’ power and the automation magic of Excel macros.

You likely already use functions like =sum(A1:A5), the simple bits of text that add, average, and calculate your values. They’re what make spreadsheets a powerful tool for crunching numbers and text. Macros are the next step: They’re tools that automate simple tasks and help you get more done in less time. Here’s how to unlock that new part of your Excel skill set by building your own macros in Excel.

Kasper Langmann is an Excel expert and co-founder of Spreadsheeto. This post was originally published in August 2016, but has been updated with additional tips


  • What Are Excel Macros?

  • Why Macros?

  • How to Build Your First Excel Macros

  • How to Code Your Own Excel Macros

  • Connect Excel to Other Apps with Integrations


What Are Excel Macros?

Macros are code that automate work in a program—they let you add your own tiny features and enhancements to help you accomplish exactly what you need to do, quickly with just a click of abutton. In a spreadsheet tool like Excel, macros can be especially powerful. Hidden behind the normal user interface, they are more powerful than standard functions you enter into a cell (e.g.=IF(A2<100,100,A2)).

These macros make Excel work for you. They replace actions that you do manually—everything from formatting cells, copying values, and calculating totals. So with a few clicks you can quickly replace repetitive tasks.

To make these macros, you can simply record your actions in Excel to save them as repeatable steps or you can use Visual Basic for Applications (VBA), a simple programming language that’s built into Microsoft Office. We’ll show you how to use both below, as well as share examples of Excel macros to help you get started.

Tip: This guide and all examples are written in Excel 2016 for Windows, but the principles apply to Excel 2007 and newer for both Mac and PC.

Why Use Excel Macros?

Learning how to automate Excel is one of the easiest ways to speed up your work—especially because Excel is used in so many work processes. Say every week you export analytics data from your content management system (CMS) to create a report about your site. The only problem is, those data exports aren’t always in an Excel-friendly format. They’re messy and often include far more data than your report requires. This means you have to clean up empty rows, copy and paste data into the right place, and create your own charts to visualize data and make it print-friendly. All of these steps may take you hours to complete.

If there only was a way to press one button and let Excel do it for you in an instant… Well, can you guess what I’m about to say next?

There is!

All it requires is a little bit of time to set up a macro, and then that code can do the work for you automatically every time. It’s not even as difficult as it sounds.

How to Build Your First Excel Macro

You already know your way around Excel, and are familiar with its grid of cells where you enter your text and functions. To build Excel macros, though, you’ll need an extra tool that’s built into Excel: the Visual Basic Editor.

Before You Proceed: Be sure to download our project file – you’ll need it for later to follow our Excel macros tutorial.

Meet The VBA Editor

Excel has a built-in tool for writing macros called the Visual Basic Editor—or VBA Editor for short. To open that, open a spreadsheet and use the shortcut Alt + F11 (for Mac: Fn + Shift + F11).

The new window that pops up is called the VBA Editor. It’s where you’ll edit and store all of your macros. Its layout may look a bit different from this screenshot, but you can move the windows around to the order you want. Just be sure to keep the Project Explorer pane open so you can easily edit your macros.

VBA project explorer

Your macros will be made up of «Modules,» or files with your VBA code. You’ll add a new module or open an existing one in the VBA Editor, then type in the code you want. To insert a module, click «Insert» and then click «Module». You’ll then see the blank space to write your code on the right.

vba editor

How to Record an Excel Macro

There are two ways to make a macro: code it or record it. The main focus of this article is on the former, but recording a macro is so simple and handy, it’s worth exploring too. Recording a macro is a good way of getting to know the basics of VBA. Later on, it serves as handy storage for code that you don’t need to memorize.

When you record a macro, you tell Excel to start the recording. Then you perform the tasks you want to be translated into VBA code. When you’re done, tell Excel to stop recording and you can use this new macro to repeat the actions you just performed again and again.

There are limitations to this, so you can’t automate every task or become an expert in automation by only recording. You’ll still need to type or edit code manually sometimes. But it’s still a handy way to get started. Here’s how: 1. Go to the «View» tab of the ribbon and click the tiny arrow below the «Macros» button. 2. Then click «Record Macro» 3. Type in the name of your macro and click «OK» to start the recording. 4. Perform the actions in your spreadsheet you want to be turned into a macro. 5. When you’re done, go to the «View» tab, click the tiny arrow below the «Record Macro» button again and select «Stop recording».

record macro in Excel

Now, use the shortcut Alt + F11 (for Mac: Fn + Shift + F11) to open the VBA Editor, and double-click «Module 1» in the Project Explorer.

This is your first code! Amazing, right? You may not have written it yourself, but it’s still generated from your actions.

first macro in VBA

Yours probably look different than mine. Can you guess what my code does?

  • Sub Makebold is just the text Sub followed by the name I entered when I started recording.

  • The green line doesn’t actually do anything—it’s a comment where you could add an explanation of what the macro does.

  • Selection.Font.Bold = True makes the values in the selected cells bold.

  • End sub simply tells Excel that the macro stops here.

Now, what will happen if I change the True part of the third line to False? The macro would then remove any bold formatting from the selection instead of making it bold.

That’s how you record a simple macro. But the real power of macros comes when you can write it yourself—so let’s get started learning to write simple VBA code.

How to Code Your Own Excel Macros

Macros are just bits of code in Excel that do your bidding. Once you write the code in the VBA Editor, you can run it and let the code work its magic on your spreadsheet. But what’s even better is to build your macro into your spreadsheet, and the best tool for that is buttons.

So first, before we start coding, let’s add a button to run our macro.

Add a Button to Run Your Macro

You can use various Excel objects as buttons for running macros, but I prefer to use a shape from the «Insert» tab. When you have inserted your shape, right click it and select «Assign Macro…» Then select the macro you want to run when the shape is clicked—perhaps the one you just made with a recording and save it by clicking «OK».

Attach macro to button in Excel

Now, when you click the shape which we just turned into a button, Excel will run the macro without having to open the code each time.

There’s one other thing to note before we get started: saving your spreadsheet with Macros. By default, Excel spreadsheet files with an .xlsx extension cannot include macros. Instead, when you save your spreadsheet, select the «Excel Macro-Enabled Workbook (*.xlsm)» format, and add your file name as normal.

Go ahead and do that to save your spreadsheet before we start coding.

Save as macro enabled Excel file


Now, let’s get started with actual coding!

Copying and pasting is the simplest way to move data around, but it’s still tedious. What if your spreadsheet could do that for you? With a macro, it could. Let’s see how to code a macro that will copy data and move it around in a spreadsheet.

Open the project file you downloaded earlier and make sure the «Copy, cut, and paste» sheet is selected. This is a sample employee database with the names, departments, and salaries of some employees.

Let’s try to copy all the data in columns A through C into D through F using VBA. First, let’s look at the code we need:

Copying Cells with VBA

Copying in VBA is quite easy. Just insert this code into the VBA Editor: Range("Insert range here").Copy. Here’s some examples:

  • Range("A:C").Copy ← copies column A through C

  • Range("A1:C100").Copy ← copies the range A1:C100

Remember when you recorded a macro before? The macro had Sub Nameofmacro() and End sub at the top and bottom line of the code. These lines must always be included. Excel makes that easy, too: When you type in «Sub» followed by the macro name in the beginning of the code, the End sub is automatically inserted at the bottom line.

Tip: Remember to enter these lines manually when you’re not using the macro recorder.

Pasting Cells with VBA

Pasting can be done in different ways depending on what you want to paste. 99% of the time, you’ll need one of these two lines of code:

  • Range("The cell/area where you want to paste").Pastespecial ← pastes as normal (formulas and formatting)

  • Range("The cell/area where you want to paste").Pastespecial xlPasteValues ← only pastes values

Cutting Cells with VBA

If you want to relocate your data instead of copying it, you need to cut it. Cutting is quite easy and follows the exact same logic as copying.

Here’s the code: Range("Insert range here").Cut

When cutting, you can’t use the ‘PasteSpecial’ command. That means that you can’t paste values only, or formatting only. Therefore, you need these lines to paste your cells with VBA: Range(«Insert where you want to paste»).Select ActiveSheet.Paste

For example, here’s the code you’d need to cut the range A:C and paste it into D1:

  • Range("A:C").Cut

  • Range("D1").Select

  • ActiveSheet.Paste


Copying, cutting, and pasting are simple actions that can be done manually without breaking a sweat. But when you copy and paste the same cells several times a day, a button that does it for you can save a bunch of time. Additionally, you can combine copying and pasting in VBA with some other cool code to do even more in your spreadsheet automatically.

Adding Loops to VBA

I just showed you how to take a simple action (copying and pasting) and attach it to a button, so you can do it with a mouse click. That’s just one automated action. When you have the code to repeat itself, though, it can do longer and more complex automation tasks in seconds.

Take a look at the «Loops» sheet in the project file. It’s the same data as in the previous sheet, but every third row of the data is now moved one column to the right. This type of faulty data structure is not unusual when exporting data from older programs.

This can take a lot of time to fix manually, especially if the spreadsheet includes thousands of rows instead of the small sample data in this project file.

Let’s make a loop that fixes it for you. Enter this code in a module, then look at the explanations below the picture:

excel macro loop code

  1. This line makes sure the loop starts at the top-left cell in the sheet and not accidentally messes the data up by starting somewhere else.

  2. The For i = 1 To 500 line means that the number of times the loop has run (represented by i) is an increasing number that starts with 1 and ends with 500. This means that the loop will run 500 times. The number of times the loop should run depends on the actions you want it to do. Use your good sense here. 500 times is way too many for our sample dataset, but would fit perfectly if the database had 1500 rows of data.

  3. This line recognizes the active cell and tells Excel to move 3 rows down and select that cell, which then becomes the new active cell. If it was every fourth row that was misplaced in our data, instead of every third, we could just replace the 3 with a 4 in this line.

  4. This line tells Excel what to do with this newly selected cell. In this case, we want to delete the cell in such manner that the cells to the right of the cell are moved left. That is achieved with this line. If we wanted to do something else with the misplaced rows, this is the place to do it. If we wanted to delete every third row entirely, then the line should’ve been: Selection.Entirerow.delete.

  5. This line tells Excel that there are no more actions within the loop. In this case, 2 and 5 are the frame of the loop and 3 and 4 is the actions within the loop.

When we run this macro, it will result in a neat dataset without any misplaced rows.

Adding Logic to VBA

Logic is what brings a piece of code to life by making it more than just a machine that can do simple actions and repeat itself. Logic is what makes an Excel-sheet almost human—it lets it make intelligent decisions on its own. Let’s use that to automate things!

This section is about IF-statements which enables the «if-this-then-that» logic, just like the IF-function in Excel.

Let’s say the export from our website CMS was even more erroneous than expected. Every third row is still misplaced, but now, some of the misplaced rows are placed 2 columns to the right instead of 1 column to the right. Take a look at the sheet «IF-statement» in the project file to see what it looks like.

How do we take this into account in our macro? We add an IF-statement to the loop!

Let’s formulate what we want Excel to do:

We start in cell A1. Then we go three rows down (to cell A4, A7, A10, etc.) until there’s no more data. Every time we go three rows down we check this row to see if the data has been misplaced by 1 or 2 columns. Then move the data in the row either 1 or 2 columns to the left.

Now, let’s translate this into VBA code. We’ll start with a simple loop, as before:

Excel Macro add loop

The only thing we need now is to write what should happen within the loop. This is the «go three rows down» part that we developed back in the section about loops. Now we’re adding an IF-statement that checks how much the data is misplaced and corrects it correspondingly.

This is the final code to copy into your module editor, with each step explained below:

Excel Macro if code

  1. This is the first part of the IF-statement. It says that if the cell right of the active cell (or Activecell.Offset(0,1) in VBA code) is blank (represented by = "") then do something. This something is the exact same action as we did when we created the loop in the first place: deleting the active cell, and moving the active row one cell to the left (accomplished with the Selection.Delete Shift:=xlToLeft code). This time, we do it two times instead of one, because there are two blank cells in the left side of the row.

  2. If the above is not true, and the cell right of the active cell is not blank, then the active cell is blank. Therefore, we only need to delete the active cell and move the active row one cell to the left one time.

The IF-statement must always end with an End If to tell Excel it’s finished running. After the IF-statement, the loop can run again and again, repeating the IF-statement each time

Congratulations, you’ve just created a macro that can clean up messy data! See the animation below to see it in action (If you haven’t already tried it yourself).

example macro running in Excel

Automate Excel Without Macros

Zapier Excel Integrations

Excel macros have only one problem: they’re tied to your computer, and they can’t run in the Excel Web App or on your mobile device. And they’re best at working on data already in your spreadsheet, making it difficult to get new data from your other apps into your spreadsheet.

App integration tool Zapier can help. It connects the Office 365 for Business edition of Excel to hundreds of other apps—Stripe, Salesforce, Slack, and more—so you can log data to your spreadsheet automatically or start tasks in other apps right from Excel.

Here’s how it works. Say you want to save your Typeform form entries to an Excel spreadsheet. Just create a Zapier account, and click the Make a Zap button in the top right corner. Then, select Typeform in the app picker, and set it to watch your form for new entries.

Zapier Typeform

Zapier can watch your Typeform form for new entries

Test your Zap, then click Continue to add another step to your Zap. This time we’ll select the Excel app, and choose to Add a Row to our spreadsheet. You could also update a row, or search your spreadsheet for a specific row if you wanted.

Add row to Excel spreadsheet

Zapier lets you add, update, or find rows in your Excel spreadsheet

Now, choose your spreadsheet and worksheet, then click the + icon on the right of each spreadsheet row to select the correct form field to save to that spreadsheet row. Save and test your Zapier integration, then turn it on. Then every time your Typeform form gets filled out, Zapier will save that data to your Excel spreadsheet.

Zapier excel integration

Zapier can add your form data directly to the spreadsheet row you want

Here are some great ways to get started automating Excel with Zapier in a few clicks—or build your own Excel integrations to connect your spreadsheets to your favorite apps.

Manage Your Spreadsheet Data

Save Form Entries to an Excel Spreadsheet

Log Data to an Excel Spreadsheet

Do Work From Your Spreadsheet


Go Build Your Own Macros!

Now you’ve learned some of the most essential VBA tools to make a macro for cleaning up data and automating your work. Play around with the tricks and tools you’ve just learned, because they are the fundamentals for automation in VBA. Remember to use the macro recorder (and Google) when you feel you are in over your head.

To learn more, here are some extra resources to help you get the most out of Excel Macros:

  • Learn more about how to repeat VBA code with loops

  • Dig deeper into what you can do with if statements and other logic jumps in Excel Macros

  • Explore Microsoft’s Excel VBA Reference to dig into everything you can do with VBA code and macros.

  • Use Google Sheets instead of Excel? Check out our guide to Google Apps Script to learn how to automate Google Sheets

  • If you run into problems, here’s how to fix the most common errors in Excel.

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

Понравилась статья? Поделить с друзьями:
  • What are excel file types
  • What are excel data tables created from
  • What are excel add ins
  • What are error bars in excel
  • What are elephant word