In microsoft excel what is a macro

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

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

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

How?

Icon image

Before you record a macro    

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

Developer tab on the ribbon

Icon image

Record a macro    

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

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

    Record Macro

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

  4. On the Developer tab, click Stop Recording.

    Stop Recording

Icon image

Take a closer look at the macro    

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

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

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

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

Next steps

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

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

How?

Icon image

Before you record a macro    

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

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

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

Icon image

Record a macro    

  1. On the Developer tab, click Record Macro.

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

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

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

Icon image

Take a closer look at the macro    

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

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

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

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

Need more help?

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

Need more help?

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

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

Macros are a great tool to automate repetitive tasks in Excel. By implementing key macros into your spreadsheet, not only do you streamline the production and management of your data through automation, but you also avoid tasking manual inputs, such as dealing with complex formulas. Overall, macros are a great solution to greatly reducing your turnaround and human effort.

In this article, we’ll show you how to use macros in Excel to automate your workflow. You’ll learn how to make, build or create your own macros in Excel and how to add macros in Excel, so you can get the best custom functionality to automate the processes that will make your work life easier.

What are macros in Excel?

A macro is an action or a group of actions that will complete automatically according to your specifications.

Macros (Microsoft Office Macros) are a very powerful tool for automating predictable, repetitive tasks in your office workflow. A macro is a piece of Visual Basic for Applications (VBA) code that is saved inside your document. Once you know how to use (and create) them, you’ll find you can apply macros to a wide range of tasks to free up time to focus on the deep work that will really set your business apart.

There are many different circumstances in which you’d want to use macros to automate parts of your work. Here are just some examples:

  • Changing the style and formatting of your data.
  • Creating new documents.
  • Linking with other data sources (databases, text files, and more).
  • Altering data and text.

If you’ve never used macros before, then using Layer might be the best alternative for you — Layer is an easy-to-use automation tool that can achieve the same as macros and more in just a few simple steps.

Transfer Data From One Excel Worksheet to Another Automatically

Excel worksheets or workbooks can be linked to automatically update data. Here’s how to transfer data from one Excel worksheet to another automatically

READ MORE

Transfer Data From One Excel Worksheet to Another Automatically

How to create macros in Excel?

Before you can start using macros in Excel, you need to create one. Here’s how.

Let’s say you want your workbook to automatically total the data from each row and the format and style to be consistent for all your workbooks. Instead of wasting time on these tedious actions, you can build a macro to do this for you without the risk of human error.

  1. 1. Open your Excel workbook containing your data. In the toolbar, click View > Record Macro.

How to Use Macros in Excel Record Macro

How to Use Macros in Excel — Record macro

  1. 2. Name your macro (one word only, no spaces). You can also choose to assign a keyboard shortcut for your macro and add a description (here, you can add anything such as an overview of what the macro does or when you should use it). Click “Ok”.

How to Use Macros in Excel Name Macro

How to Use Macros in Excel — Name macro

  1. 3. Now carry out all of your desired actions. The macro will record everything you do. Here is an example of the changes I want to make to my Excel; adding a new column for total sales, adding currency formatting to my columns, and formatting the header rows. You can also add formulas and other numbers, text, and cell formatting to your dataset.

How to Use Macros in Excel Create new macro

  1. 4. Once you have applied all of your changes, click “Stop recording” in the “View” menu.

How to Use Macros in Excel Stop recording macro

Please note: An alternative way to stop recording a macro is to click the icon in the bottom or top left-hand corner of your workbook (depending on whether you have the Excel app or the online version).

How to use macros in Excel?

Before you can use the macro you’ve just created, it’s vital that you perform the following steps; delete your cells, then save the file in a macro-enabled format.

You must delete your data before saving as, otherwise, when you run the macro, it will remember this specific data and add it to any future workbooks. Deleting this data now means that the macro will only remember the actions, not the data.

