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?
|
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.
|
|
Record a macro
|
|
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?
|
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:
|
|
Record a macro
|
|
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?
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
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
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
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
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
Check the «Developer» box. This box is near the bottom of the «Main Tabs» list of options.
-
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.
Advertisement
-
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
Click the Developer tab. It’s at the top of the Excel window. Doing so opens a toolbar here.
-
3
Click Record Macro. It’s in the toolbar. A pop-up window will appear.
-
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
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
Click the «Store macro in» drop-down box. It’s in the middle of the window. Doing so prompts a drop-down menu.
-
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
Click OK. It’s at the bottom of the window. Doing this saves your macro settings and begins recording.
-
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
Click Stop Recording. It’s in the Developer toolbar. This will save your macro.
Advertisement
-
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
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
Click Save As. This option is on the left side of the window (Windows) or in the drop-down menu (Mac).
-
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
Enter a name for your Excel file. In the «Name» text box, type in the name for your Excel spreadsheet.
-
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
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
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.
Advertisement
-
1
Open the macro-enabled spreadsheet. Double-click the spreadsheet that has the macro in it to open the spreadsheet in Excel.
-
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
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
Click Macros. You’ll find it in the Developer tab’s toolbar. A pop-up window will open.
-
5
Select your macro. Click the name of the macro which you want to run.
-
6
Click Run. It’s on the right side of the window. Your macro will begin running.
-
7
Wait for the macro to finish running. Depending on how large your macro is, this can take several seconds.
Advertisement
Add New Question
-
Question
Can I use a macro that I create in other spreadsheets and future spreadsheets on the same pc?
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?
You will first need a basic understanding of VBA. There are many tutorials on this.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Video
-
Macros are generally useful for automating tasks which you must perform often, such as calculating payroll at the end of the week.
Thanks for submitting a tip for review!
Advertisement
-
Although most macros are benign, some macros can maliciously change or delete information on your computer. Never open a macro from a source which you don’t trust.
Advertisement
About This Article
Article SummaryX
1. Enable Developer options in Excel.
2. Click the Developer tab.
3. Click Record Macro.
4. Enter the macro name and details.
5. Click OK.
6. Perform the macro’s steps.
7. Click Stop Recording.
Did this summary help you?
Thanks to all authors for creating a page that has been read 710,278 times.
Is this article up to date?
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.
Contents
- 1 How do you use macros in Excel?
- 2 What can Excel macros do?
- 3 What is macros in Excel for beginners?
- 4 What are the steps to run a macro?
- 5 What is VBA in Excel?
- 6 How do I run a macro line by line?
- 7 When should I use macros?
- 8 What is the difference between VBA and macros?
- 9 What is macro explain with example?
- 10 How do I write VBA code in Excel?
- 11 Is VBA worth learning?
- 12 Where is macros in Excel?
- 13 How do you check if macros are running in Excel?
- 14 Is VBA difficult to learn?
- 15 Is VBA obsolete?
- 16 What is Vlookup in Excel?
- 17 How do I debug a macro in Excel?
- 18 What does step into macro mean?
- 19 Which items can be entered when we record a macro?
- 20 What are the disadvantages of macros?
How to Run a Macro in Excel
- Click the Insert tab.
- In the Illustrations group, click on the Shapes icon.
- Click anywhere on the worksheet.
- Resize/Format the shape the way you want.
- Right-click on the shape and select the Assign Macro option.
What can Excel macros do?
Macros are programs used to automate frequently used processes or tasks in Excel. A macro records operations and re-uses the sequence of mouse actions or keystrokes of anything you can do in Excel with keystrokes or a mouse.
What is macros in Excel for beginners?
An Excel macro is an action or a set of actions that you can record, give a name, save and run as many times as you want and whenever you want. Macros help you to save time on repetitive tasks involved in data manipulation and data reports that are required to be done frequently.
What are the steps to run a macro?
Right-click the macro in the Navigation Pane, and then click Design View. On the Design tab, in the Tools group, click Single Step. Click Run. If the macro is a new or edited macro, you will be prompted to save the macro before you can run it.
What is VBA in Excel?
VBA stands for Visual Basic for Applications. Excel VBA is Microsoft’s programming language for Excel.and all the other Microsoft Office programs, like Word and PowerPoint. The Office suite programs all share a common programming language.
How do I run a macro line by line?
F8 is the key! In the visual basic editor, place your cursor inside of the macro and hit F8. This will run the first line of your code. Hit F8 to run each additional line, or F5 to resume without stopping.
When should I use macros?
A macro is used to automate a task that you perform repeatedly or on a regular basis. It is a series of commands and actions that can be stored and run whenever you need to perform the task. You can record or build a macro and then run it to automatically repeat that series of steps or actions.
What is the difference between VBA and macros?
The main difference between VBA and Macro is that VBA is the programming language to create Macros while Macros are programming codes that run on Excel environment to perform automatic routine tasks.VBA and Macro are two terms related to Excel. Macro is a way of representing multiple instructions.
What is macro explain with example?
Macro is defined as something that covers a large amount, or is large in size. An example of macro is the study of the key driving aspects of an economy; macro economics. An example of macro is a very close up photograph of an ant; a macro photograph. adjective.
How do I write VBA code in Excel?
Insert VBA code to Excel Workbook
- Open your workbook in Excel.
- Press Alt + F11 to open Visual Basic Editor (VBE).
- Right-click on your workbook name in the “Project-VBAProject” pane (at the top left corner of the editor window) and select Insert -> Module from the context menu.
- Copy the VBA code (from a web-page etc.)
Is VBA worth learning?
VBA is worth learning if you plan to work mostly with MS-office programs and want to automate the Excel process and exchange data to and from Office applications. If you want to focus on a broader work environment, other languages such as Python could be more useful.
Where is macros in Excel?
Open Microsoft Excel, click Menus tab, you can get back the classic style interface. Then, just go to the familiar Tools menu, you will find the Macro function listed in the drop down menu.
How do you check if macros are running in Excel?
Click the File tab. Click Options. Click Trust Center, and then click Trust Center Settings. In the Trust Center, click Macro Settings.
Is VBA difficult to learn?
With the right training, learning Microsoft VBA is easy. The Microsoft VBA Introduction course makes it easy to learn VBA primarily for Excel. There’s also an Advanced VBA training course if you’re looking for a higher difficulty level.
Is VBA obsolete?
NET Visual Basic is no longer supported or updated by Microsoft, the VBA programming language was upgraded in 2010 with the introduction of Visual Basic for Applications 7 in Microsoft Office applications.
Visual Basic for Applications.
Paradigm | Multi-paradigm |
Developer | Microsoft |
First appeared | 1993 |
Stable release | 7.1 (Office 2019) |
Influenced by |
---|
What is Vlookup in Excel?
VLOOKUP stands for ‘Vertical Lookup’. It is a function that makes Excel search for a certain value in a column (the so called ‘table array’), in order to return a value from a different column in the same row.
How do I debug a macro in Excel?
Debugging
- Empty the range A1:E2.
- Press F8 four times.
- Press F8 two more times.
- Single step through the rest of the code to see how Excel VBA enters the other numbers.
- Click on the green arrow to execute the macro until the breakpoint.
- Only part of the macro (for i = 1) has been executed.
What does step into macro mean?
The Step Into button on the Debugging toolbar allows you to execute the macro line by line. The active line of code which is about to be executed will be highlighted in yellow.
Which items can be entered when we record a macro?
When you record a macro, the macro recorder records all the steps in Visual Basic for Applications (VBA) code. These steps can include typing text or numbers, clicking cells or commands on the ribbon or on menus, formatting cells, rows, or columns, or even importing data from an external source, say, Microsoft Access.
What are the disadvantages of macros?
The disadvantage of the macro is the size of the program. The reason is, the pre-processor will replace all the macros in the program by its real definition prior to the compilation process of the program.
#Руководства
- 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» и выбираем пункт «Параметры…».
Скриншот: 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
Узнать больше
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.
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
2. Next, click on the Macros button on the right side of the View ribbon
3. This will open the Macros drop-down.
Click Record Macro.
4. Enter a name for your macro, something like Hide_Columns.
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.
For this Excel macro tutorial, you only need to save the macros in the current Excel file.
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.
6. Then select Column I and press Ctrl + Shift + Right Arrow to include all remaining columns on the right.
7. Right-click on the highlighted Column Bar then click on Hide.
Your worksheet should now look like this:
To end the macro recording:
8. On the View ribbon, click on Macros and select Stop Recording.
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.
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.
3. The VBA code editor opens.
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.
2. This opens the Customize Ribbon window.
On the right side, check the Developer tab checkbox.
3. You should now see the Developer tab.
To start recording the Unhide macro:
1. Click on the Record Macro button in the Developer tab.
2. Name this macro Unhide_Columns.
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.
6. Click on the Stop Recording macro button to finish up.
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.
2. In the Macro window, select the macro Hide_Columns and click on Run.
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.
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.
2. To create a button, click on Insert > Illustrations > Shapes.
Then select the Rectangle.
3. Draw a rectangle and format it as you’d like. Label it “HIDE”.
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.
5. In the Assign Macro window, select Hide_Columns and click OK.
The Hide button now works!
Now, do the same for the Unhide_Columns macro.
6. Create another rectangle button and label it “UNHIDE”.
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.
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.
2. On the Developer tab, toggle ON the Use Relative References button.
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.
4. Name the macro Mark_Interested.
Then assign a shortcut key. For example, Ctrl + Q.
Click OK. The recording has now started.
4. Highlight the row of the Active Cell using the keyboard shortcut Shift + Space Bar.
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.
5. Apply the formatting:
- Fill using the color Green
- Change font color to White
6. End the macro recording from the Status Bar
All done!
Try to use the shortcut Ctrl + Q to quickly apply formatting to entire rows.
Saving macro-enabled workbooks
If you save the practice workbook, this window will pop up:
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
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.
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:
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:
- In the upper-left corner, click the File tab and then select Options:
- In the Excel Options window, select Trust Center and then click Trust Center Settings:
- In the Trust Center, go to Macro Settings and then select Enable all 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:
If you want to create new macros, you need to enable the Developer tab first.
To enable the Developer tab:
- In the upper-left corner, click the File tab and then select Options.
- In the Excel Options window, select Customize Ribbon and then enable the Developer checkbox in the Main Tabs area:
- 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.
How to delete macros in Excel
To delete a macro in Excel:
- Open the Macro window in one of the following ways:
- Press Alt+F8.
- Select the Developer tab and click Macros.
- Select the macro that you want to delete and click Delete.
- 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:
- In the upper-left corner, click the File tab and then select Options.
- In the Excel Options window, select Trust Center and then click Trust Center Settings.
- 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.
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:
- In the Developer tab, click Record Macro:
- Enter the macro name and click OK:
Excel will start recording the macro.
- Perform the actions, that need to be included in the macro, then click Stop Recording:
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:
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:
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:
- In the Developer tab, click Visual Basic:
- In the VBA project tree, double-click the module with the macro that you want to edit:
- 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:
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:
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.
-
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
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.
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.”
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
Step 3) Developer Tab
You will now be able to see the DEVELOPER tab in the ribbon
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
Step 5) Record Macro
- Click on the DEVELOPER tab
- Click on Record Macro as shown in the image below
You will get the following dialogue window
- Enter ImportBankReceipts as the macro name.
- Step two will be there by default
- Enter the description as shown in the above diagram
- 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
- Go to the local drive where you have stored the CSV file
- Select the CSV file
- Click on Import button
You will get the following wizard
Click on Next button after following the above steps
Follow the above steps and click on next button
- Click on Finish button
- Your workbook should now look as follows
Step 7) Format the Data
Make the columns bold, add the grand total and use the SUM function to get the total amount.
Step 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
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
- 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
- Select ImportBankReceipts
- Highlights the description of your macro
- Click on Run button
You will get the following data
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.
Watch Video – How to Run a Macro in Excel
In Excel, you can create a macro by recording it or by writing code in the VB editor.
Once created, you need to run the macro.
In this tutorial, I’ll show you different ways to run a macro in Excel.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
How to Run a Macro in Excel
For the purpose of this tutorial, let’s say we have a macro named ‘ColorCell’ with the following code:
Sub ColorCell()
Range("A1").Interior.Color = vbRed
End Sub
This one line code would fill the cell A1 of the active sheet with red color.
Now let’s see various ways to run this macro in Excel.
Run the Macro by Clicking on a Shape
One of the easiest ways to run a macro is to have a button in the worksheet and click that button to execute the macro.
It’s easy and intuitive.
The benefit of this method is that it makes it really easy and intuitive for anyone to run the macro. Even if you share the workbook with someone who has no knowledge of VBA, he/she can just click on the button and see the actions take place (without even knowing what happens in the back end).
Something as shown below:
Here are the steps to do this:
That’s it! Now the shape would work as a button and whenever you click on it, it will run the assigned macro.
Run Macro By Clicking a Button
While the shape is something you can format, a button has a standard format.
Here is how it looks:
You can assign a macro to a button and then can run the macro by simply clicking that button.
Here are the steps to assign a macro to a button:
The button inserted using this technique is a standard one and you can’t change the formatting of the button (unlike shapes, where you can change practically everything).
However, you can change the text of the button. To do this, right-click on it and select Edit Text.
Note: You can also assign a macro to other interactive controls, such as a checkbox or scrollbar.
Run a Macro from the Ribbon (Developer Tab)
If you have multiple macros in the workbook, you can see a list of all the macros in the Macros dialogue box. It makes it easy to run multiple macros from a single place.
Here are the steps:
Run a Macro from the VB Editor
If you are the one writing and testing macros, then instead of inserting buttons, you can directly run a macro from the VB Editor.
Here are the steps:
- Select any line within the code in the code window. If you have multiple macros/subs, make sure your cursor is in the macro that you want to run.
- Go to the toolbar and click on the Green triangle icon (you can also use the keyboard shortcut – F5).
As soon as you do this, the macro would be executed.
If you only have the VB Editor open (and you can’t see the worksheet), you may not see the change happening in the worksheet. You can minimize the VB Editor screen and then run the macro to see the changes in real-time.
You May Also Like the Following Excel VBA Tutorials:
- Working with Cells and Ranges in Excel VBA.
- Working with Worksheets in VBA.
- Working with Workbooks in VBA.
- Using Loops in Excel VBA.
- Using IF Then Else Statement in Excel VBA.
- Creating User-Defined Functions in Excel.
- Excel VBA Events – An Easy (and Complete) Guide.
- How to Create and Use Personal Macro Workbook in Excel.
- 24 Useful Excel Macro Examples.
- How to Create and Use an Excel Add-in.
- Guide to Using For Next Loop in Excel VBA
- How to Enable Macros in Excel?