Excel VBA programming means using Visual Basic for Applications, Excel’s built-in programming language, to automate workbook tasks and add custom behavior. In desktop Excel for Microsoft 365 on Windows, you can write a macro in the Visual Basic Editor, run it from the ribbon or a button, and save it in a macro-enabled workbook.
What Excel VBA is—and what it is not
VBA is a programming language included with desktop versions of Microsoft Office. In Excel, it can work with workbooks, worksheets, cells, charts, tables, and many other parts of the application. A VBA procedure that performs an action is commonly called a macro. Some macros are short, such as formatting a report; others coordinate multiple steps across sheets or files.
VBA is different from a worksheet formula. A formula calculates a result in a cell, usually when its inputs change. A macro runs instructions when someone starts it or when a programmed event occurs. For example, a formula can calculate a line total, while VBA could import a set of files, prepare a report, and save the finished workbook.
VBA is also not the same as Office Scripts, Excel’s other automation option. Office Scripts use TypeScript and are designed for Excel on the web and Microsoft 365 workflows. VBA remains useful for desktop automation and established macro-enabled workbooks, but it is not a way to make VBA macros run in a web browser.
How VBA works inside Excel
Excel exposes its features to VBA through an object model. Objects include the application, a workbook, a worksheet, and a range of cells. A procedure can refer to those objects, read or change their properties, and call their methods. For instance, a macro can tell a worksheet range to clear its contents or assign a value to a cell.
VBA code is stored in a workbook or in another location, such as the Personal Macro Workbook. A standard macro is usually placed in a module. Excel can also hold code associated with a particular worksheet or workbook, including event procedures that respond to actions such as opening a workbook or changing a cell. Event-driven automation can be helpful, but it should be documented because the code may run without the user clicking a macro button.
To access the tools in Excel for Microsoft 365 on Windows, enable the Developer tab through File > Options > Customize Ribbon, then select Developer. Open the Visual Basic Editor with Developer > Visual Basic or press Alt+F11. In the editor, use Insert > Module to add a standard module. On Mac, enable Developer through Excel > Settings (or Preferences, depending on the release) > Ribbon & Toolbar; the editor is available from Developer or Tools, and Option+F11 may open it. Shortcut behavior can depend on the Mac keyboard’s function-key settings.
Write and run a first macro
This example reads order quantities from column B on a worksheet named Orders and writes twice each numeric quantity to column C. It uses column A to find the last row containing an order identifier. Before running any macro, save a copy of the workbook: macros can change data, and their actions cannot be undone with Ctrl+Z (Command+Z on Mac).
Option Explicit
Sub DoubleQuantities()
Dim ws As Worksheet
Dim lastRow As Long
Dim rowNum As Long
' Use a copy of the workbook before running this macro.
Set ws = ThisWorkbook.Worksheets("Orders")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("C1").Value = "Double quantity"
For rowNum = 2 To lastRow
If IsNumeric(ws.Cells(rowNum, "B").Value) Then
ws.Cells(rowNum, "C").Value = ws.Cells(rowNum, "B").Value * 2
Else
ws.Cells(rowNum, "C").ClearContents
End If
Next rowNum
End Sub
The example assumes that the sheet exists, identifiers begin in A2, and quantities begin in B2. It writes results in column C and replaces existing content there; rows with nonnumeric quantities have their corresponding C cells cleared. If the sheet name is different, change the name in the code. To run it in Windows Excel, return to the workbook, choose Developer > Macros, select DoubleQuantities, and choose Run. The Mac ribbon has a Developer tab too, though exact shortcut behavior may differ.
For a workbook that must retain VBA, save it as an Excel Macro-Enabled Workbook (.xlsm), rather than as a standard .xlsx file. The .xlsx format does not store VBA macro code. When reopening a macro-enabled file, Excel may display a security notice; only enable macros when you trust the file and understand what it is intended to do.
Common uses for Excel VBA
VBA is most useful when a repeatable task involves several actions that would otherwise require the same sequence of clicks. Typical examples include preparing recurring reports, copying selected data into a template, applying consistent formatting, validating entries, and combining information from worksheets. A macro can also create a custom form or add a button that starts a procedure.
- Report preparation: format headings, set print areas, refresh selected workbook content, and prepare sheets for review.
- Data handling: move or reshape rows, check for missing values, or split a process into repeatable stages.
- Workbook interaction: respond to a button click, open a form, or run a controlled action when a workbook event occurs.
- Connecting desktop tasks: automate certain interactions with other Office applications, subject to the installed applications, permissions, and platform.
Automation does not automatically make a process more reliable. A macro can repeat a mistaken assumption just as consistently as a correct one. Good designs make inputs and outputs clear, handle unexpected values, avoid overwriting unrelated cells, and provide a way to review results.
VBA compared with formulas, Power Query, and Office Scripts
Choose the tool that matches the task rather than using VBA for every spreadsheet problem. A normal formula is often easier to inspect and maintain when the goal is to calculate values in cells. Power Query, available through Excel’s data tools, is usually a stronger fit for importing, cleaning, and combining data through a repeatable sequence of transformations. It can refresh that process without requiring a custom macro.
VBA is a practical choice when automation needs to control desktop Excel’s interface or perform actions that formulas and query steps do not address conveniently. Office Scripts may fit browser-based workbooks and cloud workflows better, especially when combined with Power Automate. VBA macros do not run in Excel for the web, even though the browser can open and edit many macro-enabled files. Users who need the automation itself to work in the browser should consider an alternative rather than assuming the VBA code will execute there.
For a workbook shared across Windows and Mac, test the actual tasks on both platforms. Many basic workbook operations are portable, but some VBA features, controls, and interactions with the operating system differ. Windows-specific API calls and ActiveX controls, for example, can limit portability. A simple macro that edits cells is generally a less complicated cross-platform case than one that depends on Windows system features.
Security, file formats, and compatibility
Macros can change or access workbook content, so treat VBA files as executable code rather than as passive documents. Do not enable macros in an unexpected attachment simply because the file looks like a spreadsheet. Follow your organization’s security rules, and ask an administrator if macro settings are managed centrally. Excel’s macro security options are under File > Options > Trust Center > Trust Center Settings > Macro Settings on Windows, but changing a setting to allow all macros is not a safe general recommendation.
Keep an untouched source copy and test new code on sample data. Before distributing a macro workbook, explain what the macro does, which sheets or columns it changes, and whether a user must enable it. Avoid storing passwords or other secrets in VBA code: workbook code should not be treated as a secure place for credentials.
VBA is available in desktop Excel, but Excel for the web cannot create, edit, or run VBA macros. A workbook can still contain a VBA project when opened in a browser, but that does not mean its macros are operating there. If colleagues use different Excel versions, operating systems, or security policies, test the workflow in those environments and provide a non-macro route when the task is important.
Learning VBA and diagnosing common problems
Beginners can start by recording a macro through Developer > Record Macro, performing a small task, and stopping the recording. The generated code can reveal how Excel represents actions, but recorded macros often include unnecessary selections and fixed cell references. Learning to use variables, loops, conditions, and direct references to worksheets and ranges makes code more adaptable.
Use Option Explicit at the top of a module to require declared variables. This helps catch misspelled variable names. Give variables meaningful names, add comments where the purpose is not obvious, and test on a small copy before applying code to a full workbook. When debugging, step through the procedure in the Visual Basic Editor and inspect the line where execution stops.
- “Subscript out of range”: a workbook, worksheet, or other collection item may not have the name the code expects. Check spelling and which workbook the code references.
- “Object variable or With block variable not set”: an object such as a worksheet may not have been assigned before the code uses it.
- The macro is missing or cannot run: check that the file is saved as .xlsm, that the correct workbook is open, and that security policy permits the macro.
- Unexpected overwritten data: identify every range the procedure writes to or clears, then test those actions on a copy before using real workbooks.
Frequently Asked Questions
Is Excel VBA the same as a macro? Not exactly. VBA is the programming language; a macro is an automated procedure, often written in VBA. Excel can also record user actions as a macro and generate VBA code for them.
Can I use VBA in Excel for the web? No. Excel for the web does not run, create, or edit VBA macros. Use desktop Excel to work with VBA, or consider Office Scripts for browser-based automation.
Do I need to know programming before learning VBA? No, but basic ideas such as variables, conditions, loops, and debugging make it easier to understand and adapt code. Recording a small macro can be a useful first look at the language.
Will saving as .xlsx keep my macros? No. Save a workbook containing VBA as .xlsm to retain its macro code. Keep a separate copy if you need a macro-free .xlsx version.
Can VBA damage or overwrite workbook data? Yes. A macro can clear or replace cells, and Ctrl+Z cannot undo macro actions. Review its code, save a backup, and test it on a copy before running it on important data.
Related
- Excel Redo Shortcut: How to Restore an Undone Action
- Excel Refresh Data Shortcut: Refresh All or a PivotTable
- Excel Shortcut to Paste Formatting and Keep Data
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Array AutoFilter: Filter Data in Memory or ExcelExcel’s VBA AutoFilter method filters a worksheet range or table; it does not filter a VBA array directly.…
- Excel VBA: Bring a Workbook Window to the Front ReliablyTo bring an open workbook to the front with Excel VBA, activate Excel and then activate the workbook:…
- Easy Macro Recorder in Excel: How to Record and Use OneYes. Microsoft Excel for Microsoft 365 includes a built-in macro recorder: choose Developer > Record Macro, perform the…
- Excel VBA Sort Order: Ascending, Descending, and CustomIn Excel VBA, set a sort field’s Order to xlAscending or xlDescending to choose its direction. For a…
- Excel VBA Object Required? Causes and FixesIn Excel VBA, “Object required” is usually run-time error 424: VBA expected an object reference but received a…
- VBA Excel: How to Find Unique Values in Two ColumnsTo find distinct values across two Excel columns with VBA, scan both columns into a dictionary and write…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.