Writing VBA Macros From Scratch

Excel’s macro recorder has a lot of power, but it has its limitations. As covered in another article, the macro recorder often records unnecessary code and can’t record things like logic or interactions with other programs. It can also be hard to use for longer macros – you may find yourself storyboarding your actions beforehand just to avoid making costly mistakes.

This article aims to help you begin coding macros from scratch in VBA. You’ll learn where Macros are stored, write a basic macro, and learn the basics of programming in VBA using variables, logic, and loops.

Getting Started

VBA and the Visual Basic Editor

VBA, or Visual Basic for Applications, is the language that macros are written in. All macros are stored as VBA code, whether they’re hand-coded or created with the macro recorder.

You can access all the VBA code in a workbook using the Visual Basic Editor. This is a special text editor and debugger that’s built-in to all office apps, including Excel. Typically, you’ll open this editor with the ALT+F11 keyboard shortcut in Excel, but you can also access it from Excel’s Developer tab if you have it enabled.

The Project Explorer

The Project Explorer is a window inside the VB Editor that shows you all the items that can have VBA code in them. If you don’t see this window, press F5 to make it appear or select Project Explorer from the View menu.

Double-clicking an item in the Project Explorer will show the code for that item. There are several types of items that can appear in the Project Explorer:

Although all these item types can include VBA code, the best practice is to code macros in Modules.

Making Your First Macro

Using the Macros List

The Macros List shows you all the macros in your workbook. From this list you can edit an existing macro, or create a new one.

To create a new macro using the Macros list:

After clicking “Create” the VB Editor will appear, showing the newly created macro. Excel will create a new module for the macro if necessary.

Manually in the VB Editor

You can add a new macro manually without the Macros list. This is the better option if you’d like to specify the module the macro is saved in.

To add a macro manually: