4.4 · Macros & VBA programming

Level 4 · Expert: Power Query, data model & VBA

4.4Macros & VBA programming

Goal: Automate a repetitive task with a macro and understand the basics (and risks) of VBA.
Estimated time: 14 min · self-paced reading · If you only have 5 min: read “The essentials in 30s” + the diagram.

The essentials in 30 seconds

  • Record, then re-read: a macro memorizes a sequence of actions in VBA — you replay the weekly report, formatted identically, in one click.
  • Read the editor (Alt+F11) to progress: change a range, a value, a color in the generated code — short and focused macros, tested on a copy.
  • Wassim's reflex: a macro doesn't undo (Ctrl+Z useless) and can be malicious — save the workbook as .xlsm, trusted sources only.

Running mini-case — Wassim replays his Monday formatting in one click

Wassim, an accountant in Algiers, formats the same report every Monday (frozen panes, bold headers, amounts in dinars, AutoFilter). He records a « FormatReport » macro, opens the code with Alt+F11, spots the lines and adjusts the range. Saved as .xlsm, one click replays everything — tested first on a copy, because a macro doesn't undo. Fourth milestone of the running thread: the repetitive interface work is automated, carefully.

Continuation of cases 4.1-4.3 — Wassim automates what neither Power Query nor the formulas do: the interface gestures.

1. Record a macro

A macro memorizes a sequence of actions to replay them. Developer ▸ Record Macro: you perform the gestures (format, filter, paste…), you stop recording. Excel generates VBA code. Replaying the macro reproduces everything instantly — ideal for Wassim's weekly report, formatted identically.

You keep macros short and focused: one task = one macro. The monsters that do everything are unreadable and break at the first structural change.

2. Read and adapt the VBA

The code opens in the VBA editor (Alt+F11). Even without being a developer, you can read and adapt it: change a value, a range, a color. It's the best way to learn: record, then understand the produced code — Wassim quickly spots the lines for bold and currency format.

VBA manipulates objects (workbook, sheet, range) with properties and methods: Worksheets, Range, Font.Bold, NumberFormat… Understanding this vocabulary is enough to adapt 80% of recorded macros.

3. Precautions

A workbook with macros is saved as .xlsm — as .xlsx, the macros are lost. Macros can be a virus vector: only enable those from trusted sources, with full awareness. Another limit: a macro doesn't « undo » (Ctrl+Z doesn't reverse its actions) — you test on a copy.

Finally, for simple data transformation, Power Query is often preferable to VBA: no code, refreshable, safer. VBA stays relevant for automating varied interface actions (formatting, dialog boxes, interactions between sheets).

Common misinterpretation: « Macros undo with Ctrl+Z, you can enable them from anywhere, and VBA replaces Power Query everywhere ». No on all three points. A macro modifies the workbook with no possibility of undo — hence the test on a copy. A macro from an unknown source can be malicious — hence enabling with full awareness, trusted sources only. And to transform data, Power Query (no code, refreshable) beats VBA; VBA shines on varied interface gestures.
From macro to code Record the gestures, read the produced VBA, adapt it, then replay it Record The MondaygesturesVBA code Generatedon its ownRead / adapt Rangesand formatsReplay In oneclick (.xlsm)
Record the gestures, read the produced VBA, adapt it, then replay it
Text version of the diagram (SEO / screen readers / translation): 1) Wassim records his weekly formatting via Developer ▸ Record Macro. 2) He opens the code with Alt+F11 and spots the lines for bold, format and filter. 3) He adapts a range and a color, saves as .xlsm, then replays on a copy to check. 4) The following Monday, one click replays everything identically. Lesson: record gestures, read the VBA, adapt carefully, replay — never without a test copy or a trusted source.

🔎 Concrete example — 🔎 Concrete example — Automate a weekly formatting

Every Monday, Wassim formats the same report; the recorder produces this VBA:

Sub FormatReport()
    ' Freeze panes + bold headers (Wassim: weekly report)
    Range("A2").Select
    ActiveWindow.FreezePanes = True
    Rows("1:1").Font.Bold = True
    ' Amounts in dinars + auto-filter
    Columns("C:C").NumberFormat = "#,##0 DZD"
    Range("A1").AutoFilter
End Sub

Reading: the recorder turns clicks into reusable, readable code.

