Tabellab

What VBA Is and When It Beats Doing It by Hand

Lesson 1 of 8Reading

One key, one finished weekly report

A couple of minutes from now you will press F5 and watch Excel build a whole weekly report by itself: a new tab, a blue header, 20 rows for four shops, a formula in every row, 9 green days that beat the target, a total of 19,895, and a message box that tells you how long it took (usually a fraction of a second). The language doing it is VBA, Visual Basic for Applications, and it is already inside your copy of Excel: nothing to download, nothing to install. All companies, names and numbers are fictional.

When a macro earns its keep

  • Repetition: the same clean-up on a new export every Monday morning.
  • Volume: 40,000 rows, where doing it by hand costs an afternoon.
  • Consistency: a report that must look identical every single month, whoever builds it.
  • Things formulas cannot do: add sheets, name them, colour rows, save files, show a message box.
  • When not to bother: if a formula, a PivotTable or Power Query already solves it, use those. They need no code and nobody has to maintain them.

The recipe first, the code second

Every macro starts as a list of steps you could do by hand. Here is the weekly report as you would build it manually. Keep the numbers in mind: they reappear as comments in the code below.

  1. Add a new sheet and give it a name.
  2. Type four headers, make them bold, white on blue.
  3. Enter (or paste) 20 rows: shop, day, sales.
  4. Write a vs Target formula in every row and fill it down.
  5. Format the numbers with thousands separators.
  6. Colour every row that reached the target, one by one.
  7. Add a total and an average under the data.
  8. Widen the columns so everything is readable.

Run it in four steps

  1. Open any workbook and press Alt+F11 to open the Visual Basic Editor (on a Mac: Tools β†’ Macro β†’ Visual Basic Editor).
  2. Choose Insert β†’ Module. An empty page called Module1 appears: ordinary macros live there.
  3. Paste the macro below into it.
  4. Click anywhere between Sub WeeklyReport and End Sub, press F5 (or the green Run button), then switch back to Excel.
The macro only adds a new sheet and writes into it. Nothing on your existing sheets is read or changed, and each run makes a fresh tab, so run it as often as you like.
Option Explicit

Sub WeeklyReport()
    Const TARGET As Long = 1000

    Dim ws As Worksheet
    Dim shops As Variant
    Dim days As Variant
    Dim sales As Variant
    Dim i As Long
    Dim r As Long
    Dim lastRow As Long
    Dim hits As Long
    Dim started As Double

    started = Timer

    ' --- one fictional week for four shops, so the macro needs no file of yours ---
    shops = Array("Harbor", "Market", "Station", "Uptown")
    days = Array("Mon", "Tue", "Wed", "Thu", "Fri")
    sales = Array(820, 1140, 690, 1310, 905, _
                  760, 1020, 1480, 880, 640, _
                  1205, 970, 590, 1090, 1365, _
                  715, 1530, 845, 1010, 930)

    ' 1. a new sheet with a name that includes the time
    Set ws = ThisWorkbook.Worksheets.Add
    ws.Name = "Week " & Format(Now, "hh-mm-ss")

    ' 2. headers: bold white text on blue
    ws.Range("A1:D1").Value = Array("Shop", "Day", "Sales", "vs Target")
    With ws.Range("A1:D1")
        .Font.Bold = True
        .Font.Color = vbWhite
        .Interior.Color = RGB(30, 64, 175)
    End With

    ' 3. + 4. twenty rows, each with its own formula
    For i = 0 To 19
        r = i + 2
        ws.Cells(r, 1).Value = shops(i \ 5)
        ws.Cells(r, 2).Value = days(i Mod 5)
        ws.Cells(r, 3).Value = sales(i)
        ws.Cells(r, 4).Formula = "=C" & r & "-" & TARGET
    Next i
    lastRow = 21

    ' 5. number format for sales and difference
    ws.Range("C2:D" & lastRow).NumberFormat = "#,##0"

    ' 6. pale green for every day on or above target
    For r = 2 To lastRow
        If ws.Cells(r, 3).Value >= TARGET Then
            ws.Range(ws.Cells(r, 1), ws.Cells(r, 4)).Interior.Color = RGB(220, 252, 231)
            hits = hits + 1
        End If
    Next r

    ' 7. total and average below the data
    ws.Cells(lastRow + 2, 2).Value = "Total"
    ws.Cells(lastRow + 2, 3).Formula = "=SUM(C2:C" & lastRow & ")"
    ws.Cells(lastRow + 2, 3).NumberFormat = "#,##0"
    ws.Cells(lastRow + 3, 2).Value = "Average"
    ws.Cells(lastRow + 3, 3).Formula = "=AVERAGE(C2:C" & lastRow & ")"
    ws.Cells(lastRow + 3, 3).NumberFormat = "#,##0.00"
    ws.Range(ws.Cells(lastRow + 2, 2), ws.Cells(lastRow + 3, 3)).Font.Bold = True

    ' 8. column widths that fit the contents
    ws.Columns("A:D").AutoFit

    MsgBox hits & " of 20 days reached the target of " & Format(TARGET, "#,##0") & "." & vbNewLine & _
           "Built in " & Format(Timer - started, "0.00") & " seconds.", _
           vbInformation, "Weekly report ready"