You then have to save the workbook in a macro-enabled format — ideally XLTM. If you save it as another format, like XLTX, the macros won’t be able to run.

  1. 1. Select all of your data and delete your cells. Right-click and select “Delete” — this is the only way to delete all values and formatting.

How to Use Macros in Excel Save macro

  1. 2. Save as a macro-enabled format by heading to File > Save as. Choose the “Excel Macro-enabled Template” (XLTM) or a macro-supportive alternative. Click “Save”.

How to Use Macros in Excel Save macro file XLTM

How to run macros in Excel?

Depending on how you assign it, you may be able to run macros by pressing a combination short-cut key, a button on the Quick Access Toolbar, or in a custom group on the control ribbon. You can also assign a macro to run automatically when you open your Excel workbook.

Now that you’ve created a macro-enabled template, it’s time to run it. Here’s how:

  1. 1. Open your newly-created Excel template file. With standard security settings, you will see a warning notification stating that macros are disabled. You should click “Enable Macros”.

How to Use Macros in Excel Enable macros Excel

Please note: You may not always want to enable content. If you receive a file from a third party, for example, they may be running a macro that could damage or delete your data. This one is safe, however, as we created it ourselves.

  1. 2. Import your data into the workbook. You can import from another Excel file or other formats like CSV. In the toolbar, click Data > Get Data and choose the option that best suits your needs.

How to Use Macros in Excel Import data macro excel

In this example, I’ll select “Get Data…” to import data from another Excel file. Once I’ve located my Excel file, I’ll click “Get data”.

How to Use Macros in Excel Macros in Excel

How to Use Macros in Excel — Macros in Excel

  1. 3. Click the checkbox of the sheet(s) you want to import. When finished, click the “Load” button on the bottom-left-hand corner of the screen.

How to Use Macros in Excel Get data macros

  1. 4. Now that your data is in the spreadsheet, go to View > View Macros. Click on the macro you created previously and click “Run”.

How to Use Macros in Excel Run macro Excel

Alternatively, if you added a keyboard shortcut for your macro, press the combination now to run the Macro.

As you can see from the screenshot below, the macro has automatically applied the actions previously recorded. My new data now has a new ‘Total monthly sales’ column, currency formatting has been applied to my columns, and the headers have also been formatted.

How to Use Macros in Excel Build and run macro

Want to Boost Your Team’s Productivity and Efficiency?

Transform the way your team collaborates with Confluence, a remote-friendly workspace designed to bring knowledge and collaboration together. Say goodbye to scattered information and disjointed communication, and embrace a platform that empowers your team to accomplish more, together.

Key Features and Benefits:

  • Centralized Knowledge: Access your team’s collective wisdom with ease.
  • Collaborative Workspace: Foster engagement with flexible project tools.
  • Seamless Communication: Connect your entire organization effortlessly.
  • Preserve Ideas: Capture insights without losing them in chats or notifications.
  • Comprehensive Platform: Manage all content in one organized location.
  • Open Teamwork: Empower employees to contribute, share, and grow.
  • Superior Integrations: Sync with tools like Slack, Jira, Trello, and more.

Limited-Time Offer: Sign up for Confluence today and claim your forever-free plan, revolutionizing your team’s collaboration experience.

Conclusion

Although macros are not widely known or used by the majority of Excel users, they are an incredibly intelligent feature that could streamline the day-to-day operations of many Excel users. What’s more, we’ve seen that macros aren’t as intimidating to set up and run as they might seem.

Here we’ve shown how you can create/record macros in your spreadsheet, how to save them correctly, and how to run them on other datasets. Finally, we’ve also shown how this process can be even easier and more intuitive with Layer.

Looking for more articles on how to make the most of Excel? Take a look at how to transfer data from one Excel worksheet to another automatically.

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.

In this tutorial, we will learn to record macros in Excel. Macros are used to record data in order to carry them forward to a new sheet or file. They can help you save a huge amount of time by enabling you to create a data structure or an entire database only once.

