VBA Code in Excel: How to Add and Run Macros
In this article
To put VBA code into Excel, you must open the Visual Basic Editor (VBE) using the shortcut Alt + F11, insert a new module via the Insert menu, paste your code into the window, and save the workbook as an Excel Macro-Enabled Workbook (.xlsm). This process allows you to automate repetitive tasks, create custom functions, and manipulate data across sheets far more efficiently than using standard formulas.
What You'll Need
- A desktop version of Microsoft Excel (VBA is not supported in Excel for the Web).
- The VBA code you wish to implement (either written by you or sourced from a trusted provider).
- Administrative permissions on your computer to enable the Developer tab.
- A backup of your current spreadsheet, as VBA actions cannot be undone using the Undo button.
Step-by-Step
- Enable the Developer Tab: By default, the tools needed for VBA are hidden. Right-click any existing tab on the Ribbon (such as Home or Insert) and select Customize the Ribbon. In the right-hand column, find the checkbox labeled Developer and check it. Click OK. Note that menu labels may differ slightly depending on your version of Office or regional settings.
- Open the Visual Basic Editor: With your workbook open, click the Developer tab and select the Visual Basic button on the far left. Alternatively, you can press Alt + F11 on your keyboard to jump directly into the editor. This opens a separate window where the actual coding environment resides.
- Insert a Module: In the Project Explorer pane on the left side of the VBE window, you will see a folder structure representing your open workbooks. Right-click on the name of your current workbook (e.g., VBAProject (Book1)), hover over Insert, and select Module. This creates a blank white space where your code will live. It is important to use a Module for general macros rather than putting code inside "ThisWorkbook" or specific "Sheet" objects, as this ensures the code is accessible globally across the file.
- Paste the VBA Code: Copy your desired code and paste it into the main window of the new module. Ensure that the code starts with a declaration like "Sub MacroName()" and ends with "End Sub". If you are adding a custom function, it will start with "Function FunctionName()" and end with "End Function".
- Save the Workbook Correctly: You cannot save VBA code in a standard .xlsx file. Go to File > Save As. In the file type dropdown menu, select Excel Macro-Enabled Workbook (*.xlsm). If you save it as a standard workbook, Excel will strip all the VBA code from the file upon closing, and you will lose your work.
- Run the Macro: Close the VBE window to return to your spreadsheet. To execute the code, go to the Developer tab and click the Macros button. Select the name of your macro from the list and click Run. Alternatively, you can assign the macro to a button by going to Insert > Button (Form Control) on the Developer tab, drawing the button on your sheet, and selecting the macro to link to it.
Common Mistakes
One of the most frequent errors is failing to save the file in the .xlsm format. Users often spend hours writing complex scripts only to save the file as a standard .xlsx, which permanently deletes the code. Always double-check the file extension before closing the application.
Another common mistake is ignoring the "Undo" limitation. Unlike typing in a cell or formatting a table, actions performed by a VBA macro cannot be reversed using Ctrl + Z or the Undo arrow. If a script deletes 1,000 rows of data, those rows are gone unless you have a saved backup of the file. Always test your code on a duplicate copy of your data first.
Many beginners also forget to enable macros when reopening a file. Because macros can be used to deliver malware, Excel disables them by default. When you open an .xlsm file, you will usually see a yellow security warning bar at the top of the screen. You must click "Enable Content" for the code to function.
Lastly, naming conflicts are a regular issue. You cannot name a macro the same thing as a module, nor can you use spaces in the name of a Sub procedure. For example, "Sub My Macro()" will trigger a syntax error; it must be "Sub My_Macro()" or "Sub MyMacro()".
Tips
To make your code easier to manage, use the "Comments" feature. By placing an apostrophe (') at the start of a line, you turn that line green, and Excel ignores it during execution. Use this to document what each section of your code does, which is invaluable when you return to the project months later.
If you find yourself using the same VBA code across many different workbooks, consider saving the code in the Personal Macro Workbook (Personal.xlsb). This is a hidden workbook that opens every time you start Excel, making your custom macros available regardless of which file you are currently working in.
For better performance, especially with large datasets, add "Application.ScreenUpdating = False" at the beginning of your macro and "Application.ScreenUpdating = True" at the end. This prevents Excel from flickering and redrawing the screen after every single single action the code takes, which can speed up execution time significantly.
Use the F8 key while in the VBE to "Step Into" your code. This allows you to run the macro one line at a time. As you press F8, the current line is highlighted in yellow, allowing you to watch exactly how the data changes in your spreadsheet in real-time, which is the most effective way to learn how the code works.
Troubleshooting
If your macro does not run, first check the security settings. Go to File > Options > Trust Center > Trust Center Settings > Macro Settings. Ensure that "Disable VBA macros with notification" is selected. If macros are completely disabled without notification, your code will never trigger.
If you encounter a "Compile Error: Variable not defined," it is likely because you have "Option Explicit" at the top of your module. This is actually a good practice, as it forces you to declare every variable using a "Dim" statement. To fix this, either declare the missing variable (e.g., Dim myValue As Integer) or remove the "Option Explicit" line from the top of the code.
If the VBE window freezes or Excel crashes during a loop, press Ctrl + Break (or Esc) repeatedly to force the code to stop. If the code is stuck in an infinite loop, you may need to force-close Excel via the Task Manager, though this will result in the loss of any unsaved data.
If you receive a "Runtime Error 1004," this is a generic error that usually means Excel cannot find the object you are referencing. Check that the sheet names in your code match the actual names of the tabs in your workbook exactly, including spaces and capitalization.
Frequently Asked Questions
Can I use VBA on Excel for Mac?
Yes, VBA is supported on Mac, though the user interface for the Visual Basic Editor is different and some Windows-specific functions (like those involving FileSystemObject or certain ActiveX controls) will not work.
Does VBA work on the web version of Excel?
No, VBA does not run in a browser. For automation in Excel for the Web, Microsoft uses Office Scripts, which is based on TypeScript/JavaScript rather than VBA.
Is there a limit to how much VBA code I can add?
There is no practical limit to the amount of code you can add to a module, but extremely large projects can slow down the editor. It is better to split complex projects into multiple modules.
Can I password protect my VBA code?
Yes. In the VBE, go to Tools > VBAProject Properties, click the Protection tab, check "Lock project for viewing," and enter a password. This prevents others from seeing or editing your scripts.
What is the difference between a Sub and a Function?
A "Sub" (Subroutine) performs a series of actions, such as formatting a sheet. A "Function" performs a calculation and returns a specific value, allowing it to be used as a custom formula directly inside a cell.