Lesson: you automate the repetitive AND reproducible; you test on a copy (no undo).

Section vocabulary

Macro
A recorded sequence of actions to be replayed in one click.

Simple example: Wassim's FormatReport replays his Monday formatting.

What it is not: a formula that recalculates by itself.

Reflex: an identical weekly gesture: record it as a macro.

VBA
Visual Basic for Applications: the language of Excel macros (objects, properties, methods).

Simple example: Wassim reads Range and Font.Bold in his recorded code.

What it is not: Power Query's M language (data preparation).

Reflex: adapting a macro: spot objects and properties.

.xlsm
The workbook format that supports macros; .xlsx loses them.

Simple example: Wassim saves his automated report as .xlsm.

What it is not: an .xlsx workbook that would keep the macros.

Reflex: macro created: save as .xlsm immediately.

Macro security
Macros can be malicious: enable with full awareness, trusted sources.

Simple example: Wassim only enables his own macros and those validated by the firm.

What it is not: inherently harmless code, enableable without thinking.

Reflex: macro received: check the source before enabling.

In practice — In practice — Record and re-read a macro

  1. Enable the Developer tab, then Record Macro.
  2. Perform a simple formatting, stop recording.
  3. Open the code (Alt+F11) and spot the matching lines.
  4. Change a value (e.g. color), save as .xlsm, replay on a copy.
You automate a repetitive task and can read/adapt the generated code, carefully.

Ready-to-say script — announce the macro to the team (30 s)

« This is Wassim: the Monday report formatting is recorded as a macro — one click replays everything: panes, bold, dinars format, filter. The workbook is .xlsm, I tested it on a copy because a macro doesn't undo. Only enable our validated macros. »

Say it before distributing the file: remind them of the .xlsm and the trusted source.

Copy-paste template — safe VBA loop over a range (with a test copy)

Sub NormalizeAmounts()
    Dim c As Range
    Application.ScreenUpdating = False
    For Each c In Worksheets("Sales").Range("C2:C500")
        If IsNumeric(c.Value) Then c.Value = Round(c.Value, 2)
    Next c
    Application.ScreenUpdating = True
    MsgBox "Amounts normalized (tested on a copy)."
End Sub

Weekly formatting

Like Wassim: record panes, bold, DZD format and filter — one click every Monday.

Adapt the code

Change the range C2:C500 or the format in the editor: the macro follows the new structure.

Macro received by email

Unknown source: don't enable it — request validation, analyze with full awareness.

Data to transform

Prefer Power Query (no code, refreshable) over a fragile macro.

Caution: Macros are enabled with full awareness and only from trusted sources: a booby-trapped workbook can run malicious code. Save as .xlsm (otherwise macros are lost) and always test on a copy, because a macro doesn't undo with Ctrl+Z.

✓ Best practices

  • Record first, read the code next to learn.
  • Keep macros short and focused.
  • Test on a copy (a macro doesn't undo).

✗ Common pitfalls

  • Enabling macros from unknown sources (viruses).
  • Forgetting to save as .xlsm (macros lost).
  • Using VBA where Power Query would do better (data transformation).

Key takeaways

  • A macro replays a sequence of actions; the code is VBA.
  • You record, then read/adapt in the editor (Alt+F11).
  • Workbook with macros = .xlsm; macros = a security risk.
  • A macro doesn't undo: test on a copy.

48h challenge — apply tomorrow

On a copy of a real report: record your formatting, re-read the code in Alt+F11, change a value, save as .xlsm and replay.

Section exit checklist
  • I know how to record and replay a focused macro.
  • I know how to read and adapt the generated VBA (range, value).
  • I know the precautions (.xlsm, test copy, trusted sources).
Self-assessment 1-5: could I adapt a line of VBA unaided?did I test my last macro on a copy before distributing it?

Frequently asked questions

Macro (VBA) or Power Query?

To transform/consolidate data: Power Query (no code, refreshable, safer). To automate varied interface actions (formatting, dialog boxes, interactions), VBA stays relevant.

Do you need to know how to program to use macros?

No to record and replay; a little to adapt the code. It's actually a good entry point to programming: record an action and read the matching VBA.

Check your understanding

Which precaution is specific to macros?

Additional resources (optional, to go further)

Level 4 examFresh, harder questions to test what you've learned