Excel для Microsoft 365 Excel для Microsoft 365 для Mac Excel 2021 Excel 2021 для Mac Excel 2019 Excel 2019 для Mac Excel 2016 Excel 2016 для Mac Excel 2013 Excel 2010 Excel 2007 Excel Starter 2010 Еще…Меньше
Существует несколько способов запуска макроса в Microsoft Excel. Макрос — это действие или набор действий, с помощью которых можно автоматизировать различные задачи. Макрос записывется на Visual Basic для приложений программирования. Макрос всегда можно запустить, нажав кнопку Макрос на вкладке Разработчик на ленте. В зависимости от того, как макрос назначен для запуска, его также можно запустить, нажав сочетание клавиш сочетание клавиш, нажав кнопку на панели быстрого доступа или в настраиваемой группе на ленте либо щелкнув объект, рисунок или элемент управления. Кроме того, макрос можно запускать автоматически при запуске книги.
Перед запуском макроса
Перед началом работы с макросами следует включить вкладку Разработчик.
-
Чтобы Windows, перейдите в меню Параметры > >Настроить ленту.
-
Для Macперейдите на Excel > параметры… >ленты & панели инструментов.
-
Затем в разделе Настройка ленты в разделе Основныевкладки, в разделе Разработчик, нажмите кнопку ОК.
-
Откройте книгу, содержащую нужный макрос.
-
На вкладке Разработчик в группе Код нажмите кнопку Макросы.
-
В поле Имя макроса выберите макрос, который вы хотите запустить, и нажмите кнопку Выполнить.
-
У вас также есть другие варианты:
-
Параметры: добавление сочетания клавиш или описания макроса.
-
Шаг. Откроется Visual Basic редактора в первой строке макроса. Нажатие F8 позволит вам по одной строке пролиться между кодами макроса.
-
Изменить. Откроется редактор Visual Basic и вы сможете при необходимости изменить код макроса. После внесения изменений можно нажать F5, чтобы запустить макрос из редактора.
-
Вы можете добавить сочетание клавиш в макрос при его записи, а также добавить его к существующему макросу:
-
На вкладке Разработчик в группе Код нажмите кнопку Макросы.
-
В поле Имя макроса выберите макрос, который нужно назначить сочетанием клавиш.
-
Нажмите кнопку Параметры.
Откроется диалоговое окно Параметры макроса.
-
В поле Сочетания клавиш введите любую букву в нижнем или верхнем регистре, которую вы хотите использовать с сочетаниями клавиш.
Примечания:
-
Для Windowsклавиша для букв в нижнем регистре — CTRL+letter. Для букв верхнего регистра это CTRL+SHIFT+Letter.
-
Для Macдля букв в нижнем регистре есть клавиши OPTION+COMMAND+LETTER,но клавиши CTRL+letter также будут работать. Для букв верхнего регистра это CTRL+SHIFT+Letter.
-
Будьте внимательны при назначении ярлыков, так как они будут переопределять все эквивалентные стандартные Excel, пока открыта книга с макросом. Например, если назначить макрос CTRL+Z,вы потеряете возможность отменить. В связи с этим обычно лучше использовать клавиши CTRL+SHIFT+БУКВА С верхнего регистра, например CTRL+SHIFT+Z, для которых в Excel нет эквивалентных Excel.
Список сочетаний клавиш CTRL, которые уже назначены в Excel, см. в статье Excel сочетания клавиш и клавиши для работы с функцией.
-
-
Введите описание макроса в поле Описание.
-
Нажмите кнопку ОК, чтобы сохранить изменения, а затем — кнопку Отмена, чтобы закрыть диалоговое окно Макрос.
Чтобы запустить макрос нажатием кнопки на панели быстрого доступа, сначала необходимо добавить соответствующую кнопку на панель. Для этого см. назначение макроса кнопке.
Вы можете создать пользовательскую группу, которая появится на вкладке ленты, а затем назначить макрос кнопке в этой группе. Например, можно добавить настраиваемую группу «Мои макросы» на вкладку Разработчик, а затем добавить в новую группу макрос (который отображается как кнопка). Для этого см. назначение макроса кнопке.
Запуск макроса путем щелчка области графического объекта
Вы можете создать хот-спот на графическом элементе, который пользователи могут щелкнуть, чтобы запустить макрос.
-
На компьютере вставьте графический объект, например рисунок, или нарисуйте фигуру. Распространенный сценарий — нарисовать фигуру Скруглённый прямоугольник и отформатировали ее так, чтобы она выглядела как кнопка.
Чтобы узнать о вставке графического объекта, см. добавление, изменение и удаление фигур.
-
Щелкните правой кнопкой мыши созданный хот-спот и выберите пункт Назначить макрос.
-
Выполните одно из указанных ниже действий.
-
Чтобы назначить существующий макрос графическому объекту, дважды щелкните макрос или введите его имя в поле Имя макроса.
-
Чтобы записать новый макрос для назначения выбранному графическому объекту, нажмите кнопку Запись ,в диалоговом окне Запись макроса введите имя макроса и нажмите кнопку ОК, чтобы начать запись макроса. Завершив запись макроса, нажмите кнопку Остановить на вкладке Разработчик в группе Код.
Совет: Вы также можете нажать в левой части панели состояния.
-
Чтобы изменить существующий макрос, щелкните его имя в поле Имя макроса и выберите изменить.
-
-
Нажмите кнопку ОК.
На вкладке Разработчик нажмите кнопку Visual Basic, чтобы запустить редактор Visual Basic(VBE). Перейдите Project проводнике, чтобы найти модуль, содержащий макрос, который вы хотите запустить, и откройте его. Все макрос в этом модуле будут перечислены в области справа. Выберите макрос, который вы хотите запустить, разместив курсор в любом месте макроса и нажимая F5или выбрав в меню пункт Выполнить > Макрос.
Создайте Workbook_Open события.
В следующем примере событие Open используется для запуска макроса при открытии книги.
-
Откройте или создайте книгу, в которую нужно добавить макрос.
-
На вкладке Разработчик в группе Код нажмите кнопку Visual Basic.
-
В окне Project проводника щелкните правой кнопкой мыши объект ThisWorkbook и выберите просмотр кода.
Совет: Если окно Project проводника не отображается, в меню Вид выберите пункт Project проводник.
-
В списке Объект над окном Код выберите книга.
При этом автоматически создается пустая процедура для события Open, например:
Private Sub Workbook_Open()
End Sub
-
Добавьте в процедуру следующие строки кода:
Private Sub Workbook_Open()Листы даты
MsgBox(«Лист1»).
Диапазон(«A1»). Value = Date
End Sub -
Переключитесь на приложение Excel и сохраните данную книгу как книгу с поддержкой макросов (.XLSM).
-
Закройте и снова откройте книгу. При повторном запуске книги Excel выполняется процедура Workbook_Open, в которой в окне сообщения отображается сегодняшняя дата.
-
В окне сообщения нажмите кнопку ОК.
Примечание: Ячейка A1 на листе «Лист1» также содержит дату в результате Workbook_Open процедуры.
Дополнительные сведения
Вы всегда можете задать вопрос специалисту Excel Tech Community или попросить помощи в сообществе Answers community.
К началу страницы
См. также
Автоматический запуск макроса при открытии книги
Автоматизация задач с помощью средства записи макросов — Excel
Запись макроса для открытия определенных книг при запуске Excel
Создание и сохранение всех макросов в одной книге
Сохранение макроса
Нужна дополнительная помощь?
Do you want to learn how to run a VBA macro in Microsoft Excel? This guide will show you all the methods you can use to run your VBA code.
Microsoft Excel is a powerful spreadsheet application that offers users a variety of features and capabilities. One of the most popular features of Excel is the ability to create and run VBA macros.
A macro is a small scripts written in the VBA (Visual Basic for Applications) programming language that can be run in your desktop Excel app.
Macros can save you a lot of time and energy when working in Excel. They can be used to automate tedious tasks and save you hours of work each week.
But in order to leverage this time saving tool, you will need to know how to run your VBA macros.
Follow this guide and you’ll be able to start running macros like a pro in no time!
Run VBA Macro from the Developer Tab
The most common method for running a macro is from the Developer tab in the Excel ribbon.
This tab is hidden by default, so you will need to enable the Developer tab in your desktop Excel app first.
Follow these steps to run a VBA macro from the Developer tab.
- Go to the Developer tab.
- Press the Macros command in the Code section.
This will open the Macro menu which lists all the macros available to run.
- Select the macro which you want to run.
- Press the Run button.
That’s it! Your chosen macro code will now execute!
💡 Tip: Use the Macros in dropdown option to select the location of macros to run. You can select a specific workbook, All Open Workbooks, or This Workbook.
Run VBA from the View Tab
The Macro command is also available in the View tab.
Go to the View tab and press the Macros button to launch the Macros menu.
This opens the same Macro dialog box as before and you can select the macro and press the Run button.
Run VBA Macro from Macro Menu with a Keyboard Shortcut
There is an easier way to open the Macro menu! There’s no need to use the Developer or View tab since there is a dedicated keyboard shortcut to open the Macro menu.
You can use the Alt + F8 keyboard shortcut to open the Macro menu.
Run VBA Macro from a Keyboard Shortcut
You can entirely bypass the Macro dialog box by assigning a keyboard shortcut to your desired Macro.
If this is a macro that you want to use a lot, then assigning a shortcut is a good way to avoid the many clicks needed when running a macro through the Macro menu.
Follow these steps to assign your macro a dedicated keyboard shortcut.
- Open the Macro menu.
- Select the macro to which you want to assign a keyboard shortcut.
- Press the Options button.
This will open up the Macro Options menu where you can add a description for the macro and assign a keyboard shortcut.
- Add a character into the Shortcut key input box.
- Press the OK button in the Macro Options menu.
- Press the Cancel button in the Macros menu.
⚠️ Warning: This chosen shortcut key will override any existing keyboard shortcut, so you should avoid using keys taken by commonly used shortcuts such as copy, paste etc.
A lot of Ctrl and single key combinations are already taken with commonly used commands, so you might want to create a Ctrl + Shift shortcut instead.
💡 Tip: Hold the Shift key while entering a key in the Shortcut key input to create a Ctrl + Shift shortcut.
Run VBA Macro from a Form Control Button
If other people are using your spreadsheet solution, they might not realise they can run your macros to help complete their work.
This is where a button is the preferred choice to run a macro. It makes the act of running your macro easy and obvious!
You can create a Form Control Button to run the macro when you click the button. This can be placed anywhere in the spreadsheet since is floats over top of the grid. This means it won’t interfere with the rest of your data or formulas.
Follow these steps to insert a Form Control Button and assign a macro to it.
- Go to the Developer tab.
- Click on the Insert command.
- Choose the Button option found in the Form Controls section.
This will not actually insert a button yet. You will notice your cursor has now turned into a small black plus sign. This will allow you to draw a button in your sheet.
- Left click and drag anywhere in the sheet.
When you release the click and drag action, the Assign Macro menu will immediately pop up and you will be able to assign your macro to the button.
- Select your macro.
- Press the OK button.
Now you have a button in your sheet which will run your select VBA macro when clicked.
💡 Tip: Righ click on the button and select Edit Text to change the text displayed on the button.
Run VBA Macro from any Shape, Icon, or Image
Form Control buttons are pretty ugly and outdated. They also don’t have many options to customize the look, but thankfully they aren’t the only way to make a button to run your macros!
There are some much more stylish options like using an image, shape, or icon as a button to run your macros.
Follow these steps to assign a macro to any object such as an image, shape, or icon.
- Right click on the object.
- Select Assign Macro option from the menu.
- Select the macro from the Assign Macro menu.
- Press the OK button.
Now when you click on the shape, image, or icon it will execute the macro code!
Run VBA Macro from a Quick Access Toolbar Command
Another option is to add your most frequently used macros to the Quick Access Toolbar.
The Quick Access Toolbar is a customizable set of commands that are always visible so you can easily use them at any time. You can even add a macro so it can be run with a click.
Follow these steps to add a macro to your Quick Access Toolbar.
- Right-click anywhere on the Quick Access Toolbar.
- Select the Customize Quick Access Toolbar option from the menu.
This will open the Excel Options menu on the Quick Access Toolbar section.
- Select Macros from the Choose commands from dropdown.
- Select the macro you want to add to your Quick Access Toolbar.
- Press the Add button.
- Press the OK button.
When you press the Add button you will see the selected macro gets added to your list of commands. You can use the Up and Down arrow buttons to adjust the order this macro will appear in your commands.
💡 Tip: Press the Modify button in the Excel Options to change the icon and label of the macro that will appear in your Quick Access Toolbar!
Now you should have a new icon available in the Quick Access Toolbar. Click on this to run your select macro.
💡 Tip: An easy way to use the commands in your Quick Access Toolbar is with the Alt hotkey shortcuts. In this example, the command is in the 8th position starting from the undo command, so you can press the Alt + 8 to run the macro.
Run VBA Macro from a Custom Ribbon Command
If you have an entire repertoire of macros and you’re running out of room in the Quick Access Toolbar, then adding a custom ribbon tab to organize your macros could be the ideal solution.
Excel allows you to add your own custom ribbons and fill them with your favorite macros as well as any other commands you frequently use.
Follow these steps to add a macro to the Excel ribbon.
- Right click anywhere on the Excel ribbon.
- Select the Customize the Ribbon option from the menu.
This will open the Excel Options menu on the Customize Ribbon section.
- Press the New Tab button to create your new ribbon tab.
- Press the Rename button to give your tab a name.
Each tab will need at least one group, and this is automatically created when you create a new tab. You can also rename the group. Both of these names will be displayed in your Excel ribbon.
Now you will be able to add a macro into the new tab and group.
- Select the Macros option from the Choose commands from dripdown.
- Select the macro which you want to add into the ribbon.
- Press the Add button.
- Press the OK button.
💡 Tip: Select the tab and use the Up or Down arrow buttons to adjust the position of the new tab in your ribbon.
You now have a new custom tab that can hold all your most frequently used macros. 😃
Run VBA Macro from Visual Basic Editor Run Menu
The visual basic editor (VBE) is the environment where you write VBA code, so it makes sense that you should be able to also run your code from it.
A lot of people like to test their code as they develop their solutions and this means frequently running your macros from the the editor. Your current code can always be run from the Run menu in the VBE.
Follow these steps to run your macro from the Run menu in the visual basic editor.
- Select the macro you want to run.
You can select the macro by either placing the cursor in the code or selecting the macro name from the dropdown menu in the top right.
- Go to the Run menu.
- Select the Run Sub/UserForm option from the menu.
This will run your selected macro!
Run VBA Macro from Visual Basic Editor Toolbar
The visual basic editor comes with a toolbar for easy access to the most frequently used commands.
Follow these steps to run your macro from the toolbar.
- Select the macro you want to run.
- Press the Play button in the toolbar.
This will run your selected macro!
📝 Note: If you don’t see this toolbar you might need to enable it. Go to the View menu then Toolbars and check the Standard option.
Run VBA Macro from Visual Basic Editor Keyboard Shortcut
There are a lot of very useful keyboard shortcuts for using the visual basic editor.
Running a macro from the VBE is a very common task, so it’s no surprise there is also a keyboard shortcut available for this.
Press the F5 key while in the VBE and the currently selected macro will run!
Run VBA Macro from Another Macro
You can easily run a macro from a macro in Excel.
This is a good practice when it comes to programming. Creating smaller procedures and then reusing them within your main macro can be more efficient to run and easier to maintain the code.
Sub ExampleCode()
MsgBox ("Hello world!")
End Sub
Sub MainCode()
Call ExampleCode
MsgBox ("Goodbye!")
End Sub
You can easily run any macro from within a macro using a single line of code. The above example will run the ExampleCode
macro from the MainCode
macro.
Run VBA Macro from a Worksheet Event
Did you know you can automatically run a macro?
You can automatically run a macro based on events that happen in your Excel worksheet!
For example, you can have a macro run anytime someone changes a value in the sheet.
Follow these steps to create a worksheet event-driven macro.
- Select the Sheet in which you want to trigger the macro. All your workbook sheets will be listed in the Microsoft Excel Object folder of the VBE Projects.
- Select the Worksheet options from the dropdown menu.
- Select the event type that should trigger your macro.
Private Sub Worksheet_Change(ByVal Target As Range)
End Sub
When you select the type of event, it will insert a bit of code into the editor. For example, the Change event trigger will insert the above code.
- Place any code you want to run when the event occurs inside the generated code.
If you have an existing macro that you want to run, you can call it using a Call YourMacroName
single line of code.
This macro will now run anytime you make changes in any cell within Sheet1.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" Then Call ExampleCode
End Sub
You might want to limit the macro to only running when the change event occurs in a particular cell or range. This is possible by setting conditions for the Target
in your code.
In the above example, the ExampleCode
macro will only be called when changes are made to cell A1.
Run VBA Macro from a Hyperlink
Did you know you can trigger your macros to run when you click on a hyperlink in Excel?
This is particular worksheet event method is worth its own mention!
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
If Target.Address = "B2" Then Call ExampleCode
End Sub
The above code will run every time you click the hyperlink in cell B2 in Sheet2.
The code will execute and then take you to the hyperlinked address!
Run VBA Macro from a Workbook Event
There is also the possibility to automatically run a macro based on workbook events such as when you open or close the file.
This is a great option to make sure a task is performed before you do anything else in your workbook.
Follow these steps to run a macro automatically when you open your Excel file.
- Select ThisWorkbook found in the Microsoft Excel Object folder of the VBE Projects.
- Select Workbook from the dropdown menu.
- Select Open from the event type dropdown menu.
Private Sub Workbook_Open()
End Sub
This will insert the above code into the code editor. You can then add any code inside which you want run when you open the file. You can also call any macro here with the Call YourMacroName
single line of code.
Conclusions
VBA macros can be used to automate your tasks in Excel, so it’s important you know how to run them.
There are many methods to run your desired macros depending on your situation.
You can use the Excel ribbon, a keyboard shortcut, or a customized quick access command when you want to manually run a macro. Also, you can attach your macros to run from buttons in the workbook to make it more user friendly.
You might need to occasionally run your VBA macros while developing your solutions to test them. This can be done several ways in the visual basic editor.
You can even trigger your macros based on certain worksheet or workbook events for the ultimate in automation.
Are you using macros in Excel. Did you know all these methods to run your macros? Do you know any others? Let me know in the comments below!
About the Author
John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.
Written by Puneet for Excel 2007, Excel 2010, Excel 2013, Excel 2016, Excel 2019, Excel for Mac
1. Run a Macro from the List
From the Developer Tab, you can access the list of the MACROS, which you have in your workbook or in PERSONAL.XLSB. To run a macro in Excel, you can use the below steps:
- Click on the macro button from the “Developer Tab” and open the list of macros.
- In this list of MACROS, you will have all the macro you have in the open workbooks, including the Personal Macro Workbook.
- Just select the macro you want to run and click on the “RUN” button.
When you click on the run button, it executes the macro and closes the dialog box.
2. Run a Macro with a Shortcut Key
You can also run a macro using a keyboard shortcut key. Usually, when you record a macro, it asks you to define a shortcut key that you can use to run that macro.
And if you are writing a macro, you can define a shortcut key from the list of macros.
- Select the name of the macro for which you want to define the shortcut key and click on the options.
- After that, click within the input box and press the shortcut key that you want to define.
3. Add a Macro Button to Quick Access Toolbar
You can also add a button to the Quick Access Toolbar to run a macro. You can use the below steps:
- First, click on the small dropdown that you have on the quick access toolbar and select more commands, and it will take you to the actual options to customize the quick access toolbar.
- Now from here, select the macros from the truth command from and select the macro that you want to add, after that click on the add button and it will add that macro to do quick access toolbar.
- In the end, click, OK.
And you will have a button for the macro that you have added.
4. Add Macro to a Shape
Let’s say you have a VBA code which you need to use frequently in your work. In this situation, you can create a button and assign that macro to it.
- First, insert a simple shape from Insert Tab ➜ Illustrations ➜ Shapes. Select any of the shapes which you want to use as a button.
- After that, right-click on that shape and select “Assign Macro”.
- Now from the list of macros, select the macro which you want to assign to the shape.
Now, whenever you click on that shape, the macro which you assigned will execute.
5. Assign a Macro to a Form Control Button
Apart from using a shape, you can also use a control button to run a macro.
- First, go to the Developer tab and in the controls group and then click on insert. And from the insert drop-down, click on the button to insert it.
- After that, it will show you the macros list from where you can select it.
- Once you select the macro and click OK, you will get a button in the worksheet (you can change the text of the button to give it a meaningful name).
6. Opening and Closing a Workbook
You can also make a macro to run while opening and closing a workbook. That means when you open or close a workbook, the macro you have assigned will get executed. For this, you need to use “auto_open” and “auto_close”.
Let’s suppose you want to assign a macro to run while opening the workbook. You need to use auto_open as the name of that macro.
Sub auto_open()
Range("A1").Value = Now
End Sub
Now, this micro will run when you open the workbook and enter the current date, and type in the cell A1 of the active sheet.
In the same way, you can also use “auto_close” to make this macro while closing the workbook.
7. Activating and Deactivating a Worksheet
Just like the workbook can also run a macro on activating and deactivating a worksheet. And in this case, you need to add that macro into the code window of that worksheet.
- First, right-click on the worksheet tab and click on the “view code”.
- Now in the code window, select the worksheet from the left drop-down. The moment you chose deactivate; you’ll get a new sub with the name “Worksheet_Deactivate”.
- Now you need to add the code in this procedure that you want to run when you deactivate the worksheet.
Private Sub Worksheet_Deactivate()
Range(“A1”).Value = Now
End Sub
And if you want to run a macro when you activate a worksheet, select activate instead of deactivated from the drop-down.
Private Sub Worksheet_Activate()
Range(“A1”).Value = Now
End Sub
8. Run a Macro When a Change in Worksheet
You can also run a macro when you make changes to a worksheet. For example, when you enter a value in a cell or delete a value from a cell.
For this, you, again, need to enter the good in the code window of the worksheet and select “Selection Change” from the drop-down.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Range(“A1”).Value = “Last Updated: ” & Format(Now, “dd-mmm-yy hh:mm:ss Am/pm”)
End Sub
9. Within Another Procedure
You can run a macro from another procedure by using the call statement. Use the keyword Call and then the name of the macro.
Sub myStrikeThrough()
If Selection.Value = “Yes” Then
Selection.Value = “No”
Else
Selection.Value = “Yes”
End If
End Sub
Sub markDone()
Call myStrikeThrough
Selection.Font.Bold = True
End Sub
When you run “markDone” macro, it first runs “mystrikethrough” macro and then makes the selection font bold.
10. Schedule a Macro
You can also schedule a macro to run at a specific time. Let’s suppose if you want to run a macro in the morning at 8:30, you can specify the time, and we will run it.
For this, you need to use an Application.OnTime method. Let’s suppose you have a macro “myCode”, you can write the code like below to run it at 8:30 AM.
Application.OnTime TimeValue("08:30:00"), "myCode"
[icon name=”bell” class=”” unprefixed_class=””] VBA is one of the Advanced Excel Skills
What is VBA and why should I use it?
VBA, or Visual Basic for Applications, is a scripting/programming language that can be used in Excel.
VBA Scripts, which are also referred to as “Macros”, are used for automating time-consuming operations in Excel, as well as enabling additional functionalities – Such as creating User Forms, creating User Defined Functions (UDFs), and more.
An additional benefit of VBA – All Office Applications can speak with each other using VBA – We can send an email from an Excel spreadsheet or create a Word document based on a specific Excel range, etc.
Here are some examples of VBA codes that I personally like:
- VBA code that unhides all worksheets in a workbook
- VBA code that creates a table of contents for all the worksheets in the workbook
- VBA code to remove page breaks
- VBA code that generates a brand new Excel Function that can sum and counts cells by their color!
Just because you may not have any prior knowledge in VBA, it doesn’t mean you can’t use it!
There are countless VBA code snippets which can be found on the net, and be used to solve problems in your Excel Workbook. All you have to do is to know how to find your required code, and how to run it.
Safety guidelines for using VBA
Before we start, a couple of IMPORTANT warnings – PLEASE READ CAREFULLY!!!
- VBA is a programming language. It can be very useful, but also very dangerous. Just like any programming language, it can be used for good purposes, but also bad purposes!
- VBA can be dangerous because it may contain malicious code that may intentionally harm your files and computer! You can easily use VBA to delete files from your computers, send them to other people and basically wreak total havoc 🙁
- VBA can be also dangerous if you run a certain code without understanding the impact of a specific line of code. It can crash your Excel, disable a certain functionality in Excel, become irresponsive, or even cause severe data loss to your files – On your active workbook and even on other workbooks (Open or even closed ones!)
- There is no “CTRL Z” (Undo) after running a VBA code. This means that unless you’ve saved your documents before running your code, you might not be able to undo your actions in Excel.
- Macros can be programmed to be triggered as soon as Excel starts or a certain operation is done. This is especially relevant for XLSM files (Excel Macro-Enabled Workbook). This means that you may trigger a macro without even knowing!
Attention – Please use macros at your own risk – we are not responsible for any loss or damage caused by running any of the VBA codes that are displayed or referred to on this website!
Okay, now that I’ve got your attention – Macros are a useful and important tool in the toolbox of any Excel expert.
Here are some guidelines on how to avoid the risks of using Macros, to enjoy their benefits:
- Before you run any VBA code – even the simplest one – Make sure you’ve saved all active Excel workbooks. If things go south, you can always re-open your workbook.
- If your Excel file is important and you’re not 100% sure about the consequences of your code – Create a backup to your files. In case you accidentally changed something and found out only a day after that this change was undesired – You can still revert to the backup file.
- A good practice before running VBA codes is to close all unnecessary Excel workbooks, as some VBA codes can unintentionally affect other workbooks. Closing these workbooks will lower the risk of data loss.
- Do not run VBA codes from untrusted websites. As beginners, you should focus on Macros you find on trusted and popular websites.
- Do not open suspicious Excel workbooks, especially XLSM (Excel Macro-Enabled Workbook) ones.
- Test your code before running it on your actual data. For example, run the code on a “dummy” file/data to verify it works well.
- Quality-Check your data and files after running the VBA code. Make sure that there are no undesired results!
- If you opened an XLSM workbook, Excel will ask you if it’s OK to enable Macros. Do not enable it unless you are 100% certain it’s safe, as this may trigger unwanted Macros in the background. If not sure – Do not enable. Better safe than sorry 🙂
Remember – Even Excel experts with many years of experience can make mistakes, especially when working with advanced features like VBA.
Being safe and careful is less painful and less time-consuming than trying to recover your valuable files.
So how do I run VBA codes?
Okay, let’s start with a simple code snippet that we’d like to run:
Sub Hello_Excel()
MsgBox (“I love Excel Practice Online!”)
End Sub
Basically, every VBA program starts with the word Sub, followed by a name for this program. Every program also ends with End Sub
Between the first and last line, you can see the MsgBox command – This will show a message box (MsgBox) with the message “I love Excel Practice Online” 🙂
To run this code:
- Copy all three lines to your clipboard (CTRL+C)
- Open a new Excel workbook (XLSX format is fine).
- As this is the first time you run a Macro, make sure all other Excel workbooks are saved and closed. Remember – Better safe than sorry.
- Next, you’ll need to open the Visual Basic Editor (VBE). This can be done by using the ALT+F11 Shortcut. You should now see the following screen:
- Click Insert – Module, to insert a new VBA module:
- Paste the code in the blank module, place your cursor somewhere in the highlighted line, and click Run (the green triangle, or use the ALT+F5 shortcut) to run the Macro:
- And here’s the result:
That’s it, you’ve successfully run your first Macro! 🙂
Am I the VBA Master now?
Unfortunately, not yet 🙂
But every journey begins with a single step – And this was your first step.
Now, progression is up to you. It’s a good idea to start trying to solve your everyday Excel problems using Macros. Just use Google.
For example, asking Google “How to unhide all worksheets VBA” will return the relevant VBA codes. Add the words VBA or Macro to your Google searches to make sure you get VBA solutions for your problems.
Also, follow our VBA section for useful VBA codes as well as VBA tutorials.
Good luck! 🙂
VBA is an excellent tool in Microsoft Office suite, including MS Excel application. It can assist you to accomplish a lot of tasks not supported by the native features in Excel. Now, in this article, we will teach you to run VBA code in Excel step by step.
If you intend to write some VBA codes to achieve some of your requirements, you have to firstly figure out how to run VBA code in your Excel. Now, thereinafter, we will use MS Excel 2010 for an instance to show the detailed steps, including how to enable macro, trigger VBA editor and several means to run macro, etc.
Step 1: Show “Developer” Ribbon
- First off, launch Excel application.
- Then, go to “File” menu and click “Options”.
- In the popup “Excel Options” window, turn to “Customize Ribbon” tab.
- Next, in the right side, find and check the “Developer” option.
- Finally, click “OK” to enable the modifications.
Step 2: Change Macro Security Settings
Since Excel comes with macro auto disabled in security settings, you need to first change the settings by following the steps below:
- At first, in Excel main window, switch to “Developer” ribbon.
- Then, click “Macro Security” button in “Code” group.
- Next, in the new window, select “Disable all macros except digitally signed macros” or “Enable all macros” option to your liking.
- Lastly, click “OK” to save the changes.
Step 3: Trigger Excel VBA Editor
Excel VBA editor is the place where you put the code. You can get access to it by 2 means.
- On “Developer” tab, click the “Visual Basic” button in “Code” group.
- Directly press “Alt + F11” key shortcuts to bring up “Microsoft Visual Basic for Applications” window.
Step 4: Add VBA Code
After entering Excel VBA editor, you need to add your code into either a project or a module.
1. Put Code into Existing Project
As you can see, under expanded “Microsoft Excel Objects” folder, you can see the existing projects, including the projects for each worksheet and the one for the current workbook called “ThisWorkbook”.
- To begin with, double click on a project to open its window.
- Then, put the code into it.
2. Put Code into Module
Besides, you can add code to a module by the following steps.
- In the first place, click “Insert” button in toolbar.
- From the drop down list, select “Module”.
- Then, in the new module, you can put your code.
Step 5: Run VBA Code
1. Run Macro in VBA Editor
To run VBA in the “Microsoft Visual Basic for Applications” window, you can just press “F5” key button or click the “Run” icon in the toolbar.
2. Run Macro through Quick Access Toolbar (QAT)
Moreover, you can add macro to Quick Access Toolbar and run it through QAT by the steps below.
- At the outset, go to “File” > “Options”.
- In the popup window, access “Quick Access Toolbar” tab.
- Then, select “Macros” from the list of “Choose commands from”.
- Next, choose the macro in the left side.
- Later, click “Add” button in center.
- After that, click “OK” to save the changes to Quick Access Toolbar.
- Finally, in the main Excel window, to run this macro, you can click the macro button in Quick Access Toolbar, as shown in the following screenshot.
3. Run Macro through Ribbon
In addition, like Quick Access Toolbar, you can add and run macro in ribbon.
- For a start, access “File” menu and hit “Options”.
- In “Excel Options”, go to “Customize Ribbon”.
- Then, create a new group on “Home” tab by “New Group”.
- Optionally, you can rename this group by “Rename…” button.
- Subsequently, select “Macros” in the list of “Choose commands from”.
- After that, pitch on the desired macro in the left side.
- Next, click the “Add” button to add this macro to the new group.
- Eventually, click “OK” to save options.
- Since then, to run this macro, you can click the newly added macro button in ribbon.
Author Introduction:
Shirley Zhang is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including mdf recovery and outlook repair software products. For more information visit www.datanumen.com