- Back-to-School Tech Tips
- Editor's Choice: School Tech
How to Create a Macro In Excel
Automate your recurring tasks with simple macros
- Pima College
What to Know
- Open the Developer tab and choose Record Macro . Add a name and shortcut for macro. In the drop-down, choose This Workbook > OK .
- Once created, perform formatting commands for the new macro, then choose Stop Recording > File > Save As . Save as an .xlsm file.
- The Developer tab isn't visible by default. To enable, open Options (PC) or Preferences (Mac). Open Ribbon settings, select Developer .
Microsoft Excel's spreadsheet configuration , formatting abilities, and formula functions allow you to perform repetitive tasks. You can streamline those tasks further by using macros. Learn how to do this with Excel for Microsoft 365, Excel 2019, Excel 2016, Excel 2013, Excel 2010, Excel for Microsoft 365 for Mac, Excel 2019 for Mac, and Excel 2016 for Mac.
How to Display the Developer Tab in Excel for Microsoft 365, Excel 2019, Excel 2016, Excel 2013, and Excel 2010
Before you add macros in Excel, display the Developer tab on the ribbon. By default, the Developer tab is not visible.
Go to the File tab and then select Options .
In the Excel Options dialog box, select Customize Ribbon .
In the Customize the Ribbon list, go to the Main Tabs section and select the Developer check box.
Select OK to add the Developer tab to the ribbon.
How to Create a Macro in Excel for Microsoft 365, Excel 2019, Excel 2016, Excel 2013, and Excel 2010
When you're ready to create a macro, start Excel and open a worksheet.
Macros cannot be created or run in Excel Online. However, Excel Online opens workbooks containing macros. You can make changes to worksheets and save workbooks in Excel Online without affecting macros.
Go to the Developer tab.
In the Code group, select Record Macro .
In the Macro Name text box, enter a descriptive name for the macro.
Enter a shortcut key for the macro.
Select the Store Macro In drop-down arrow and choose This Workbook .
Select OK .
Perform the formatting and commands you want to include in the macro.
Select Stop Recording when you're finished.
Go to the File tab and then select Save As or press F12 .
In the Save As dialog box, enter a file name for the workbook.
Select the Save as Type drop-down arrow, choose Excel Macro-Enabled Workbook and then select Save .
How to Display the Developer Tab in Excel for Microsoft 365 for Mac, Excel 2019 for Mac, and Excel 2016 for Mac
Before you add macros in Excel for Microsoft 365 for Mac or in Excel 2019 or 2016 on a Mac , display the Developer tab on the ribbon. By default, the Developer tab is not visible.
Go to Excel and choose Preferences .
Select Ribbon & Toolbar .
In the Customize the Ribbon section, go to the Main Tabs list and select the Developer check box.
Select Save .
How to Create a Macro in Excel for Microsoft 365 for Mac, Excel 2019 for Mac, and Excel 2016 for Mac
In the Macro Name text box, enter a name for the macro.
In the Shortcut key text box, type the lowercase or uppercase letter you want to use.
Select the Store macro in drop-down arrow and choose This Workbook .
When you're finished, go to the Developer tab and select Stop Recording .
Go to the File tab and select Save As or, press Shift + Command + S .
Select the File Format drop-down arrow, choose Excel Macro-Enabled Workbook (.xlsm) . Then select Save .
How to Run a Macro
When you want to run a macro you created in Excel, either use the shortcut you assigned to the macro or run the macro from the Developer tab.
To run a macro using a combination shortcut key , open the worksheet containing the macro. Enter or select the data on which you want to apply the formatting or commands included in the macro. Then, press the key combination assigned to the macro.
To run a macro from the Developer Tab, open the worksheet containing the macro, then follow these steps:
In Excel, enter any data on which you want to apply the formatting or commands you included in the macro.
In the Code group, select Macros .
In the Macro dialog box, choose the name assigned to the macro, then select Run .
How to Change the Macro Shortcut Key
To add or change a combination shortcut key for a macro:
In the Macros dialog box, select the name of the macro for which you want to assign or change the combination shortcut key.
Select Options .
In the Macro Options dialog box, go to the Shortcut key text box, type the lowercase or uppercase letter to use for the combination shortcut, and then select OK .
Get the Latest Tech News Delivered Every Day
- How to Link or Insert Excel Files to Word Documents
- Worksheets and Workbooks in Excel
- How to Rename a Worksheet in Excel
- Find Data With Excel's ROW and COLUMN Functions
- How to Share an Excel File
- How to Insert a Checkbox in Excel
- How to Use the MEDIAN Function in Excel
- How to Change the Number of Decimal Places in Excel
- How to Create a Drop-Down List Using Data From Another Excel Worksheet
- How to Create and Format a Pie Chart in Excel
- Round Numbers to the Nearest Even Integer in Excel
- How to Limit Rows and Columns in Excel
- Hide/Unhide Scroll Bars and Reset the Vertical Slider Range in Excel
- How to Find and Use Excel's Free Flowchart Templates
- How to Delete a Page in Excel
- How to Divide in Excel With the QUOTIENT Function
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts.
How to enable macros in microsoft excel.
Do more with less effort!
Be smart when enabling macros, how to turn on macros for a specific excel spreadsheet, how to enable macros for all excel spreadsheets.
Using Microsoft Excel macros, you can run a prerecorded set of steps to automate many of your repetitive tasks. You'll have to turn on the feature before you can use it. We'll show you how to activate macros on a per-spreadsheet basis as well as for all spreadsheets in Excel.
Enabling macros is not always safe and you should only use them when you're sure of the source of your spreadsheets. Good macros save you time by automating your tasks, but there are bad macros that can harm your machine.
Related: Macros Explained: Why Microsoft Office Files Can Be Dangerous
For example, if you've got your spreadsheet from an unknown source, you shouldn't trust it to run any macros as you aren't sure what it will end up doing. However, if you know the sender and you trust them, then it should be okay to allow your spreadsheets to execute macros.
To enable macros in a specific spreadsheet and not all spreadsheets, then first, open your spreadsheet with Microsoft Excel.
When your macro-enabled spreadsheet opens, Excel will display a message at the top of the spreadsheet content. To allow this file to run macros, then next to the message, click "Enable Content."
Excel will allow the current file to execute its macros, and you're all set.
Related: How to Disable the Security Warning Message Bar in Microsoft Office Programs
It's not recommended to activate macros for all your spreadsheets, but if you're sure you'll only open safe and trusted files, then you can turn on the option as follows.
Activate Macros in Excel on Windows
If you're a Windows user, first, launch Microsoft Excel on your PC.
In Excel's left sidebar, click "Options." If you're on a spreadsheet screen, then choose File > Options instead.
On the "Excel Options" window, in the left sidebar, click "Trust Center."
On the right pane, click the "Trust Center Settings" button.
You'll see a "Trust Center" window. In the left sidebar of this window, click "Macro Settings."
On the right pane, activate the "Enable VBA Macros (Not Recommended; Potentially Dangerous Code Can Run)" option. Then select "OK" at the bottom.
In the future, to disable macros for all spreadsheets, select an appropriate option on this screen.
Select "OK" at the bottom of the "Excel Options" window.
And that's it. Excel will now allow any spreadsheet to run macros.
Activate Macros in Excel on Mac
To turn on Excel macros on your Mac, first, launch the Excel app.
In Excel, click Excel > Preferences > Security & Privacy. Then, turn on the "Enable All Macros (Not Recommended; Potentially Dangerous Code Can Run)" option.
And that's how you allow your spreadsheets to run codes and automate your tedious tasks.
If you'd like to learn more about Excel macros , then check out our dedicated guide on the topic. It will walk you through the process of creating a macro with an example.
Related: Learn How to Use Excel Macros to Automate Tedious Tasks
Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How to permanently add macros to Excel as part of the program? [duplicate]
I have a macro where I'm not sure when I will need to use it.
I need them built into Excel to be able use them at every start of the program – like you would install some add-on (e.g. Kutools).
How can I do it?
- What you're looking for is the personal macro workbook – Raystafarian Aug 1, 2013 at 20:43
2 Answers 2
In excel 2010, the personal macro workbook is located at C:\Users\UserName\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.xlsb . The best way to create this is to record a macro into your personal macro workbook. You do this by:
- It is not working to me. I have that macro in my Personal macros file. But when I pick it, click: run. It doesnt work. It must be an issue during recording it. There must be some some order how to record it. Probably I did it in wrong way in detail while recording. – Rapier Aug 3, 2013 at 12:02
If you want to create a method to use and distribute your VBA solutions (e.g. allow other users to access UDF's you've created and used in your workbooks), you can easily create an Excel Add-in. Generally, you'll:
- Create a new, blank workbook and create your VBA solution.
- Save your new workbook as a .XLAM (Excel add-in).
- Use Excel to add your add-in; then distribute or make available as necessary.
See Microsoft's detailed directions here.
- I have tried it also. Can't make it work. Also have some problems with kind of permission in excel. It is saying me to run as 'unhidden'. I don't know where to enable it. – Rapier Aug 3, 2013 at 12:41
Not the answer you're looking for? Browse other questions tagged microsoft-excel microsoft-excel-2010 vba macros .
- The Overflow Blog
- Journey to the cloud part I: Migrating Stack Overflow Teams to Azure
- Featured on Meta
- Our Design Vision for Stack Overflow and the Stack Exchange network
Hot Network Questions
- Why does Canada's superficial loss rule also include a clause for "30 days before the sale"?
- How likely is it that the Voyager spacecrafts haven't yet been damaged by micrometeoroids?
- What order should my index's columns be for a SELECT a, b, MAX( c ) FROM d WHERE e = 1 GROUP BY a, b?
- show that solutions which start in the first quadrant must remain there for all time
- Is an “immaterial being” any less nonsensical than a “smelly color”?
- Calculating integral with exponential function and parameter
- Electrical issues while central air is running
- What are some good books on mathematical pedagogy?
- Typical pitch interval of the exclamation "uh-oh!"
- Golf the fast growing hierarchy
- Why people buy high dividend stock?
- Confused about the definition of a limit point
- Graphic3D, white face, black edge in any view?
- How did peer discovery work in Bitcoin v0.1?
- Why can't I move my knight from d5 to c7?
- How to put a tube in a used tubeless tire
- Intercepting a grappled Bite Swallow attack in place of an ally with Vigilant Guardian: What happens?
- Alternative chalk board materials
- reading device or board specific properties from the Arduino MKR WiFi 1010 device
- Question about number format for numbers between zero and one
- Why do people do a postdoc, rather than getting another PhD?
- anova degrees of freedom
- Male and female seahorses: which is which
- Be big more often
How to Add Macros in Excel
Microsoft Excel Macros are powerful tools that can streamline repetitive tasks, automate reports, and perform complex calculations. In this blog post, we will show you how to add macros in Excel, step-by-step. Whether you are a beginner or experienced user of Excel, this guide is designed to provide you with everything you need to know to get started with macros. By the end of this article, you will have the skills you need to boost your productivity and efficiency in Excel.
What are Excel Macros and why should you use them?
Step 1: open the developer tab, step 2: record the macro, how to run a macro in excel, best practices for macros, macro security warning, macro does not run, invalid cell ranges, can macros cause harm to my computer, can i record a macro for a pivottable, can i edit or delete a recorded macro, can macros work with excel files on different computers, i’m having trouble with a macro, where can i find help.
Excel Macros are a series of commands and functions that can be recorded and saved to automate repetitive tasks. Macros are a powerful tool that can save time and reduce the risk of errors when you perform the same task repeatedly.
For example, let’s say you have a spreadsheet with a column of numbers that need to be multiplied by a fixed value. Instead of manually typing in the formula or dragging the formula down the column, you can record a macro to perform this task in a matter of seconds. You can then use this macro every time you need to perform this task, saving you time, effort, and reducing the chances of errors.
How to Record a Basic Macro in Excel
Before you can start recording a macro, you need to make sure that the Developer tab is visible on your Excel ribbon. If you don’t see the Developer tab, follow these steps:
- Click on the File menu on your Excel ribbon.
- Select Options.
- In the Excel Options dialog box, select Customize Ribbon.
- Under Customize Ribbon, select Main Tabs and check the box next to Developer.
Once you have the Developer tab visible, you’re ready to start recording your macro:
- Select the cell where you want to start recording the macro.
- Click on the Developer tab and then click on the Record Macro button in the Code group.
- In the Record Macro dialog box, give your macro a name and optionally a keyboard shortcut.
- Select where you want to store your macro (in This Workbook, a New Workbook, or in a Personal Macro Workbook).
- Click OK to start recording your macro.
- Perform the actions you want to record in your macro, such as formatting cells, entering data, or using functions.
- When you’re done recording, click on Stop Recording in the Developer tab.
Now that you’ve recorded your macro, you can run it whenever you need to perform the same task again:
- Select the cell where you want to run the macro.
- Click on the Developer tab and then click on the Macros button in the Code group.
- Select the macro you want to run from the list of available macros.
- Click Run to run the macro.
Recording and running macros in Excel can be a huge timesaver, reducing errors and freeing up your time to focus on other tasks. By following the steps outlined in this guide, you can start creating your own macros and become a more efficient Excel user. So go ahead, give it a try and see how much time you can save!
Recording and using macros is a great way to be more efficient with your Excel workflow, but there are some best practices you should follow to get the most out of them:
- Always test your macros before using them on important spreadsheets to make sure they work as intended.
- When recording a macro, use relative cell references instead of absolute cell references whenever possible. This will ensure that your macro is flexible enough to be used on a range of different spreadsheets.
- Keep your macro’s name clear and descriptive. This will help you recognize its function quickly and avoid running the wrong macro accidentally.
- Store your macros in a safe location and back them up regularly to avoid losing any of your work.
- Don’t record a macro to perform a task that cannot be repeated consistently. If there is the slightest variation in the data, it could throw off the whole process.
Some Common Macro Errors and How to Fix Them
As with any feature, there are errors that can occur when using macros. Here are some common ones and their solutions:
When you open a spreadsheet with a macro enabled, Excel may display a security warning that says the file contains macros and asks if you want to enable them. To fix this, you need to change the macro security settings in Excel:
- Click on File, then Options.
- Click Trust Center, then Trust Center Settings.
- Select Macro Settings, then click the radio button next to ‘Enable all macros’.
- Click OK to save the changes.
If you click on the macro and nothing happens or you get an error message, it could be because the macro is in a hidden sheet or module. To fix this, you need to unhide the sheet or module:
- Click on the View tab in Excel.
- Select Unhide from the Windows group.
- Select the sheet or module that you want to unhide.
If your macro is not selecting the correct cell range, it could be because the cell range is no longer valid. To fix this, you can manually edit the macro to select the correct cell range:
- Right-click on the macro name.
- Select Edit.
- Select the correct cell range in the macro code.
- Click Save to save the changes.
Excel Macros can be an incredibly powerful tool in your productivity arsenal, allowing you to automate repetitive tasks and save a huge amount of time. We’ve shown you how to record basic macros step-by-step, run them, and discussed some tips and best practices. With these skills, you’ll be able to improve your efficiency and streamline your workflow.
Here are some common questions people ask about Excel Macros:
Macros are not inherently harmful, but they can be used to execute malicious code. To reduce the risk of this, only enable macros from trusted sources. Excel also has built-in security features that help protect your computer from harmful macros.
Yes, you can record a macro for a PivotTable. Macros can be used for almost anything that you can do in Excel, including formatting, calculations, and data analysis tasks like PivotTables.
Yes, you can edit or delete a recorded macro. To edit a macro, right-click on the macro name and select Edit. To delete a macro, right-click on the macro name and select Delete.
Yes, Macros can work with Excel files on different computers, as long as the file is saved in a shared location and the necessary add-ins and reference files are available on both computers.
If you’re having trouble with a macro, try searching for a solution online. There are many forums, blogs, and communities dedicated to helping people with Excel Macros. If you can’t find a solution, consider hiring an expert or taking an online course to improve your skills.
How to Protect Formulas in Excel
How to Put a Checkmark in Excel
How to Protect Excel Sheet
How to Remove Cell Lines in Excel
How to Remove Letters from a Cell in Excel
How to Read Excel File in Python
How to Remove Password in Excel
How to Restore Previous Version of Excel
How to Separate Words in Excel Using Formula
How to Run a T Test in Excel
How to Show Grid Lines on Excel
How to Sort by Alphabetical Order in Excel
How to Share Workbook in Excel
How to Strike Through Text in Excel
How to Subtract in Excel Formula
View all posts
- Ablebits blog
- Excel macro
Personal Macro Workbook in Excel - make macros available in all workbooks
The tutorial shows how to create and use the Personal.xlsb file to make Excel macro available in all workbooks.
Normally, when you write a macro in Excel, it can only be accessed from that specific workbook. But what if you want to use it in other files too? Recreating the same macro for each and every workbook does not sound like a good idea. Instead, store your popular VBA codes in the Personal Macro Workbook. This will make the macros accessible every time you open Excel, in any workbook!
What is Excel Personal Macro Workbook?
Personal Macro Workbook is a special file named Personal.xlsb in Excel 2007 – 2019 or Personal.xls in earlier versions. Any macros stored in this file are available to you whenever you start Excel. A great thing about the personal workbook is that it's hidden by default, so you won't ever notice it opening in the backend. No actions on your side are required. Microsoft Excel just knows the location where this file lives in your system and looks for it automatically on every launch.
Aside from macros, the Personal Macro Workbook can store your custom functions (user-defined functions) written in VBA.
Where is Personal Macro Workbook?
The Personal.xlsb file is stored in the XLSTART folder in the following locations.
On Windows 10, Windows 7, and Windows Vista:
On Windows XP:
C:\Documents and Settings\User Name\Application Data\Microsoft\Excel\XLSTART\
How to create Personal Macro Workbook in Excel
To make your personal macro workbook, you need to record any macro, which is done via the Developer tab. So, before we get started, please make sure the Developer tab is activated in your Excel.
To create the Excel Personal Macro Workbook, carry out these steps:
- If you want to record a specific macro, perform the desired actions. If your goal is just to create a personal workbook, continue with the next step.
Done! The Personal.xlsb file is created and will be automatically opened in the background every time you start Excel.
Now that you have a personal macro workbook, how do you place macros into it? There are four different ways to do this:
- Record a macro and save it to Personal Macro Workbook as shown above.
- Write a macro in the VB Editor.
- Copy VBA code from another workbook.
- Import macros from a .bas file.
How to view, create, copy and edit macros in Personal Macro Workbook
Once the Personal.xlsb file is saved on your computer, you can view, create and edit the macros the Visual Basic Editor. Also, you can copy the code you wish to reuse from another workbook.
To create or edit a macro in your personal workbook, this is what you need to do:
- Open the VB Editor. For this, press ALT + F11 or click the Visual Basic button on the Developer tab, in the Code group.
- In the Project Explorer window, find the PERSONAL.XLSB object, expand it, and double-click on Module1 to open its Code window.
- In the Code window, write, copy/paste or edit the VBA code.
- Close the VB Editor.
- Close Excel and save the changes you've made to the Personal Macro Workbook when prompted.
How to use macros stored in Personal Workbook
Macros stored in your personal workbook can be used in any Excel file. For this, just open the worksheet in which you want to run the macro, and do the following:
- On the Developer tab, in the Code group, click the Macros button or press the Alt + F8 shortcut.
How to export Personal Macro Workbook
Like any other VBA code, the macros stored in Personal.xlsb can be exported to a .bas file.
To export your personal macro workbook, here's what you need to do:
- Open the Visual Basic Editor.
- In the Project Explorer, right-click Module1 under PERSONAL.XLSB and select Export File .
- Navigate to the folder where you want to save your personal macro workbook, give the file any name you want, and click Save .
How to share Personal Macro Workbook in Excel
In case you'd like to share your personal workbook with other people, proceed in one of the following ways.
Share the Personal.xlsb file
The easiest way to share a personal macro workbook with someone is to send them a copy of your Personal.xlsb file as attachment, or save it to a cloud storage or your local network. And then, other persons can put your Personal.xlsb file in their XLSTART folder. See where Personal.xlsb is located .
Copy macros to another workbook
Export macros to a .bas file.
A professional-like way is to move all the macros you wish to share into one module and export that module as a .bas file . Send the .bas file to other users by email, and they will be able import it as a new module into their Personal.xls file.
How to enable Personal Macro Workbook in Excel
If one day you open Excel and find out that your favorite macros are no longer there, don't panic! Most likely, the Personal.xlsb file was disabled by Excel after a crash, update, or for whatever reason.
Here are the steps to get your personal workbook up and running again:
- In your Excel, click File > Options .
- In the Excel Options dialog box, select Add-ins on the left-hand side.
- In the Manage drop-down list, pick Disabled Items and click Go .
- In the Disabled Items dialog box, select Personal Macro Workbook and click Enable .
- Restart your Excel.
How to prevent Personal.xlsb from opening but keep macros running
By default, the Personal Macro Workbook should not be visible in Excel. If the Personal.xlsb file keeps opening whenever you use macros and this really bugs you, you can hide it in this way:
- Navigate to the PERSONAL.XLSB workbook.
How to unhide a personal workbook in Excel
To make your personal macro workbook visible, this is what you need to do:
- On the View tab, in the Window group, click Unhide .
How to remove Personal.xlsb file
If you'd like to completely remove the Personal Macro Workbook from your computer, delete the Personal.xlsb file from the XLSTART folder. Here's how:
- Close all Excel workbooks.
- Open Windows Explorer.
- On the View tab, in the Show/Hide group, tick the Hidden Items checkbox.
That's how to make your favorite Excel macros available in all workbooks. I thank you for reading and hope to see you on our blog next week!
You may also be interested in
- Excel macro tutorial for beginners with examples
- How to record a macro in Excel
- How to enable and disable macros in Excel
- How to run Excel macros
- How to insert VBA code
Table of contents
Thank you for this tutorial. I have been trying to remove a faulty macro for months and now it is gone.
This article is incredibly helpful for me to learn this handy trick. Thank you Svetlana!
Thank you so much!
i am too thankful for this information
Hi, My personal workbook seems to have disappeared. I can't unhide it because unhide is greyed out, and I did the enable disabled items in add-ins but still no personal workbook. HALP. How do I get it back??
Is there a way to store the Personal Macro Workbook in the cloud, so that I can use it at home and at work? Thanks
I saved a macro that is headed "Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) ' Colour in GC and AC entries" to PERSONAL.XLSB, but it does not appear when I open a worksheet and press the Macros button. Should I be adding a title for the macro in some way?
Hello! When you press Alt+F8 in your workbook to run a macro, Private Subs don’t show up in the dialog box. Don't use the "Private" option.
there's a typo: "On the Developer tab, in the Code group, click the Macros button or press the Alt + 8 shortcut" should be: "On the Developer tab, in the Code group, click the Macros button or press the Alt + F8 shortcut"
Fixed. Thank you!
Thank you so much! I couldn't find a way to import macros from a colleague but now it works. Appreciate it.
How to edit ms Excel online?
I have created macro enabled file. Created a button and attached this macro to it.
Now i want to share this excel file with users.
But I dont want to restrict users to save files on specific paths like - C:\Users\usrname\AppData\Roaming\Microsoft\Excel\XLSTART
Is there any way to avoid this step.
As a user when I received macro enabled file and xlsb file. I would simply download attachments and save them to any random path I wish to. And start using macro functionalities.
Basically, end user should not bother about the technicality of xlsb.
But I tried something and editing macros also works in a shared file (any) !!! Cancel sharing / open the file in the archiver (winrar, 7-zip, etc ...) / folder xl, file vbaProject.bin -> extract file (for example to the Desktop) / share the excel file again / reopen the excel file with the archiver and insert the original vbaProject.bin --> VBA can be edited in the shared file ;)
I have one knowledge about Personal.xlsb If I want to open 2 instances of Excel in Office2010, the second of them blocked Personal.xlsb because it is used by the first instance. Thus, either Personal must be checked "read-only" or Personal must be listed as shared. However, in both cases, macros cannot be edited. So this is a bit ill-conceived (MS) :(((
I created personal macro for Pivot Table creation but when I run this on other files, it gives me runtime error. Any suggest to fix it ? Thanks
Tried creating a macro and save it to a Personal Macro Workbook, but got an error message that said, "Personal Macro Workbook in the startup folder must stay open for recording." I have no idea what this means. I see nothing about it in the startup folder. When I clicked OK, I was further informed that the macro would not record. Please help.
Hey Paul - Search for the PERSONAL.XLSB file and open it. Once open, click: View > Hide.
On the workbook you are trying to create a macro in, click "Record Macro" again, should work!
Thank you Ms. Svetlana for writing this blog. It was *exactly* what I needed and more. I found your post through a Bing search, but will be exploring your website and products later. Thanks again and God bless. --Jeff Fuhr
Post a comment
- EXPLORE Coupons Tech Help Pro Random Article About Us Quizzes Request a New Article Community Dashboard This Or That Game Popular Categories Arts and Entertainment Artwork Books Movies Computers and Electronics Computers Phone Skills Technology Hacks Health Men's Health Mental Health Women's Health Relationships Dating Love Relationship Issues Hobbies and Crafts Crafts Drawing Games Education & Communication Communication Skills Personal Development Studying Personal Care and Style Fashion Hair Care Personal Hygiene Youth Personal Care School Stuff Dating All Categories Arts and Entertainment Finance and Business Home and Garden Relationship Quizzes Cars & Other Vehicles Food and Entertaining Personal Care and Style Sports and Fitness Computers and Electronics Health Pets and Animals Travel Education & Communication Hobbies and Crafts Philosophy and Religion Work World Family Life Holidays and Traditions Relationships Youth
- EDIT Edit this Article
- PRO Courses Guides New Tech Help Pro Expert Videos About wikiHow Pro Upgrade Sign In
- Browse Articles
- Learn Something New
- This Or That Game New
- Train Your Brain
- Explore More
- Support wikiHow
- About wikiHow
- H&M Coupons
- Hotwire Promo Codes
- StubHub Discount Codes
- Ashley Furniture Coupons
- Blue Nile Promo Codes
- NordVPN Coupons
- Samsung Promo Codes
- Chewy Promo Codes
- Ulta Coupons
- Vistaprint Promo Codes
- Shutterfly Promo Codes
- DoorDash Promo Codes
- Office Depot Coupons
- adidas Promo Codes
- Home Depot Coupons
- DSW Coupons
- Bed Bath and Beyond Coupons
- Lowe's Coupons
- Surfshark Coupons
- Nordstrom Coupons
- Walmart Promo Codes
- Dick's Sporting Goods Coupons
- Fanatics Coupons
- Edible Arrangements Coupons
- eBay Coupons
- Log in / Sign up
- Computers and Electronics
- Microsoft Excel
How to Use Macros in Excel
Last Updated: October 25, 2022 Tested
This article was co-authored by wikiHow staff writer, Jack Lloyd . Jack Lloyd is a Technology Writer and Editor for wikiHow. He has over two years of experience writing and editing technology-related articles. He is technology enthusiast and an English teacher. The wikiHow Tech Team also followed the article's instructions and verified that they work. This article has been viewed 726,230 times. Learn more...
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.
- If you have a specific file which you want to open in Excel, double-click that file to open it instead.
- On a Mac, click Excel in the upper-left corner of the screen to prompt a drop-down menu.
- On a Mac, you'll click Preferences... in the drop-down menu.
- On a Mac, click instead Ribbon & Toolbar in the Preferences window.
- On a Mac, you'll click Save here instead.
Recording a Macro
- You can also close Excel and open a specific Excel file by double-clicking it.
- On a Mac, the shortcut key combination will end up being ⌥ Option + ⌘ Command and your key (e.g., ⌥ Option + ⌘ Command + T ).
- 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.
Saving a Macro-Enabled Spreadsheet
- 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.
- Skip this step on a Mac.
- On a Mac, you'll replace the "xlsx" at the end of the file's name with xlsm .
- On a Mac, you must first click the "Where" drop-down box.
Running a Macro
- If you don't see this option, skip this step.
- 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.
- 7 Wait for the macro to finish running. Depending on how large your macro is, this can take several seconds.
Video . By using this service, some information may be shared with YouTube.
- Macros are generally useful for automating tasks which you must perform often, such as calculating payroll at the end of the week. Thanks Helpful 1 Not Helpful 0
- 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. Thanks Helpful 0 Not Helpful 0
You Might Also Like
- ↑ https://support.office.com/en-us/article/enable-or-disable-macros-in-office-files-12b036fd-d140-4e74-b45e-16fed1a7e5c6
- ↑ https://support.office.com/en-us/article/file-formats-supported-in-excel-for-mac-f9970726-bb98-489c-afe2-6d876873945a
About This Article
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? Yes No
- Send fan mail to authors
Is this article up to date?
- Do Not Sell or Share My Info
- Not Selling Info
Keep up with tech in just 5 minutes a week!
#1 Excel tutorial on the net
- Add a Macro to the Toolbar
If you use an Excel macro frequently, you can add it to the Quick Access Toolbar . This way you can quickly access your macro. First, we record an empty macro.
1. On the Developer tab, click Record Macro.
2. Name the macro MyName. Choose to store the macro in Personal Macro Workbook. This way the macro will be available to all your workbooks (Excel files). This is possible because Excel stores your macro in a hidden workbook that opens automatically when Excel starts.
3. Click OK.
4. Click Stop Recording.
5. Open the Visual Basic Editor .
6. Create the macro:
This macro places your name in the Active Cell.
7. Close the Visual Basic Editor.
8. Now we can add this macro to the Quick Access Toolbar. Click the down arrow and click More Commands.
9. Under Choose commands, select Macros.
10. Select the macro and click Add.
11. You can modify the button that will be added to the Quick Access Toolbar by clicking on Modify. For example, choose a smiley.
12. Click OK twice.
13. You can now execute the macro. For example, select cell E2 and click on the smiley button added to the Quick Access Toolbar.
14. When you close Excel, Excel asks you to save the changes you made to the Personal Macro Workbook. Click Save to store this macro in a hidden workbook that opens automatically when Excel starts. This way the macro will be available to all your workbooks (Excel files).
- Create a Macro
Learn more, it's easy
- Swap Values
- Run Code from a Module
- Macro Recorder
- Use Relative References
- Enable Macros
- Protect Macro
Follow excel easy.
Become an Excel Pro
- 300 Examples
Add a Macro to the Toolbar • © 2010-2023 Popular Excel Topics: Pivot Tables • Vlookup • Formulas • Charts • Conditional Formatting
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Getting started with VBA in Office
- 10 contributors
Are you facing a repetitive clean up of fifty tables in Word? Do you want a particular document to prompt the user for input when it opens? Are you having difficulty figuring out how to get your contacts from Microsoft Outlook into a Microsoft Excel spreadsheet efficiently?
You can perform these tasks and accomplish a great deal more by using Visual Basic for Applications (VBA) for Office—a simple, but powerful programming language that you can use to extend Office applications.
This article is for experienced Office users who want to learn about VBA and who want some insight into how programming can help them to customize Office.
The Office suite of applications has a rich set of features. There are many different ways to author, format, and manipulate documents, email, databases, forms, spreadsheets, and presentations. The great power of VBA programming in Office is that nearly every operation that you can perform with a mouse, keyboard, or a dialog box can also be done by using VBA. Further, if it can be done once with VBA, it can be done just as easily a hundred times. (In fact, the automation of repetitive tasks is one of the most common uses of VBA in Office.)
Beyond the power of scripting VBA to accelerate every-day tasks, you can use VBA to add new functionality to Office applications or to prompt and interact with the user of your documents in ways that are specific to your business needs. For example, you could write some VBA code that displays a pop up message that reminds users to save a document to a particular network drive the first time they try to save it.
This article explores some of the primary reasons to leverage the power of VBA programming. It explores the VBA language and the out-of-the-box tools that you can use to work with your solutions. Finally, it includes some tips and ways to avoid some common programming frustrations and missteps.
When to use VBA and why
There are several principal reasons to consider VBA programming in Office.
Automation and repetition
VBA is effective and efficient when it comes to repetitive solutions to formatting or correction problems. For example, have you ever changed the style of the paragraph at the top of each page in Word? Have you ever had to reformat multiple tables that were pasted from Excel into a Word document or an Outlook email? Have you ever had to make the same change in multiple Outlook contacts?
If you have a change that you have to make more than ten or twenty times, it may be worth automating it with VBA. If it is a change that you have to do hundreds of times, it certainly is worth considering. Almost any formatting or editing change that you can do by hand, can be done in VBA.
Extensions to user interaction
There are times when you want to encourage or compel users to interact with the Office application or document in a particular way that is not part of the standard application. For example, you might want to prompt users to take some particular action when they open, save, or print a document.
Interaction between Office applications
Do you need to copy all of your contacts from Outlook to Word and then format them in some particular way? Or, do you need to move data from Excel to a set of PowerPoint slides? Sometimes simple copy and paste does not do what you want it to do, or it is too slow. Use VBA programming to interact with the details of two or more Office applications at the same time and then modify the content in one application based on the content in another.
Doing things another way
VBA programming is a powerful solution, but it is not always the optimal approach. Sometimes it makes sense to use other ways to achieve your aims.
The critical question to ask is whether there is an easier way. Before you begin a VBA project, consider the built-in tools and standard functionalities. For example, if you have a time-consuming editing or layout task, consider using styles or accelerator keys to solve the problem. Can you perform the task once and then use CTRL+Y (Redo) to repeat it? Can you create a new document with the correct format or template, and then copy the content into that new document?
Office applications are powerful; the solution that you need may already be there. Take some time to learn more about Office before you jump into programming.
Before you begin a VBA project, ensure that you have the time to work with VBA. Programming requires focus and can be unpredictable. Especially as a beginner, never turn to programming unless you have time to work carefully. Trying to write a "quick script" to solve a problem when a deadline looms can result in a very stressful situation. If you are in a rush, you might want to use conventional methods, even if they are monotonous and repetitive.
VBA Programming 101
Using code to make applications do things.
You might think that writing code is mysterious or difficult, but the basic principles use every-day reasoning and are quite accessible. Microsoft Office applications are created in such a way that they expose things called objects that can receive instructions, in much the same way that a phone is designed with buttons that you use to interact with the phone. When you press a button, the phone recognizes the instruction and includes the corresponding number in the sequence that you are dialing. In programming, you interact with the application by sending instructions to various objects in the application. These objects are expansive, but they have their limits. They can only do what they are designed to do, and they will only do what you instruct them to do.
For example, consider the user who opens a document in Word, makes a few changes, saves the document, and then closes it. In the world of VBA programming, Word exposes a Document object. By using VBA code, you can instruct the Document object to do things such as Open, Save, or Close.
The following section discusses how objects are organized and described.
The Object Model
Developers organize programming objects in a hierarchy, and that hierarchy is called the object model of the application. Word, for example, has a top-level Application object that contains a Document object. The Document object contains Paragraph objects and so on. Object models roughly mirror what you see in the user interface. They are a conceptual map of the application and its capabilities.
The definition of an object is called a class, so you might see these two terms used interchangeably. Technically, a class is the description or template that is used to create, or instantiate, an object.
Once an object exists, you can manipulate it by setting its properties and calling its methods. If you think of the object as a noun, the properties are the adjectives that describe the noun and the methods are the verbs that animate the noun. Changing a property changes some quality of appearance or behavior of the object. Calling one of the object methods causes the object to perform some action.
The VBA code in this article runs against an open Office application where many of the objects that the code manipulates are already up and running; for example, the Application itself, the Worksheet in Excel, the Document in Word, the Presentation in PowerPoint, the Explorer and Folder objects in Outlook. Once you know the basic layout of the object model and some key properties of the Application that give access to its current state, you can start to extend and manipulate that Office application with VBA in Office.
In Word, for example, you can change the properties and invoke the methods of the current Word document by using the ActiveDocument property of the Application object. This ActiveDocument property returns a reference to the Document object that is currently active in the Word application. "Returns a reference to" means "gives you access to."
The following code does exactly what it says; that is, it saves the active document in the application.
Read the code from left to right, "In this Application, with the Document referenced by ActiveDocument, invoke the Save method." Be aware that Save is the simplest form of method; it does not require any detailed instructions from you. You instruct a Document object to Save and it does not require any more input from you.
If a method requires more information, those details are called parameters. The following code runs the SaveAs method, which requires a new name for the file.
Values listed in parentheses after a method name are the parameters. Here, the new name for the file is a parameter for the SaveAs method.
You use the same syntax to set a property that you use to read a property. The following code executes a method to select cell A1 in Excel and then to set a property to put something in that cell.
The first challenge in VBA programming is to get a feeling for the object model of each Office application and to read the object, method, and property syntax. The object models are similar in all Office applications, but each is specific to the kind of documents and objects that it manipulates.
In the first line of the code snippet, there is the Application object, Excel this time, and then the ActiveSheet , which provides access to the active worksheet. After that is a term not as familiar, Range, which means "define a range of cells in this way." The code instructs Range to create itself with just A1 as its defined set of cells. In other words, the first line of code defines an object, the Range, and runs a method against it to select it. The result is automatically stored in another property of the Application called Selection .
The second line of code sets the Value property of Selection to the text "Hello World", and that value appears in cell A1.
The simplest VBA code that you write might simply gain access to objects in the Office application that you are working with and set properties. For example, you could get access to the rows in a table in Word and change their formatting in your VBA script.
That sounds simple, but it can be incredibly useful; once you can write that code, you can harness all of the power of programming to make those same changes in several tables or documents, or make them according to some logic or condition. For a computer, making 1000 changes is no different from making 10, so there is an economy of scale here with larger documents and problems, and that is where VBA can really shine and save you time.
Macros and the Visual Basic Editor
Now that you know something about how Office applications expose their object models, you are probably eager to try calling object methods, setting object properties, and responding to object events. To do so, you must write your code in a place and in a way that Office can understand; typically, by using the Visual Basic Editor. Although it is installed by default, many users don't know that it is even available until it is enabled on the ribbon.
All Office applications use the ribbon. One tab on the ribbon is the Developer tab, where you access the Visual Basic Editor and other developer tools. Because Office does not display the Developer tab by default, you must enable it by using the following procedure:
To enable the Developer tab
On the File tab, choose Options to open the Options dialog box.
Choose Customize Ribbon on the left side of the dialog box.
Under Choose commands from on the left side of the dialog box, select Popular Commands .
Under Customize the Ribbon on the right side of the dialog box, select Main Tabs in the drop down list box, and then select the Developer checkbox.
Choose OK .
In Office 2007, you displayed the Developer tab by choosing the Office button, choosing Options , and then selecting the Show Developer tab in Ribbon check box in the Popular category of the Options dialog box.
After you enable the Developer tab, it is easy to find the Visual Basic and Macros buttons.
Figure 1. Buttons on the Developer tab
To protect Office users against viruses and dangerous macro code, you cannot save macro code in a standard Office document that uses a standard file extension. Instead, you must save the code in a file with a special extension. For example you cannot save macros in a standard Word document with a .docx extension; instead, you must use a special Word Macro-Enabled Document with a .docm extension.
When you open a .docm file, Office security might still prevent the macros in the document from running, with or without telling you. Examine the settings and options in the Trust Center on all Office applications. The default setting disables macro from running, but warns you that macros have been disabled and gives you the option to turn them back on for that document.
You can designate specific folders where macros can run by creating Trusted Locations, Trusted Documents, or Trusted Publishers. The most portable option is to use Trusted Publishers, which works with digitally signed documents that you distribute. For more information about the security settings in a particular Office application, open the Options dialog box, choose Trust Center , and then choose Trust Center Settings .
Some Office applications, like Outlook, save macros by default in a master template on your local computer. Although that strategy reduces the local security issues on your own computer when you run your own macros, it requires a deployment strategy if you want to distribute your macro.
Recording a macro
When you choose the Macro button on the Developer tab, it opens the Macros dialog box, which gives you access to VBA subroutines or macros that you can access from a particular document or application. The Visual Basic button opens the Visual Basic Editor, where you create and edit VBA code.
Another button on the Developer tab in Word and Excel is the Record Macro button, which automatically generates VBA code that can reproduce the actions that you perform in the application. Record Macro is a terrific tool that you can use to learn more about VBA. Reading the generated code can give you insight into VBA and provide a stable bridge between your knowledge of Office as a user and your knowledge as a programmer. The only caveat is that the generated code can be confusing because the Macro editor must make some assumptions about your intentions, and those assumptions are not necessarily accurate.
To record a macro
Open Excel to a new Workbook and choose the Developer tab in the ribbon. Choose Record Macro and accept all of the default settings in the Record Macro dialog box, including Macro1 as the name of the macro and This Workbook as the location.
Choose OK to begin recording the macro. Note how the button text changes to Stop Recording . Choose that button the instant you complete the actions that you want to record.
Choose cell B1 and type the programmer's classic first string: Hello World. Stop typing and look at the Stop Recording button; it is grayed out because Excel is waiting for you to finish typing the value in the cell.
Choose cell B2 to complete the action in cell B1, and then choose Stop Recording .
Choose Macros on the Developer tab, select Macro1 if it is not selected, and then choose Edit to view the code from Macro1 in the Visual Basic Editor.
Figure 2. Macro code in Visual Basic Editor
Looking at the code
The macro that you created should look similar to the following code.
Be aware of the similarities to the earlier code snippet that selected text in cell A1, and the differences. In this code, cell B1 is selected, and then the string "Hello World" is applied to the cell that has been made active. The quotes around the text specify a string value as opposed to a numeric value.
Remember how you chose cell B2 to display the Stop Recording button again? That action shows up as a line of code as well. The macro recorder records every keystroke.
The lines of code that start with an apostrophe and colored green by the editor are comments that explain the code or remind you and other programmers the purpose of the code. VBA ignores any line, or portion of a line, that begins with a single quote. Writing clear and appropriate comments in your code is an important topic, but that discussion is out of the scope of this article. Subsequent references to this code in the article don't include those four comment lines.
When the macro recorder generates the code, it uses a complex algorithm to determine the methods and the properties that you intended. If you don't recognize a given property, there are many resources available to help you. For example, in the macro that you recorded, the macro recorder generated code that refers to the FormulaR1C1 property. Not sure what that means?
Be aware that Application object is implied in all VBA macros. The code that you recorded works with Application. at the beginning of each line.
Using Developer Help
Select FormulaR1C1 in the recorded macro and press F1. The Help system runs a quick search, determines that the appropriate subjects are in the Excel Developer section of the Excel Help, and lists the FormulaR1C1 property. You can choose the link to read more about the property, but before you do, be aware of the Excel Object Model Reference link near the bottom of the window. Choose the link to view a long list of objects that Excel uses in its object model to describe the Worksheets and their components.
Choose any one of those to see the properties and methods that apply to that particular object, along with cross references to different related options. Many Help entries also have brief code examples that can help you. For example, you can follow the links in the Borders object to see how to set a border in VBA.
Editing the code
The Borders code looks different from the recorded macro. One thing that can be confusing with an object model is that there is more than one way to address any given object, cell A1 in this example.
Sometimes the best way to learn programming is to make minor changes to some working code and see what happens as a result. Try it now. Open Macro1 in the Visual Basic Editor and change the code to the following.
Use Copy and Paste as much as possible when working with code to avoid typing errors.
You don't need to save the code to try it out, so return to the Excel document, choose Macros on the Developer tab, choose Macro1 , and then choose Run . Cell A1 now contains the text Wow! and has a double-line border around it.
Figure 3. Results of your first macro
You just combined macro recording, reading the object model documentation, and simple programming to make a VBA program that does something. Congratulations!
Did not work? Read on for debugging suggestions in VBA.
Programming tips and tricks
Start with examples.
The VBA community is very large; a search on the Web can almost always yield an example of VBA code that does something similar to what you want to do. If you cannot find a good example, try to break the task down into smaller units and search on each of those, or try to think of a more common, but similar problem. Starting with an example can save you hours of time.
That does not mean that free and well-thought-out code is on the Web waiting for you to come along. In fact, some of the code that you find might have bugs or mistakes. The idea is that the examples you find online or in VBA documentation give you a head start. Remember that learning programming requires time and thought. Before you get in a big rush to use another solution to solve your problem, ask yourself whether VBA is the right choice for this problem.
Make a simpler problem
Programming can get complex quickly. It's critical, especially as a beginner, that you break the problem down to the smallest possible logical units, then write and test each piece in isolation. If you have too much code in front of you and you get confused or muddled, stop and set the problem aside. When you come back to the problem, copy out a small piece of the problem into a new module, solve that piece, get the code working, and test it to ensure that it works. Then move on to the next part.
Bugs and debugging
There are two main types of programming errors: syntax errors, which violate the grammatical rules of the programming language, and run-time errors, which look syntactically correct, but fail when VBA attempts to execute the code.
Although they can be frustrating to fix, syntax errors are easy to catch; the Visual Basic Editor beeps and flashes at you if you type a syntax error in your code.
For example, string values must be surrounded by double quotes in VBA. To find out what happens when you use single quotes instead, return to the Visual Basic Editor and replace the "Wow!" string in the code example with 'Wow!' (that is, the word Wow enclosed in single quotes). If you choose the next line, the Visual Basic Editor reacts. The error "Compile error: Expected: expression" is not that helpful, but the line that generates the error turns red to tell you that you have a syntax error in that line and as a result, this program will not run.
Choose OK and change the text back to"Wow!".
Runtime errors are harder to catch because the programming syntax looks correct, but the code fails when VBA tries to execute it.
For example, open the Visual Basic Editor and change the Value property name to ValueX in your Macro, deliberately introducing a runtime error since the Range object does not have a property called ValueX. Go back to the Excel document, open the Macros dialog box and run Macro1 again. You should see a Visual Basic message box that explains the run-time error with the text, "Object doesn't support this property of method." Although that text is clear, choose Debug to find out more.
When you return to the Visual Basic Editor, it is in a special debug mode that uses a yellow highlight to show you the line of code that failed. As expected, the line that includes the ValueX property is highlighted.
You can make changes to VBA code that is running, so change ValueX back to Value and choose the little green play button underneath the Debug menu. The program should run normally again.
It's a good idea to learn how to use the debugger more deliberately for longer, more complex programs. At a minimum, learn a how to set break-points to stop execution at a point where you want to take a look at the code, how to add watches to see the values of different variables and properties as the code runs, and how to step through the code line by line. These options are all available in the Debug menu and serious debugger users typically memorize the accompanying keyboard shortcuts.
Using reference materials well
To open the Developer Reference that is built into Office Help, open the Help reference from any Office application by choosing the question mark in the ribbon or by pressing F1. Then, to the right of the Search button, choose the dropdown arrow to filter the contents. Choose Developer Reference . If you don't see the table of contents in the left panel, choose the little book icon to open it, and then expand the Object Model Reference from there.
Figure 5. Filtering on developer Help applies to all Office applications
Time spent browsing the Object Model reference pays off. After you understand the basics of VBA syntax and the object model for the Office application that you are working with, you advance from guesswork to methodical programming.
Of course the Microsoft Office Developer Center is an excellent portal for articles, tips, and community information.
Searching forums and groups
All programmers get stuck sometimes, even after reading every reference article they can find and losing sleep at night thinking about different ways to solve a problem. Fortunately, the Internet has fostered a community of developers who help each other solve programming problems.
Any search on the Web for "office developer forum" reveals several discussion groups. You can search on "office development" or a description of your problem to discover forums, blog posts, and articles as well.
If you have done everything that you can to solve a problem, don't be afraid to post your question to a developers forum. These forums welcome posts from newer programmers and many of the experienced developers are glad to help.
The following are a few points of etiquette to follow when you post to a developer forum:
Before you post, look on the site for an FAQ or for guidelines that members want you to follow. Ensure that you post content that is consistent with those guidelines and in the correct section of the forum.
Include a clear and complete code sample, and consider editing your code to clarify it for others if it is part of a longer section of code.
Describe your problem clearly and concisely, and summarize any steps that you have taken to solve the problem. Take the time to write your post as well as you can, especially if you are flustered or in a hurry. Present the situation in a way that will make sense to readers the first time that they read the problem statement.
Be polite and express your appreciation.
Going further with programming
Although this article is short and only scratches the surface of VBA and programming, it is hopefully enough to get you started.
This section briefly discusses a few more key topics.
In the simple examples in this article you manipulated objects that the application had already created. You might want to create your own objects to store values or references to other objects for temporary use in your application. These are called variables.
To use a variable in VBA, must tell VBA which type of object the variable represents by using the Dim statement. You then set its value and use it to set other variables or properties.
Branching and looping
The simple programs in this article execute one line at a time, from the top down. The real power in programming comes from the options that you have to determine which lines of code to execute, based on one or more conditions that you specify. You can extend those capabilities even further when you can repeat an operation many times. For example, the following code extends Macro1.
Type or paste the code into the Visual Basic Editor and then run it. Follow the directions in the message box that appears and change the text in cell A1 from Wow! to Yes! and run it again to see the power of looping. This code snippet demonstrates variables, branching and looping. Read it carefully after you see it in action and try to determine what happens as each line executes.
All of my Office applications: example code
Here are a few scripts to try; each solves a real-world Office problem.
Create an email in Outlook
Be aware that there are situations in which you might want to automate email in Outlook; you can use templates as well.
Delete empty rows in an Excel worksheet
Be aware that you can select a column of cells and run this macro to delete all rows in the selected column that have a blank cell.
Delete empty text boxes in PowerPoint
Be aware that this code loops through all of the slides and deletes all text boxes that don't have any text. The count variable decrements instead of increments because each time the code deletes an object, it removes that object from the collection, which reduces the count.
Copy a contact from Outlook to Word
Be aware that this code copies the currently open contact in Outlook into the open Word document. This code only works if there is a contact currently open for inspection in Outlook.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Was this page helpful?
Submit and view feedback for
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 .
Table of Contents
What are Excel macros?
How to record excel macros, how to run an excel macro, run excel macro from a shortcut key, saving macro-enabled workbooks.
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!
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 S tore 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.
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.
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.
Now you can quickly run your macros using the HIDE and UNHIDE buttons.
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
Try to use the shortcut Ctrl + Q to quickly apply formatting to entire rows.
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.
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 .
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!
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- Labs The future of collective knowledge sharing
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Adding a macro file to an XLSX/XLSM file using Packaging
I'm using System.IO.Packaging to build simple Excel files. One of our customers would like to have an autorun macro that updates data and recalcs the sheet.
Pulling apart existing sheets I can see that all you need to do is add the vbaProject.bin file and change a few types in the _rels. So I made the macro in one file, extracted the vbaProject.bin , copied it into another file, and presto, there's the macro.
I know how to add package parts when they are in XML format, like the sheets or the workbook itself, but I've never added a binary file and I can't figure it out. Has anyone done this before?
- overall, this is out of my range, but in the title you ask to add a macro file to an xslx file, but xlsx files cannot hold macro files. Only xlsm and xlsb (and add-in / template files) – Scott Holtzman Feb 5, 2018 at 21:40
- I change the extension if there is a macro file passed in. – Maury Markowitz Feb 5, 2018 at 22:15
- I made the macro in one file, extracted the vbaProject.bin, copied it into another file, and presto, there's the macro - taking you at your word that that works. Why can you not just treat the package like the zip file it is and include the "vbaProject.bin" file using the .Net Zip library of your choice? – TnTinMn Feb 5, 2018 at 22:30
- Actually, that's a good question... let's see. – Maury Markowitz Feb 6, 2018 at 11:34
Ok I got it. Following TnTinMn's suggestion:
Open a new workbook and type in your macro. Change the extension to zip, open it, open the xl folder and copy out the vbaProject.bin to somewhere easy to find.
In your .Net code, make a new Part and add it to the Package as 'xl/vbaProject.bin'. Copy over byte-for-byte from the vbaProject.bin you extracted above. It will be compressed as you add the bytes.
Then you have to add a relationship to the workbook that points to your new file. You can find those relationships in xl/_rels/workbook.xml.rels .
You also have to add a content type entry at the root of the document, which goes into the [Content Types].xls . This happens automatically when you use the ContentType parameter of CreatePart
And finally, change the extension to .xlsm or .xltm
I'm extracting the following from many places in my code, so this is pseudo...
- One note: if the macro refers to sheet names that don't exist in the new file, it will create invisible sheets with those names. This is not a major problem, but you can avoid it by ensuring any name you refer to in the macro is in the new book as well. – Maury Markowitz Mar 19, 2018 at 17:24
- I have very similar logic, however for my updater I copy over a VBA Certificate signature as well. If you want to do this too, make sure to copy over the "vbaProjectSignature.bin", "vbaProjectSignatureAgile.bin" and "_rels\vbaProject.bin.rels" files and ensure there is a reference to the signatures in "[Content_Types].xml" for these new files. – David Rogers Mar 17, 2020 at 17:50
Sign up or log in, post as a guest.
Required, but never shown
Not the answer you're looking for? Browse other questions tagged vb.net excel system.io.packaging vba or ask your own question .
- The Overflow Blog
- Journey to the cloud part I: Migrating Stack Overflow Teams to Azure
- Featured on Meta
- Our Design Vision for Stack Overflow and the Stack Exchange network
- Temporary policy: Generative AI (e.g., ChatGPT) is banned
- Call for volunteer reviewers for an updated search experience: OverflowAI Search
- Discussions experiment launching on NLP Collective
Hot Network Questions
- Electrical issues while central air is running
- Are there any good alternatives to firearms for 1920s aircrafts?
- Is this duplo train track under too much tension?
- Why the penetrating depth of an electromagnetic radiation isn't consistent with its frequency?
- Of all, is this the idiomatic way of saying it: "You smell like sweat."
- What does ggf reserviert mean on DB trains?
- Shareware computer game where you play a starfighter pilot
- Why do STM32 MCUs divide RAM into SRAM1 and SRAM2?
- Why do people do a postdoc, rather than getting another PhD?
- Can one performer manage striking tubular bells and timpani simultaneously?
- Does the D-Wave hardware show any advantage for academic use-cases, for example in condensed matter physics?
- Does theism have the burden of proof?
- Confused about the definition of a limit point
- Question about number format for numbers between zero and one
- Will a buck converter clean the power output from an automotive?
- What are some good books on mathematical pedagogy?
- Are multiple extension cords in series causing significant increase in electric use?
- How does Legendre transformation in classical mechanics relate to Adrien-Marie Legendre?
- Is an “immaterial being” any less nonsensical than a “smelly color”?
- Does anyone know this skyline?
- Manned Spacecraft/Space Station design Requirements
- Risky Surgery and resistance to slashing damage
- Intercepting a grappled Bite Swallow attack in place of an ally with Vigilant Guardian: What happens?
- Why is there an indefinite article before the proper noun in "He lacked the analytic processing power of a Hamilton"?
Microsoft is bringing Python to Excel
Microsoft today announced the public preview of Python in Excel, which will allow advanced spreadsheet users to combine scripts in the popular Python language and their usual Excel formulas in the same workbook.
This feature will first roll out to Microsoft 365 Insiders as part of the Excel for Windows beta channel. Yet while the feature will first only be available in the desktop version of Excel, Microsoft notes that the Python calculations will run in the Microsoft Cloud. Python runs perfectly well on any modern PC, so I’m not sure why Microsoft went the cloud route here.
“Now you can do advanced data analysis in the familiar Excel environment by accessing Python directly from the Excel ribbon,” Stefan Kinnestrand, the GM for Modern Work at Microsoft, explains. “No set up or installation is required. Using Excel’s built-in connectors and Power Query, you can easily bring external data into Python in Excel workflows.”
Image Credits: Microsoft
Microsoft partnered with data science platform Anaconda to bring this feature to life. The company is using the Anaconda Python distribution — running in Azure — to bring the most popular Python libraries to Excel, including the likes of Matplotlib and seaborn for data visualization.
To try this out, you’ll have to join the Microsoft 365 Insider Program and opt for the beta channel to get the latest Excel builds. From there, it’s just a question of selecting “insert Python” in the Formulas ribbon to get started.
It’s worth noting that there have long been libraries that allowed Python users to work with Excel files, as well as (paid) Excel add-ons like PyXLL that bring Python’s functionality to Microsoft’s spreadsheets, too.
Open-source libraries and Python in Excel
Python in Excel is currently in preview and is subject to change based on the feedback. To use this feature, join the Microsoft 365 Insider Program and choose the Beta Channel Insider level.
Python in Excel is gradually rolling out to Excel for Windows customers using the Beta Channel. At this time, the feature is not available on other platforms.
If you encounter any issues with Python in Excel, please report them by selecting Help > Feedback in Excel.
New to Python in Excel? Start with Introduction to Python in Excel and Getting started with Python in Excel .
Open-source Python libraries
Python in Excel comes with a standard set of Python libraries provided by Anaconda through a secure distribution. Use these Python libraries to simplify your data analysis, find patterns and hidden insights, and visualize your data with plots.
Core Python in Excel libraries
The following open-source libraries are available with Python in Excel by default. They've been imported with the statements listed.
matplotlib. Import statement: import matplotlib.pyplot as plt
NumPy. Import statement: import numpy as np
pandas. Import statement: import pandas as pd
seaborn. Import statement: import seaborn as sns
statsmodels. Import statement: import statsmodels as sm
Note: These core libraries are also listed in the Python in Excel initialization task pane. Access the initialization task pane by selecting Formulas > Initialization in the Excel ribbon. This task pane is currently read-only and shows the initialization settings for your Python in Excel runtime.
How to import libraries
In addition to the core libraries, you can import additional libraries available through Anaconda. Import Python libraries into Excel using a Python import statement in a Python in Excel cell, such as import numpy as np . This statement imports the NumPylibrary and assigns it the alias np . After entering this import statement into a Python cell, you can refer to the NumPy library as np throughout the Python formulas in that workbook.
Tip: To ensure that your libraries are imported before your Python formulas run, enter your import statements and any settings on the first worksheet in your workbook. If desired, you can reserve the first worksheet specifically for the import statements and settings.
List of recommended libraries
The following table shows a subset of the open-source libraries provided by Anaconda that you can use with Python in Excel. The libraries matplotlib, NumPy, seaborn, statsmodels, and pandasare imported by default. The additional libraries listed in the table are not automatically imported, but you can choose to import them if desired.
Important: To protect your data security, these libraries will not have the ability to make network requests or access your files and data on your local machine. To learn more, see Data Security and Python in Excel .
Learn more from Anaconda
To learn more about the integration and supported libraries, visit Anaconda .
Introduction to Python in Excel
Getting started with Python in Excel
Creating Python in Excel plots and charts
Python in Excel DataFrames
Need more help?
Want more options.
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Microsoft 365 subscription benefits
Microsoft 365 training
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.
Ask the Microsoft Community
Microsoft Tech Community
Microsoft 365 Insiders
Was this information helpful?
Thank you for your feedback.
Python is coming to Microsoft Excel
Ever wished you could do more with Microsoft Excel ? Microsoft just announced the release of a public preview of Python in Excel, which would allow users to add Python code directly into a spreadsheet.
This would enable data analysts, engineers, marketers, and students learning data science to work with Python code to perform complex statistical analysis, advanced visualizations, predictive analytics, and machine learning in Excel.
Also: How to use ChatGPT to write Excel formulas
Users will be able to enter Python code directly into cells using the new =PY function, as Python will be integrated directly into the Excel grid, with no need to install additional software.
Microsoft explains that the new functionality leverages the Anaconda distribution of Python, an enterprise geared to data scientists and engineers that is also beginner-friendly. Anaconda includes many pre-packaged libraries and packages like pandas, Matplotlib, scikit-learn, NumPy, and SciPy.
Date extraction using regular expressions.
As a secure operation, Microsoft says Python in Excel runs on the Microsoft Cloud with enterprise-level security within the Microsoft 365 experience. This means that the code is executed on the Microsoft Cloud and not locally, in an isolated container using Azure Container Instances and separate from other processes to diminish the risk of unauthorized access.
Also: How to use ChatGPT to write code
The data in users' workbooks is controlled through the specific functions xl()and =PY() to ensure data is secure and only authorized operations are performed.
The public preview of the Python integration on Microsoft Excel will be available to Microsoft 365 Insiders using the Beta Channel in Excel for Windows.