End Sub

What you see on the new sheet

  • A tab called Week plus the current time, e.g. Week 14-03-22.
  • A1:D1: Shop, Day, Sales, vs Target in bold white on blue.
  • A2:D21: 20 rows. Column D holds real formulas: click D2 and the formula bar shows =C2-1000, which gives -180 for Harbor on Monday.
  • 9 rows in pale green, the days with sales of 1,000 or more (Uptown on Tuesday leads with 1,530).
  • B23:C24: Total 19,895 and Average 994.75: just under target, although almost half of the days beat it.
  • A message box: 9 of 20 days reached the target of 1,000. Built in 0.03 seconds. (your time will differ).

Your recipe, line by line

  1. Sub WeeklyReport() … End Sub: the container. Everything between is the macro, and WeeklyReport is the name Excel lists under Alt+F8.
  2. Option Explicit and the Dim lines: each Dim announces one variable (a labelled box) and what goes in it; Option Explicit makes VBA insist on that, which catches typos.
  3. Set ws = ThisWorkbook.Worksheets.Add: recipe step 1. It adds a sheet and keeps hold of it in ws. Objects such as sheets need Set; numbers and text do not.
  4. With ws.Range("A1:D1") … End With: step 2, three settings on the same block without repeating the address.
  5. For i = 0 To 19 … Next i: steps 3 and 4 as a loop. The indented block runs 20 times while i counts 0, 1, 2 … 19. i \ 5 is whole-number division, so rows 0–4 get Harbor, 5–9 Market, and so on.
  6. ws.Cells(r, 4).Formula = "=C" & r & "-" & TARGET: & glues text together, so row 2 receives =C2-1000 and row 21 =C21-1000.
  7. If … Then … End If: step 6, a decision per row. Only rows with 1,000 or more are coloured and counted in hits.
  8. MsgBox: the closing message. The space and underscore at the end of a line, _, simply continue the statement on the next line.

Try it: three one-minute changes

1. Change Const TARGET As Long = 1000 to 1200 and run again: only 5 rows turn green, column D now subtracts 1,200 and the message box agrees. 2. Swap the header colour for RGB(255, 235, 156) and the font colour for vbBlack: an amber header, the same report. 3. Change the first sales figure from 820 to 1050: Harbor on Monday turns green, the count rises to 10 and the total becomes 20,125. Every run adds a new tab, so you can compare them side by side.

