Microsoft Excel VBA is the programming language built into the desktop versions of Excel that lets you automate tasks, create custom procedures, and respond to workbook events. In Excel for Microsoft 365 on Windows, you can record a macro or write VBA in the Visual Basic Editor; save the workbook as an Excel Macro-Enabled Workbook (.xlsm) if it needs to retain the code.
What Excel VBA is
VBA stands for Visual Basic for Applications. It is used across several desktop Microsoft Office applications, including Excel, and provides a way to tell Excel what actions to perform. A VBA procedure can manipulate cells, worksheets, charts, and workbook settings through Excel’s object model: a structured set of objects and properties that represent parts of a workbook.
A macro is a procedure that performs a series of actions. Many Excel macros are written in VBA, though the words are sometimes used interchangeably. The language is more flexible than a recorded sequence of clicks: code can make decisions, repeat actions, inspect values, and respond to events such as opening a workbook or changing a cell.
VBA is part of desktop Excel rather than a separate spreadsheet product. It is useful when repeated work follows consistent rules, especially when built-in tools do not provide the needed interaction. It is not required for ordinary spreadsheet calculations, and a workbook can use formulas and Excel features without containing any VBA.
What VBA can automate
VBA can take over repetitive tasks that would otherwise involve many manual steps. For example, a macro could format a monthly report, copy selected data into a summary sheet, create a new worksheet for each department, or check records for missing information. It can also generate charts, prompt users for input, and open or save files.
VBA is especially useful when a workflow has rules that are awkward to express as a single formula. A procedure can examine each row, apply different actions depending on status, and produce a result. It can also connect actions across sheets in one workbook. However, macros can change or delete data, so code should be designed and reviewed with the workbook’s purpose in mind.
VBA does not make a workbook automatically reliable or secure. A macro follows the instructions it was given; it does not know whether a business rule is correct. For calculations that can be handled clearly with formulas, tables, PivotTables, or other built-in features, those options may be easier for other people to understand and maintain.
How VBA code runs in Excel
VBA code is organized into procedures, commonly called Sub procedures or functions. A Sub performs actions. A function returns a value and can sometimes be called from another procedure; VBA functions are not a general replacement for worksheet functions in every situation. A procedure can refer to objects such as a workbook, worksheet, range, or cell, then read or change their properties.
For example, a procedure may refer to a particular worksheet by name, find the last used row in a column, and check each row against a condition. The code runs inside Excel’s desktop application and operates on the workbook or other resources it is permitted to access. Macros can also be assigned to a button or run from the Macro dialog.
VBA also supports event procedures. These run when a defined event occurs, such as a workbook opening or a worksheet cell changing. Event-driven code can be convenient for forms and guided workflows, but it can be confusing if users do not know that actions are happening automatically. Clear instructions and restrained use of events make a workbook easier to operate.
Recording or writing a first macro
The macro recorder is a practical starting point if you want Excel to translate a sequence of actions into VBA. On Windows, show the Developer tab by going to File > Options > Customize Ribbon and selecting Developer. On Mac, use Excel > Settings > Ribbon & Toolbar and enable Developer. Menu wording can vary slightly by release.
- Save a copy of the workbook first, particularly if the task changes or clears data.
- On the Developer tab, select Record Macro. Give the macro a name that starts with a letter and contains no spaces; choose where to store it.
- Carry out the actions you want recorded. Use relative references if the same sequence should apply in relation to the selected cell; otherwise Excel may record fixed cell references.
- Select Stop Recording, then review the generated code in the Visual Basic Editor.
To write or inspect code, choose Developer > Visual Basic. On Windows, Alt+F11 opens the Visual Basic Editor; on Mac, the equivalent commonly uses Option+F11, sometimes with Fn depending on the keyboard and system settings. A recorded macro is a useful illustration of Excel’s object model, but it may include unnecessary selections or fixed references. Editing it into a smaller, clearer procedure often makes it more reusable.
A small VBA example
This example assumes a worksheet named Invoices, due dates in column C beginning in row 2, and payment statuses in column D. It colors cells A through D on rows where the due date has passed and the status is not Paid. It skips entries whose due-date value is not recognized as a date.
Sub HighlightUnpaidOverdueInvoices()
Dim ws As Worksheet
Dim lastRow As Long
Dim rowNum As Long
' Work with the named invoice sheet in this workbook.
Set ws = ThisWorkbook.Worksheets("Invoices")
lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
' Check each invoice row, starting below the headings.
For rowNum = 2 To lastRow
If IsDate(ws.Cells(rowNum, "C").Value) Then
If ws.Cells(rowNum, "C").Value < Date _
And ws.Cells(rowNum, "D").Value <> "Paid" Then
ws.Range("A" & rowNum & ":D" & rowNum).Interior.Color = RGB(255, 220, 220)
End If
End If
Next rowNum
End Sub
In the Visual Basic Editor, place the procedure in a standard module, then run it while the workbook is open. The code uses Date for the current date and colors qualifying rows pale red. If the worksheet name or column layout differs, change the references before running the macro. The comparison treats Paid as an exact text value, so a status such as Paid in full will not match it.
Save a copy before running any macro that changes a workbook. VBA actions generally cannot be reversed with Ctrl+Z, even if the change looks like an ordinary formatting edit. Test code on sample data and check the results before using it on a working file.
VBA, formulas, Power Query, and Office Scripts
VBA is one of several ways to automate Excel, and the best choice depends on the task and where the workbook will be used.
- Formulas are suited to calculations that should update as inputs change. They are visible in the grid and often easier to audit than code.
- Power Query is designed to import, clean, reshape, and combine data through repeatable steps. It is often a better fit than a macro for preparing data from files or databases.
- VBA can control desktop Excel actions, workbook objects, and interactive workflows. Its code runs in desktop Excel, not Excel for the web.
- Office Scripts provide a different automation approach for supported Microsoft 365 environments, particularly Excel on the web. They use TypeScript and are not VBA code.
VBA can be a sensible choice when an existing process already relies on desktop Excel macros, or when a desktop-only workflow needs custom buttons and event handling. For shared cloud workflows, browser use, or data transformation, compare the available alternatives before building a large VBA solution. A macro that works on one person’s computer may depend on local files, add-ins, or settings that another person’s setup does not have.
File formats and platform compatibility
An .xlsx workbook cannot store VBA project code. If you save a macro-containing workbook in that format, Excel warns that the code will be removed. Use .xlsm for a macro-enabled workbook, or .xlsb for an Excel binary workbook that can also contain VBA. The standard .xlsm format is usually the clearest choice when recipients need to recognize that a workbook contains macros.
Desktop Excel for Windows and Mac can run VBA, but not every Windows-specific feature is available on Mac. Code that depends on Windows API calls, ActiveX controls, or particular external components may need to be rewritten or may not work. Check compatibility when sharing a macro-enabled file across platforms, and avoid assuming that a workbook behaving correctly on one operating system will behave identically on another.
Excel for the web can open and edit many macro-enabled workbooks while preserving the VBA project, but it cannot create, edit, or run VBA macros. A user who needs to run the code must open the workbook in desktop Excel. This distinction matters when a team primarily works in a browser: a macro-enabled file does not make its macros available in the web app.
Macro security and safe use
Macros can make legitimate work faster, but VBA can also perform unwanted actions. Excel therefore applies security controls, and organizations may impose additional policies. Do not enable macros just because a workbook looks familiar. If a file arrived unexpectedly, confirm who sent it and whether a macro is necessary before allowing it to run.
On Windows, macro-related controls are available under File > Options > Trust Center > Trust Center Settings > Macro Settings. The exact choices available can depend on organizational policy. Avoid setting Excel to enable all macros globally. A trusted publisher or trusted location can be appropriate in managed workflows, but trust should be granted only when the source and purpose are understood.
When writing your own code, limit it to the actions the task requires. Avoid hard-coding passwords or sensitive information, and be cautious with procedures that delete files, overwrite workbooks, or access external resources. Keep a clean backup, document what the macro changes, and test with non-critical data before distributing it.
Common problems and troubleshooting
A macro that does not appear or run may be blocked, saved in the wrong format, or stored somewhere other than the workbook you expect. Confirm that the file is .xlsm or .xlsb, that the code is in the correct workbook, and that Excel has permitted the macro to run. If the workbook is open in a browser, switch to desktop Excel.
Errors can also come from small differences between the code’s assumptions and the actual sheet. A renamed tab, moved column, blank cell, or unexpected status value can change the outcome. When debugging, use the Visual Basic Editor’s step-through controls to run one line at a time and inspect the values being read. Add comments and descriptive variable names so that the purpose of each section is clear.
Another common issue is a macro that works only on the author’s computer. The code may refer to a local folder, a particular printer, an installed add-in, or a Windows-only component. Use workbook-relative references where appropriate, document external requirements, and test on the platforms and Excel versions that recipients will actually use.
Frequently Asked Questions
Is VBA included with Microsoft Excel?
VBA is included in desktop Excel for Windows and Mac. Excel for the web does not run VBA macros. Availability of desktop Excel depends on the Microsoft 365 or Office license and installation being used.
Can I use VBA in Excel for the web?
No. The web app can work with a macro-enabled workbook’s data, but it cannot create, edit, or run VBA code. Open the file in desktop Excel to use its macros.
How do I save an Excel file with a macro?
Save it as an Excel Macro-Enabled Workbook (.xlsm), or as .xlsb if that format suits the workflow. Do not use .xlsx when the VBA project must be retained.
Is VBA the same thing as a macro?
Not exactly. VBA is the programming language; a macro is an automation procedure, commonly written in VBA. Excel’s recorder can generate VBA code for a sequence of actions.
Can Excel macros be undone with Ctrl+Z?
Usually not. Running VBA generally clears Excel’s normal undo history, so save a backup and test the macro on a copy before applying it to important data.
Related
- Excel Slicer Examples for PivotTables and Tables Explained
- Excel Slicer Font Size: What You Can and Can’t Change
- Excel Slicer: Group Dates by Month
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA to Compare Two Word Documents AutomaticallyTo compare two Word files with VBA, open both documents and call Word’s Application.CompareDocuments method. It creates a…
- VBA Copy and Paste a Sheet: Code and OptionsTo copy a worksheet with VBA, use the sheet’s Copy method and specify where the duplicate should go.…
- VBA Range Column: How to Reference ColumnsIn VBA, reference a whole worksheet column with Columns("C") or Range("C:C"); to get the column containing a particular…
- Excel VBA Arrays vs Collections vs DictionariesIn Excel VBA, use an array for a compact, indexed set of values, a Collection for an ordered…
- VBA Copy and Paste to the Last Available RowTo copy data with VBA to the first available row after existing data, find the last occupied row…
- Excel VBA: Clear the Clipboard After Copy and PasteTo clear Excel’s copy mode after a VBA copy-and-paste operation, run Application.CutCopyMode = False after the paste. This…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.