Skip to content

Read and edit a macro in the VB Editor

Record and run macros9 minPremium

Builds on Record your first macro.

A sales analyst in Austin inherited a macro that formats the quarterly report. It sets the headings to 11 point, and the director wants 12. Changing one number in the code is quicker than recording the whole routine again.

How it works

Press AltF11, or select Visual Basic on the Developer tab, to open the VB Editor. View > Macros, then a macro and Edit, opens it at that macro.

  • The Project Explorer, on the left, lists each open workbook as a VBAProject. Recorded macros are in its Modules folder, usually in Module1. Double-click a module to show its code.
  • The code window shows the module. A macro starts with Sub and its name, and ends with End Sub.
  • Lines in green that start with an apostrophe are comments: notes for people, which VBA skips.

The recorder writes more than a person would. It selects cells and then works on the Selection, and a dialog such as Format Cells gives a line for each setting in it, whether you changed it or not. Change a value or delete a line, save with CtrlS in the editor, and run the macro again on a copy to check it.

Example

This is part of what the recorder wrote for the headings: select A1:D1, bold them, set the font in Format Cells, fit the columns, then click A2.

VBA
Sub FormatHeadings()
'
' FormatHeadings Macro
'
Range("A1:D1").Select
Selection.Font.Bold = True
With Selection.Font
.Name = "Aptos Narrow"
.Size = 11
.Strikethrough = False
.Superscript = False
.Underline = xlUnderlineStyleNone
End With
Columns("A:D").EntireColumn.AutoFit
Range("A2").Select
End Sub
What the recorder wrote: it selects the cells, then sets every font setting in the dialog, changed or not.

The same job, tidied, with the director's 12 point:

VBA
Sub FormatHeadings()
Range("A1:D1").Font.Bold = True
Range("A1:D1").Font.Size = 12
Columns("A:D").AutoFit
End Sub
The tidy version: no selecting, and only the settings that change.

Common mistakes

  • Looking for a recorded macro under Sheet1 or ThisWorkbook. Those modules hold code that runs on events; the recorder puts macros in a module under Modules.
  • Deleting End Sub or End With along with the lines around it. VBA then refuses to run the macro.
  • Testing an edit on the only copy of a file. Excel can't undo a macro, so try it on a copy.

In short

  • AltF11 (OptionF11 on a Mac) opens the VB Editor, and recorded macros are in a module under Modules.
  • A macro runs from Sub to End Sub; green lines after an apostrophe are comments.
  • You can change a value or delete a line the recorder added, then test the macro on a copy.

Practice

Premium

4 exercises: 1 shortcut, 2 macros and 1 quiz question.

Practice is part of Premium

Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.