Typical mistakes (everyone makes them once)

  • Saving as .xlsx: the macro lives inside the workbook, and .xlsx cannot store code. Excel warns once, most people click it away, and the module is gone on reopening. Save as Excel Macro-Enabled Workbook (.xlsm).
  • Ignoring the yellow bar: when you reopen an .xlsm file, macros stay switched off until you click Enable Content. Only do that for files you trust.
  • Cursor outside the Sub: if you press F5 with the cursor above Sub or below End Sub, Excel shows the macro list instead of running. Click inside the macro first.
  • Curly quotes: code copied through a word processor or a chat app can arrive with typographic quotes (β€œlike this”). VBA only accepts straight quotes ("), so the line turns red. Paste into the editor straight from the page.

The trap: Ctrl+Z cannot undo a macro

When a macro changes cells, Excel clears its undo history. There is no step back, not even for the last change. That is why the report macro writes only into a sheet it has just created, and why you should try any new macro on a copy of your file first.

Sub WhyUndoCannotHelp()
    ' Run this on a NEW, empty sheet only.
    ActiveSheet.Range("A1:A5").Value = "overwritten"
    ' Now press Ctrl+Z in Excel: nothing comes back.
End Sub
Run the three-line macro above on a new, empty sheet, then press Ctrl+Z (Cmd+Z on a Mac): the five cells stay overwritten. A habit that saves real work: save the workbook (or a copy) before you run anything that touches existing data.

How the course goes on

Next, The Visual Basic Editor takes the editor apart: the panes that matter, the Immediate window for testing a single line, and where code must sit for Excel to find it. In Your First Macro you write a macro from scratch and learn the thing . property = value pattern behind nearly every line above. Sub, End Sub, and Procedure Names explains the container and how small Subs call each other. After that come Dim and Option Explicit, MsgBox and InputBox, readable comments, and how to read the yellow line when a macro stops.

VBA in plain words: who this is for

If you open the same export every Monday, add the same headers, write the same formula, colour the same kind of row and send the same summary, you already know the problem VBA solves. Nobody minds doing a task like that once. It is the fiftieth time that hurts, and the fiftieth time is also when a tired person skips a step. VBA, Visual Basic for Applications, is the programming language built into the desktop versions of Excel for Windows and Mac. It lets you write those steps down once, as a short program called a macro, and replay them with one key whenever you need them.

This free first lesson of the course is written for people who use Excel every day but have never written code: analysts, accountants, office managers, sales coordinators, students who maintain a club spreadsheet. You do not need any programming background. You need a desktop copy of Excel, about fifteen minutes, and a little curiosity about what happens when you press F5. The macro in the lesson above builds a complete weekly sales report for four fictional shops. This article walks through the same example in more depth, explains when a macro is the right tool and when it is not, and shows you exactly what the code does so you can change it with confidence.

The core idea: a macro is a recipe Excel follows

Everything a macro does is something you could do by hand: add a sheet, type a header, enter a formula, change a colour, show a message. The difference is that a macro does it in the same order, with the same settings, every time, and in a fraction of a second. You can think of it as a recipe. The ingredients are the workbook, its sheets and its cells. The steps are lines of code, read from top to bottom. Excel is the cook, and it follows the recipe literally, without guessing what you meant.

That literal behaviour is both the strength and the danger. A formula recalculates when its inputs change, but it can only return a value into its own cell. A macro can do things a formula never can: create and name sheets, write hundreds of formulas, format whole blocks, open and save files, and talk to the user through message boxes. In exchange, a macro does exactly what it is told, so the most useful skill you will build in this course is reading a line of code and knowing what it will do before you run it.

Almost every line of VBA follows one of three simple shapes. The first is object, property, value: ws.Range("A1").Value = "Shop" says take the sheet held in ws, go to its cell A1, and set its value to the word Shop. The second is object, method: ws.Columns("A:D").AutoFit asks columns A to D to do something, here to resize themselves. The third is plain logic: a loop that repeats a block of lines, or an If that runs a block only when a condition is true. Once you can spot those three shapes, a macro that looked like a wall of text becomes a list of readable instructions.

When a macro beats doing it by hand, and when it does not

Writing a macro costs time up front, so it pays only when the task comes back. A useful rule of thumb is to compare the minutes you spend on the task by hand over a few months with the minutes needed to write, test and maintain the code. The chart below uses example numbers: a weekly report that takes 15 minutes by hand, and a macro that takes an hour to write and about half a minute to run.

Cumulative minutes: by hand vs with a macro (example)050100150200024681012WeeksBy hand 180Macro 66Break-even in week 5
Example numbers: 15 minutes by hand every week against a one-hour macro that then takes about 30 seconds per run. After 12 weeks the manual route has cost 180 minutes, the macro 66. With these assumptions the macro is ahead from the fifth week on.

Your own numbers will differ, and that is the point of drawing the chart: the macro wins when the task repeats often, when the data is large, or when consistency matters more than speed. It loses when the task is a one-off, when the steps change every time, or when a built-in feature already does the job. Before you write any code, ask whether a formula, a PivotTable, a table with structured references or Power Query would solve the problem. Those tools need no code, they are easier for colleagues to maintain, and they are often the better answer. VBA earns its place when you need actions rather than calculations.

Typical good and poor fits

  • Good fits for VBA: formatting a raw export the same way every week, splitting one list into a sheet per region, building a monthly report with fixed headers and colours, creating a dated copy of a file before changes, checking hundreds of rows for missing values and listing the problems.
  • Poor fits for VBA: a single calculation (use a formula), a summary by category (use a PivotTable), combining and cleaning files from a folder on a refresh schedule (Power Query is built for that), anything that must also work in Excel for the web, where VBA macros do not run.
  • Grey zone: tasks that change shape every time. If you cannot write the steps down as a fixed list, a macro will struggle too.

The worked example: one week, four shops, twenty rows

The macro in the lesson writes one fictional week of sales for four shops, Harbor, Market, Station and Uptown, Monday to Friday, into a brand-new sheet. Here are the first five data rows exactly as the macro leaves them. Column D is not a typed number: the macro writes a real Excel formula into every row, so if you change a sales figure afterwards, the difference updates by itself.

Rows 2 to 6 of the generated sheet (Harbor). The target is 1,000.
RowA: ShopB: DayC: SalesD: formula written by VBAD showsRow colour
2HarborMon820=C2-1000βˆ’180none
3HarborTue1,140=C3-1000140pale green
4HarborWed690=C4-1000βˆ’310none
5HarborThu1,310=C5-1000310pale green
6HarborFri905=C6-1000βˆ’95none

The other fifteen rows follow the same pattern for Market, Station and Uptown. Under the data, in rows 23 and 24, the macro adds a total and an average, again as formulas rather than typed results. You can check the macro's own count of green days with a third formula, which is a good habit whenever code produces numbers: let a second, independent method agree with it.

Summary formulas for the generated sheet. The first two are written by the macro, the others are checks you can type yourself.
CellWhat it showsFormulaResult
C23Total of all 20 days=SUM(C2:C21)19,895
C24Average per shop-day=AVERAGE(C2:C21)994.75
any free cellDays on or above target=COUNTIF(C2:C21,">=1000")9
any free cellHarbor week total=SUMIF(A2:A21,"Harbor",C2:C21)4,865
any free cellStation days on target=COUNTIFS(A2:A21,"Station",C2:C21,">=1000")3

The numbers tell a small story that is typical of real sales data. Nine of twenty days reached the target, yet the average of 994.75 sits just below it, because a few weak days such as Station on Wednesday (590) pull the mean down. Station has the best week with 5,220 and three days on target, Market the weakest with 4,780. The chart below shows the same twenty values, coloured the way the macro colours the rows.

Daily sales of the four shops vs the 1,000 targetOn or above target (9 days)Below target (11 days)04008001,2001,600MTWTFMTWTFMTWTFMTWTFHarborMarketStationUptownTarget1,000
The twenty values the macro writes, grouped by shop. Mint bars are the nine rows the macro colours pale green (sales of 1,000 or more), peach bars are below target. The dashed line is the target of 1,000.

What the key lines do

You do not need to understand every line on day one, but it helps to see how the recipe maps onto code. Here is the heart of the macro, the loop that writes the twenty rows and their formulas:

For i = 0 To 19 r = i + 2 ws.Cells(r, 1).Value = shops(i \ 5) ws.Cells(r, 2).Value = days(i Mod 5) ws.Cells(r, 3).Value = sales(i) ws.Cells(r, 4).Formula = "=C" & r & "-" & TARGET Next i

  • For i = 0 To 19 … Next i repeats the indented block twenty times, with i counting from 0 to 19. The arrays in the macro start at position 0, which is why the count does too.
  • r = i + 2 turns the counter into a sheet row: data starts in row 2 because row 1 holds the headers.
  • ws.Cells(r, 1) means row r, column 1 (column A) of the new sheet. Numbers for columns are what make loops easy.
  • i \ 5 is whole-number division: 0 to 4 give 0 (Harbor), 5 to 9 give 1 (Market), and so on. i Mod 5 is the remainder, 0 to 4, which picks Mon to Fri.
  • "=C" & r & "-" & TARGET glues text and numbers together with &. In row 2 it builds the text =C2-1000, and assigning that to .Formula turns it into a live formula.

The colouring step is a second loop with a decision inside it. It visits every data row, compares the sales value with the target, and only when the value is high enough does it colour the row and add one to a counter called hits. That counter is what the message box reports at the end.

For r = 2 To lastRow If ws.Cells(r, 3).Value >= TARGET Then ws.Range(ws.Cells(r, 1), ws.Cells(r, 4)).Interior.Color = RGB(220, 252, 231) hits = hits + 1 End If Next r

Step by step: run your first macro in Excel

If you have not run the macro from the lesson yet, follow these steps. They work in Excel for Microsoft 365, Excel 2021, 2019 and 2016 on Windows; the Mac menu names are given where they differ.

  1. Open a new, empty workbook. Starting with an empty file means nothing valuable can be overwritten while you learn.
  2. Optional but useful: show the Developer tab. On Windows choose File β†’ Options β†’ Customize Ribbon and tick Developer; on a Mac choose Excel β†’ Preferences β†’ Ribbon & Toolbar and tick Developer. The tab holds the Visual Basic, Macros and Record Macro buttons.
  3. Press Alt+F11 to open the Visual Basic Editor (on a Mac: Tools β†’ Macro β†’ Visual Basic Editor, or Developer β†’ Visual Basic).
  4. In the editor choose Insert β†’ Module. A blank code window called Module1 opens. Ordinary macros live in standard modules like this one.
  5. Copy the WeeklyReport macro from the lesson above and paste it into the module. Check that the lines are black and blue, not red: red means VBA could not read a line, often because of curly quotes.
  6. Click anywhere between Sub WeeklyReport() and End Sub and press F5, or click the green Run button. To step through it one line at a time instead, press F8 repeatedly and watch the yellow highlight move.
  7. Switch back to Excel with Alt+F11 again. A new sheet called Week plus the time is there, with the header, twenty rows, the green rows, the totals and a message box.
  8. Save the file with File β†’ Save As and choose Excel Macro-Enabled Workbook (*.xlsm). A normal .xlsx file cannot store code.
  9. Later, run the macro without opening the editor: press Alt+F8 (on a Mac: Tools β†’ Macro β†’ Macros), pick WeeklyReport and click Run.

Where a macro lives: from Excel to one line of codeExcelAlt+F11VBA projectone perworkbookModule1Insert β†’ModuleSubWeeklyReport… End SubStatementsrun top tobottomSaved as .xlsmthe code is keptSaved as .xlsxevery module is removedThe workbook file decides whether your code survives closing Excel.
The path from Excel to a running line of code. Each open workbook has its own VBA project, a project holds modules, and a module holds Sub procedures such as WeeklyReport.

Keep the Immediate window open while you learn: in the editor press Ctrl+G (on a Mac, View β†’ Immediate Window). Type ?ActiveSheet.Name and press Enter, and VBA answers with the name of the active sheet. It is the quickest way to test a single line without writing a whole macro.

Your own first change

The best way to understand the macro is to change it a little and run it again. Each run adds a fresh sheet, so you can compare the versions side by side. Try adding a third summary line that counts the green days with a worksheet formula, so the sheet itself confirms the number in the message box. Add these two lines just after the line that writes the average:

ws.Cells(lastRow + 4, 2).Value = "Days on target" ws.Cells(lastRow + 4, 3).Formula = "=COUNTIF(C2:C" & lastRow & ","">=" & TARGET & """)"

Inside a VBA string, two double quotes in a row stand for one literal quote character. That is why the formula text looks crowded: the code builds =COUNTIF(C2:C21,">=1000"), and cell C25 shows 9, matching the message box. If you then change the target constant to 1,200, the formula, the colours and the message all change together, because they all read the same constant.

Illustration for the VBA Basics course: an Excel workbook next to the Visual Basic Editor with a short macro
VBA Basics: from the Visual Basic Editor to a finished report, one line at a time.

Safety: macros, trust and the undo button

Because a macro can do anything you can do in Excel, it can also delete things. Three habits keep you safe. First, a macro clears Excel's undo history when it changes cells, so Ctrl+Z will not bring back what it overwrote. Test new code on a copy of the file or, as the lesson macro does, write only into a sheet the macro has just created. Second, only enable macros in files you trust. When you open an .xlsm file, Excel shows a yellow security bar and keeps the code switched off until you click Enable Content. Third, files downloaded from the internet or received as email attachments may carry a mark that makes current versions of Microsoft 365 block their macros entirely. If you trust such a file, the usual fix on Windows is to close it, right-click it in File Explorer, choose Properties and tick Unblock. Your organisation's IT settings may restrict this, and that is a good thing.

The macro settings themselves live under File β†’ Options β†’ Trust Center β†’ Trust Center Settings β†’ Macro Settings. Leave them on the default that disables macros with a notification. Enabling all macros for every file is never needed to follow this course.

Common mistakes and how to spot them

  • Saving as .xlsx. Excel warns that the VB project cannot be saved in a macro-free workbook; if you click Yes, the module is gone when you reopen the file. Spot it by the file icon and extension: code needs .xlsm (or .xlsb).
  • Pressing F5 with the cursor outside the macro. Instead of running, the editor opens the Macros dialog. Click inside the Sub first.
  • Curly quotes and odd characters after copying. A line that turns red as soon as you leave it contains something VBA cannot parse. Retype the quotes as straight ".
  • Running on the wrong sheet. Code that says ActiveSheet or uses a bare Range("A1") works on whatever sheet is active at that moment. The lesson macro avoids this by keeping the new sheet in a variable, ws, and writing ws. in front of every range.
  • Typing a value where a formula belongs. .Value = 820 - 1000 stores -180 as a fixed number, while .Formula = "=C2-1000" stores a formula that follows the data. Click the cell and look at the formula bar to see which one you have.
  • Forgetting Set for objects. ws = ThisWorkbook.Worksheets.Add stops with an error; sheets, ranges and workbooks are objects and need Set ws = ….

Quick reference: what the lesson uses

Keep this table nearby for the rest of the course. The left half lists the Excel and editor shortcuts, the right half the VBA building blocks and worksheet functions that appear in the weekly report.

Shortcuts, VBA keywords and worksheet functions used in this lesson
ItemTypeWhat it does
Alt+F11ShortcutSwitch between Excel and the Visual Basic Editor
Alt+F8ShortcutOpen the Macros dialog to run a macro from Excel
F5 / F8Shortcut (editor)Run the macro under the cursor / run it one line at a time
Ctrl+GShortcut (editor)Show the Immediate window for one-line tests
Ctrl+BreakShortcutInterrupt a running macro (on laptops often Ctrl+Fn+B or Esc)
Sub … End SubVBAThe container for one macro
Dim, Option ExplicitVBADeclare variables, and make declaration compulsory
Worksheets.AddVBAAdd a new sheet; keep it with Set ws = …
Cells(row, col), Range("A1:D1")VBAPoint at cells by numbers or by address
.Value, .Formula, .NumberFormatVBAWrite a value, write a formula, change how a number looks
For … Next, If … End IfVBARepeat a block, decide per row
MsgBoxVBAShow a message to the user
SUM, AVERAGEWorksheet functionTotal and mean of the sales column
COUNTIF, SUMIF, COUNTIFSWorksheet functionCheck the macro's results independently

Real-world uses of small macros like this one

The weekly report is deliberately simple, but the same pattern of new sheet, header, rows, formulas, formatting and message covers a surprising amount of everyday office work. A few concrete examples:

  • Monday export clean-up. A sales coordinator receives a CSV from the shop system every week. A macro deletes the empty columns, renames the headers, applies number formats, sorts by branch and adds totals, so the file is ready to share in seconds rather than a quarter of an hour.
  • Month-end checks in accounting. Before closing a month, a macro walks through the journal list, highlights rows with a missing cost centre or an amount of zero, and writes a short list of problems on a new sheet. The accountant still fixes them by hand, but nothing is overlooked.
  • One sheet per region. A regional manager needs the same list split into North, South, East and West. A macro adds one sheet per region and copies the matching rows, with the same header and layout on every tab.
  • Dated backups. A small macro saves a copy of the workbook with today's date in the file name before a big update, so there is always a way back, something Ctrl+Z cannot offer after code has run.
  • Consistent client reports. A consultant builds the same one-page summary for several clients. The macro guarantees identical fonts, colours and column widths, so reports look professional whoever produces them.

What you will build in the rest of this course

This first lesson is free. The remaining seven lessons are part of the full VBA Basics course, a one-time purchase of $9.90, and each one builds directly on the weekly report you just ran:

The Visual Basic Editor. A guided tour of the editor you used today: the Project Explorer, the code window, the Properties window and the Immediate window. You will learn where each kind of code belongs, why a macro sometimes appears under a sheet instead of a module, and how to test a single line before it goes into a macro.

Your First Macro. You write a macro from an empty module instead of pasting one, and you learn the object, property, value pattern that sits behind nearly every line of the weekly report. By the end you can read a line such as ws.Range("C2:D21").NumberFormat = "#,##0" aloud and know what it will change.

Sub, End Sub, and Procedure Names. Real projects use several small macros rather than one long one. This lesson covers naming rules, Public and Private procedures, and how one Sub calls another, so you can split a report into tidy steps that are easy to reuse.

Variables, Dim, and Option Explicit. Variables are the labelled boxes that hold the target, the counter and the sheet in today's macro. You will choose the right data type for numbers, text, dates and objects, and see how Option Explicit turns a silent typo into an error you can fix in seconds.

Talking to the User: MsgBox and InputBox. Make macros interactive: ask for a target before the report is built, offer Yes and No buttons before something is overwritten, and handle the case where the user clicks Cancel. Small touches that make a macro safe to hand to colleagues.

Comments and Readable Code. Code is read far more often than it is written. You will learn how to comment the why rather than the what, how to indent and name things so a macro explains itself, and how to leave a file that someone else, or you in six months, can still maintain.

Running Code and Fixing It When It Breaks. Every macro stops with an error sooner or later. This lesson teaches you to read the error message, step through code with F8, set breakpoints, watch variables change and fix the most common run-time errors without guessing.

Summary

VBA is the programming language inside desktop Excel. A macro is a recipe of steps that Excel follows literally: it can create sheets, write formulas, format cells and talk to the user, which formulas alone cannot do. It pays off for tasks that repeat, involve a lot of data or must look identical every time, and it is the wrong tool when a formula, a PivotTable or Power Query already does the job. Write macros into a standard module, save them in an .xlsm file, enable content only for files you trust, and remember that Ctrl+Z cannot undo what code has changed.

Now scroll back up to the lesson, paste the WeeklyReport macro into a module and press F5. Then change the target to 1,200, run it again and compare the two tabs. Five green rows instead of nine, a different message, and you will have edited your first program.

Frequently asked questions

What is VBA in Excel?

VBA (Visual Basic for Applications) is the programming language built into desktop Excel for Windows and Mac. You use it to write macros, short programs that repeat a series of steps such as adding sheets, writing formulas and formatting cells.

Is VBA hard to learn for a beginner?

The basics are approachable if you already use Excel, because most lines simply name a cell or sheet and set one of its properties. Starting with a small working macro and changing one thing at a time, as in this lesson, is the gentlest way in.

How do I open the VBA editor in Excel?

Press Alt+F11 on Windows. On a Mac use Tools, Macro, Visual Basic Editor, or the Visual Basic button on the Developer tab.

Why did my macro disappear after saving?

The workbook was most likely saved as .xlsx, which cannot store code. Save it as an Excel Macro-Enabled Workbook (.xlsm) instead.

Can I undo a macro with Ctrl+Z?

No. Running a macro that changes cells clears Excel's undo history, so test new code on a copy of the file or on a new sheet.

Does VBA work in Excel for the web or on mobile?

No. VBA macros run in desktop Excel for Windows and Mac. Excel for the web uses Office Scripts for automation instead.

Keep going: VBA Basics

This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time $9.90.

  1. The Visual Basic Editor
  2. Your First Macro
  3. Sub, End Sub, and Procedure Names
  4. Variables, Dim, and Option Explicit
  5. Talking to the User: MsgBox and InputBox
  6. Comments and Readable Code
  7. Running Code and Fixing It When It Breaks

Buy course β€” $9.90 See the full course

Knowledge check

A macro has just recoloured 500 rows of your real data in the wrong colour. You press Ctrl+Z. What happens?

Continues in this course
  • The Visual Basic Editor
  • Your First Macro
  • Sub, End Sub, and Procedure Names
  • Variables, Dim, and Option Explicit
  • Talking to the User: MsgBox and InputBox
  • Comments and Readable Code

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course β€” $9.90