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.
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.
| Row | A: Shop | B: Day | C: Sales | D: formula written by VBA | D shows | Row colour |
|---|---|---|---|---|---|---|
| 2 | Harbor | Mon | 820 | =C2-1000 | β180 | none |
| 3 | Harbor | Tue | 1,140 | =C3-1000 | 140 | pale green |
| 4 | Harbor | Wed | 690 | =C4-1000 | β310 | none |
| 5 | Harbor | Thu | 1,310 | =C5-1000 | 310 | pale green |
| 6 | Harbor | Fri | 905 | =C6-1000 | β95 | none |
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.
| Cell | What it shows | Formula | Result |
|---|---|---|---|
| C23 | Total of all 20 days | =SUM(C2:C21) | 19,895 |
| C24 | Average per shop-day | =AVERAGE(C2:C21) | 994.75 |
| any free cell | Days on or above target | =COUNTIF(C2:C21,">=1000") | 9 |
| any free cell | Harbor week total | =SUMIF(A2:A21,"Harbor",C2:C21) | 4,865 |
| any free cell | Station 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.
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 irepeats the indented block twenty times, withicounting from 0 to 19. The arrays in the macro start at position 0, which is why the count does too.r = i + 2turns the counter into a sheet row: data starts in row 2 because row 1 holds the headers.ws.Cells(r, 1)means rowr, column 1 (column A) of the new sheet. Numbers for columns are what make loops easy.i \ 5is whole-number division: 0 to 4 give 0 (Harbor), 5 to 9 give 1 (Market), and so on.i Mod 5is the remainder, 0 to 4, which picks Mon to Fri."=C" & r & "-" & TARGETglues text and numbers together with&. In row 2 it builds the text=C2-1000, and assigning that to.Formulaturns 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.
- Open a new, empty workbook. Starting with an empty file means nothing valuable can be overwritten while you learn.
- 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.
- Press
Alt+F11to open the Visual Basic Editor (on a Mac: Tools β Macro β Visual Basic Editor, or Developer β Visual Basic). - In the editor choose Insert β Module. A blank code window called
Module1opens. Ordinary macros live in standard modules like this one. - Copy the
WeeklyReportmacro 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. - Click anywhere between
Sub WeeklyReport()andEnd Suband pressF5, or click the green Run button. To step through it one line at a time instead, pressF8repeatedly and watch the yellow highlight move. - Switch back to Excel with
Alt+F11again. A new sheet called Week plus the time is there, with the header, twenty rows, the green rows, the totals and a message box. - Save the file with File β Save As and choose Excel Macro-Enabled Workbook (*.xlsm). A normal .xlsx file cannot store code.
- Later, run the macro without opening the editor: press
Alt+F8(on a Mac: Tools β Macro β Macros), pickWeeklyReportand click Run.
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.

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.
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
ActiveSheetor uses a bareRange("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 writingws.in front of every range. - Typing a value where a formula belongs.
.Value = 820 - 1000stores -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.Addstops with an error; sheets, ranges and workbooks are objects and needSet 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.
| Item | Type | What it does |
|---|---|---|
Alt+F11 | Shortcut | Switch between Excel and the Visual Basic Editor |
Alt+F8 | Shortcut | Open the Macros dialog to run a macro from Excel |
F5 / F8 | Shortcut (editor) | Run the macro under the cursor / run it one line at a time |
Ctrl+G | Shortcut (editor) | Show the Immediate window for one-line tests |
Ctrl+Break | Shortcut | Interrupt a running macro (on laptops often Ctrl+Fn+B or Esc) |
Sub β¦ End Sub | VBA | The container for one macro |
Dim, Option Explicit | VBA | Declare variables, and make declaration compulsory |
Worksheets.Add | VBA | Add a new sheet; keep it with Set ws = β¦ |
Cells(row, col), Range("A1:D1") | VBA | Point at cells by numbers or by address |
.Value, .Formula, .NumberFormat | VBA | Write a value, write a formula, change how a number looks |
For β¦ Next, If β¦ End If | VBA | Repeat a block, decide per row |
MsgBox | VBA | Show a message to the user |
SUM, AVERAGE | Worksheet function | Total and mean of the sales column |
COUNTIF, SUMIF, COUNTIFS | Worksheet function | Check 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+Zcannot 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.
- 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
- Running Code and Fixing It When It Breaks