Don’t worry if you don’t understand how to use them because, by the end of this article, you will know what a macro is, how to record a macro, and of course, how to use them.

Also read: [Step-by-Step] How to Create a Flowchart in Excel?

What is a Macro in Microsoft Excel?

A macro, as mentioned above, is used to record activity in a sheet which can be run in a different sheet or file again without you having to repeat the activity.

For example, you’re an accountant whose job is to create ledgers and financial accounts, or balance sheets in Excel. You can simply start recording a macro, create the balance sheet structure once, and run that macro again on a fresh sheet or file to apply the same structure you previously created to save time.

There are a lot of such activities undertaken in Excel that involve the repetition of tasks that consume a huge amount of time and effort.

Learn to record and use macros with the help of this tutorial and stop wasting your time again!

Let’s get started with learning to record macros in Excel with the help of suitable images and examples.

1. Recording a macro in Excel

  • Open an Excel file.
  • Click on the record macro icon in the status bar below.
  • Or, go to the View tab.
  • Pull down on the Macros button and select Record Macro.
  • A window named Record Macro opens.
Record Macros in Excel
Creating a Macro
  • Name your macro in the Macro Name dialogue box, for example- Attendance Sheet.
  • Set a unique shortcut key to run this macro in a new sheet or file, for example- CTRL+SHIFT+U
  • In the Store macro in, select Personal Macro Workbook to apply macros in any new Excel file or sheet (Recommended).
  • Select New Workbook to apply macros in a specific new Excel file.
  • Select This Workbook to apply macros in a new sheet in the same file.
  • Click OK to start recording.
  • Notice the macro icon in the status bar changes to a square icon.
Record Macros in Excel
Recording Macros from View Tab
record statusbar
Recording Macros from Status Bar

2. Preparing a data structure while recording macros

Now that a macro has begun recording, it means that whatever activity you do in that Excel sheet is being recorded.

Note- Make sure to start making changes you want to carry forward only after a macro has begun recording and not before or after that.

  • Start preparing the data structure you want to record and carry forward.
  • You can add border styles, repetitive headings, rows, text or cell colors, and various other formatting options.
  • Here is a sample data structure that we created while a macro was recording.
data structure
Recorded Data Structure

3. Steps to stop recording a macro

To stop the recording, follow the steps below.

  • Click on the square icon in the status bar.
  • Or, go to the View tab.
  • Click Stop Recording in the dropdown options under Macros.
Record Macros in Excel
Stop Recording a Macro

4. Running a macro in a new file or sheet

After you create macros in Excel, it’s time to run this macro in a new file to check if it has properly recorded our data structure.

  • Open a new Excel file or press CTRL+N.
  • Press the shortcut keys you created to run macros. For example- CTRL+SHIFT+U.
  • Or, go to the View tab.
  • Pull down on the Macros and select View Macros or press ALT+F8.
  • You should be able to see the name of the macros you created here.
  • Click Run to run a macro.

Note- If Excel shows an error message on running macros in a new sheet, click Unhide in the View tab under the Window group. You can then run the macro either in the same workbook or in the new workbook named Personal that opens after clicking unhide.  

macro ran
Macro in a New File

You can see that the macro has run in a new Excel file successfully.

5. Deleting a macro in Excel

To delete a macro in Excel, do as follows next.

  • Open an Excel file.
  • Go to the View tab.
  • Pull down on Macros in the Macro group.
  • Select View Macros.
  • Select the macro you want to delete in the Macro window.
  • Click Delete to delete a macro.
macro deleted
Macro Deleted

You can see that the selected macro has been deleted permanently from Excel.

Conclusion

This tutorial was all about recording, running, and deleting macros in Microsoft Excel. Drop your comments below if you have any doubts regarding macros in Excel. Stay tuned for more informative tutorials like this!

Понравилась статья? Поделить с друзьями:
  • Impossible is just big word
  • In each line choose one word which does not usually go
  • Impossibility is a word
  • In each line choose one word that
  • In each line choose one word hook tentacle