Excel VBA lets you replace work you do by hand with code that does it in one click. This tutorial takes you from opening the editor for the first time to writing automation that pulls from databases, drives Outlook and builds its own user interface.
Every topic below links to a full lesson with working code you can copy, and most come with a downloadable example file. The path is ordered — if you are new, start at Stage 1 and work down. If you already write macros, use the jump links above.
Updated for 2026
Every example on this page has been tested on Excel 365, Excel 2024 and Excel 2021, on both 32-bit and 64-bit Office. Code uses Option Explicit and declared variables throughout, and avoids .Select and .Activate.
Is VBA still worth learning in 2026?
A fair question, and most tutorial sites dodge it. Here is the honest answer.
VBA is no longer the only way to automate Excel. Three alternatives now exist, and each is better than VBA at something.
| Tool | Best at | Weakness |
|---|---|---|
| VBA | Desktop Excel, full Office control, UserForms, legacy files, working offline | Windows and Mac desktop only, no cloud, ageing language |
| Office Scripts | Excel on the web, sharing with Power Automate, modern syntax | No Outlook or Word control, needs a Microsoft 365 business plan |
| Python in Excel | Statistics, machine learning, charting large data | Runs in the cloud, cannot automate the Excel interface |
| Copilot | Explaining and drafting code, one-off analysis | Non-deterministic, needs review, cannot be scheduled |
When VBA is still the right answer
- The file lives on a desktop, not in SharePoint or OneDrive.
- You need to drive Outlook, Word, PowerPoint or Access from Excel.
- You need a UserForm — a real dialog with buttons and inputs.
- You are maintaining an existing macro-enabled workbook. There are tens of millions of them.
- Your organisation blocks Office Scripts or the Python runtime, which many do.
When to reach for something else
Colleagues open it in a browser, so VBA will never run. Use Office Scripts.
Use Power Query. It is refreshable, auditable and needs no code.
Use Python in Excel. VBA has no equivalent of pandas or scikit-learn.
Let Copilot draft it and move on. Do not build a macro you will run once.
VBA is not growing. It is also not going anywhere: it ships in every desktop copy of Office and Microsoft has committed to supporting it. Learning it is still one of the highest-return skills in an office job, because it is the only one of the four that works everywhere without asking IT for anything.
A note on AI-written VBA
Copilot and ChatGPT write VBA that usually runs, but they lean on patterns from old forum posts — .Select, undeclared variables, no error handling. Working through this tutorial will let you spot and fix that, which matters more now than it did five years ago.
Before you start: three things to set up
-
Turn on the Developer tab
File → Options → Customize Ribbon, then tick Developer in the right-hand column. You can skip this and press Alt + F11 to open the editor directly, but the Developer tab is where the Macro Recorder and the form controls live. -
Save as .xlsm, not .xlsx
An.xlsxfile silently discards all VBA code when you save it. Use Excel Macro-Enabled Workbook (*.xlsm). This is the most common way beginners lose an afternoon’s work. -
Understand macro blocking
Since 2022, Excel blocks macros by default in any file that came from the internet or from email. This catches almost everyone at least once — see the box below.
Why your downloaded macro file will not run
If a file came from the internet or an email attachment, Excel shows a red banner reading “Microsoft has blocked macros from running because the source of this file is untrusted” and the Enable Content button does not appear. This is not a bug and you cannot fix it from inside Excel.
Close the file, right-click it in File Explorer, choose Properties, tick Unblock at the bottom of the General tab, then reopen it.
For files you write yourself, the better fix is a Trusted Location: File → Options → Trust Center → Trust Center Settings → Trusted Locations → Add new location. Files saved there run without prompting. Full detail: Macro Security and Password Protection.
Your first macro
Press Alt + F11, then Insert → Module, and paste this in.
Option Explicit
Sub HelloWorld()
MsgBox "Hello World!", vbInformation, "My First Macro"
End Sub
Click anywhere inside the code and press F5. A message box appears.
Two things in there are deliberate and worth carrying into every macro you write. Option Explicit at the top of the module forces you to declare every variable — without it, a typo like totl instead of total creates a silent new empty variable and your code returns the wrong number with no error at all. The vbInformation and title arguments are optional, but MsgBox accepts them, and knowing what a procedure will accept is most of what learning VBA consists of.
Turn on Option Explicit permanently
Tools → Options → Editor tab → tick Require Variable Declaration. Every new module you create from then on gets the line automatically. It costs nothing and prevents an entire category of bug.
Full lesson: writing your first VBA macro
VBA tutorial: the learning path
Four stages. Each row links to a full lesson with examples and, in most cases, a downloadable file.
- 1. Foundations
- 2. The language
- 3. Excel objects
- 4. Advanced
Stage 1 — Foundations
Get the editor open, record something, run it, and understand what you are looking at.
| Topic | What you will learn |
|---|---|
| Introduction to VBA | What VBA is, what it can and cannot automate, and where it fits alongside Excel’s other tools. |
| Getting started with macros | The vocabulary — macro, module, procedure, project — in one short read. |
| The VBA environment (VBE) | Project Explorer, Properties window, code pane and the Immediate window, and what each is for. |
| Recording a macro | Record a real task, then read the code it generated. The fastest way to learn Excel’s object model. |
| Writing your first macro | Write, save and run a macro from scratch. |
| Executing a macro | Run from the Macro dialog, a keyboard shortcut, a worksheet button, or automatically on open. |
| Debugging VBA code | Breakpoints, F8 step-through, the Watch window and the Immediate window — the four tools that turn guessing into diagnosis. |
| Commenting and editing code | Comment blocks in and out while testing, and write code your future self can still read. |
| Macro security | Trusted Locations, digital signatures, and why downloaded files refuse to run. |
| 15 macros for absolute beginners | Fifteen short, complete macros covering cells, ranges, formatting and sheets. Downloadable file included. |
Stage 2 — The language
Variables, logic and loops. This is the stage where you stop recording and start writing.
| Topic | What you will learn |
|---|---|
| VBA data types | Long vs Integer, String, Double, Date, Variant, Boolean, and which to reach for when. |
| Scope of variables | Procedure-level, module-level, Public, Private and Static, and why scope causes so many mystery bugs. |
| VBA statements | If…Then…Else, Select Case, For…Next, For Each, Do While and With. |
| VBA functions | Built-in functions for text, numbers and dates, plus writing your own. |
| Input boxes and message boxes | InputBox and MsgBox, including reading which button the user pressed. |
| Passing arguments | ByRef vs ByVal, optional arguments, and writing procedures you can reuse. |
| Arrays | Fixed and dynamic arrays, ReDim Preserve, Split, Join, and loading a whole range into memory. |
| Collections | Grouping objects, and looping a collection with For Each. |
| Objects, properties and methods | The mental model that makes the rest of VBA click. Read this one twice. |
Stage 3 — Working with Excel
Applying the language to the objects you actually care about.
| Topic | What you will learn |
|---|---|
| 100+ most useful VBA codes | The reference page. Over a hundred ready-to-run macros grouped by task. |
| Tables (ListObjects) | Create, sort, filter and clear filters on Excel Tables. |
| Charts in VBA — 33 examples | Create charts and set types, titles, axes, colours and data sources in code. |
| Pivot tables in VBA | Build, refresh and reconfigure PivotTables programmatically. |
| Files and folders | Loop through a folder, open every workbook in it, and read and write text files. |
| Hyperlinks | Add, follow, loop through and remove hyperlinks. |
| Filtering data | AutoFilter and Advanced Filter in code. |
| MsgBox reference | Every button constant, icon and return value. |
| ListBox controls | Populate, clear and read multi-select list boxes. |
Stage 4 — Advanced
Interfaces, events, other applications and databases.
| Topic | What you will learn |
|---|---|
| UserForms and controls | Build a real dialog — text boxes, combo boxes, buttons — and wire it to your data. |
| Events | Workbook_Open, Worksheet_Change, SelectionChange and the rest, including the EnableEvents trap that causes infinite loops. |
| Advanced VBA programming | Class modules, custom objects, and structuring code that has outgrown a single module. |
| ADO and SQL: connecting to a database | Connect to SQL Server or Access, run SELECT, INSERT and UPDATE, and drop a recordset straight into a sheet. |
| Interacting with other applications | Drive Outlook, Word, PowerPoint and the browser from Excel. |
| VBA security | Protecting your project, signing your code, and what password protection actually does. |
Ten patterns you will use constantly
If you learn nothing else on this page, learn these. Every one is production-ready — declared variables, no .Select, and safe to drop into real work.
1. Find the last used row
Dim lastRow As Long lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Always anchor to a specific worksheet variable. Cells(Rows.Count, 1) with no sheet reference breaks the moment a different sheet is active.
Full lesson: finding the last used row with data
2. Loop a range without selecting anything
Dim cell As Range
For Each cell In ws.Range("A2:A" & lastRow)
If cell.Value = "" Then cell.Value = "N/A"
Next cell
3. Loop every worksheet
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Range("A1").Value = ws.Name
Next ws
ThisWorkbook vs ActiveWorkbook
ThisWorkbook is the workbook containing the code. ActiveWorkbook is whichever one happens to be in front when the macro runs. Confusing the two is why a macro works on your machine and damages someone else’s file.
4. Read a range into an array — the big speed win
Dim data As Variant
data = ws.Range("A1:D10000").Value ' one read instead of 40,000
Touching the worksheet is slow; touching memory is not. On large ranges this is routinely 50 to 100 times faster than looping cell by cell.
5. Speed up any long-running macro
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
' ... your code ...
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Always restore these, including when the code errors. Pattern 10 shows how.
6. Copy without the clipboard
' Copy everything, including formats
wsSource.Range("A1:D100").Copy Destination:=wsTarget.Range("A1")
' Values only, and much faster
wsTarget.Range("A1:D100").Value = wsSource.Range("A1:D100").Value
7. Delete rows safely by looping backwards
Dim i As Long
For i = lastRow To 2 Step -1
If ws.Cells(i, 1).Value = "DELETE" Then ws.Rows(i).Delete
Next i
A forward loop skips a row after every deletion, because everything below shifts up while the counter moves down.
8. Check whether a sheet exists
Function SheetExists(sheetName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Worksheets(sheetName)
On Error GoTo 0
SheetExists = Not ws Is Nothing
End Function
9. Fast lookups with a Dictionary
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict("APPLE") = 1.5
If dict.Exists("APPLE") Then MsgBox dict("APPLE")
Late binding with CreateObject avoids a broken reference on machines without the Microsoft Scripting Runtime library. A Dictionary lookup is near-instant; a nested loop over 10,000 rows is not.
10. Error handling that always cleans up
Sub ProcessData()
On Error GoTo CleanFail
Application.ScreenUpdating = False
' ... your code ...
CleanExit:
Application.ScreenUpdating = True
Exit Sub
CleanFail:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation
Resume CleanExit
End Sub
Why this one matters more than it looks
Without it, a crash halfway through leaves ScreenUpdating switched off and Excel apparently frozen. Users will not report “your macro errored” — they will report that your macro broke their computer.
A note on 64-bit Office
Most new installations are 64-bit. Ordinary VBA is unaffected, but Windows API declarations must be updated or the project will not compile.
' Old — 32-bit only, fails to compile on 64-bit Office
Declare Function GetTickCount Lib "kernel32" () As Long
' Correct for both
#If VBA7 Then
Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long
#Else
Declare Function GetTickCount Lib "kernel32" () As Long
#End If
If you inherit a workbook that fails on a modern PC with “The code in this project must be updated for use on 64-bit systems”, this is almost always the reason.
Where to go next
Reference documentation for the Application, Workbook, Worksheet and Range objects, organised by method and property. Use it when you know what you want and need the exact syntax.
Complete working applications with full source code: a data entry UserForm, a calculator, a table of contents creator, and more.
If you are learning VBA for a job, work through these after Stage 2. Every answer is worked rather than memorised.
A gentler parallel track, if this page moves faster than you would like.
Frequently asked questions
How long does it take to learn VBA?
Recording and editing a simple macro takes an afternoon. Writing useful automation unaided, with loops and conditions, takes 20 to 30 hours of practice — roughly a month at an hour a day. Advanced work with UserForms, events and databases takes several months. Automating one real task from your own job beats any amount of tutorial reading.
Do I need programming experience to learn VBA?
No. VBA is a common first language precisely because you can see the result on the sheet immediately. Prior experience helps with Stage 2 concepts like scope and passing arguments, but Stage 1 assumes nothing at all.
Is VBA free?
Yes. It ships inside every desktop installation of Excel on Windows and Mac. There is nothing to buy and nothing to install.
Why does my macro disappear when I reopen the file?
The file was saved as .xlsx, which cannot store code. Save it as .xlsm — Excel Macro-Enabled Workbook.
Why is my downloaded macro file blocked?
Excel blocks macros in files that came from the internet or from email. Close the file, right-click it in File Explorer, choose Properties, tick Unblock at the bottom of the General tab, then reopen it.
Does VBA work in Excel for Mac?
Yes, with limits. UserForms, ActiveX controls and Windows API calls behave differently or not at all, and file paths use different separators. Core automation — ranges, sheets, loops, formatting — works on both.
Does VBA work in Excel on the web?
No. Excel for the web cannot run VBA at all. If your workbook has to be automated in a browser, use Office Scripts instead.
Should I learn VBA or Python?
They solve different problems. VBA automates the Excel application — sheets, ranges, buttons, Outlook. Python analyses data. If the goal is “make this report build itself every Monday”, that is VBA. If it is “find the pattern in this dataset”, that is Python.
Can AI write VBA for me?
It can draft it, and the draft usually runs. It also reproduces old habits — .Select, undeclared variables, no error handling — because it learned from a decade of forum posts. You still have to read the code you ship, which is what this tutorial is for.
What is the difference between a macro and VBA?
A macro is a stored set of instructions. VBA is the language those instructions are written in. Every macro is VBA code, but not all VBA code is a macro — functions and event handlers are not.
Related Excel VBA guides
- 100+ most useful Excel VBA codes — the full macro library.
- VBA Code Explorer — browse by object, method and property.
- Excel chart VBA examples — 33 worked chart macros.
- 15 macros for absolute beginners — with a downloadable file.
- 100+ VBA interview questions — with worked answers.
- Advanced VBA programming — class modules, events and structure.
What changed in this update
Added a section on macro blocking, the most common reason macros will not run in 2026. Added an honest comparison of VBA against Office Scripts, Python in Excel and Copilot. Added ten production-ready code patterns using Option Explicit and declared variables throughout. Added 64-bit PtrSafe guidance. Restructured the learning path into four ordered stages, filled in the missing description for Debugging VBA code, corrected the Commenting and editing code entry that previously repeated the debugging text, and fixed the Interacting with other applications link that pointed at an old permalink.
Thanks to Quentin, who asked in the comments for more up-to-date information. This update is that.



I Need Complete Macro Coding Tutorial Form Beginner Level To Advanced, Please Help Me Out.
Thank You.
10-but I would like more up-to date information
How can I place an xy scatterplot chart inside a form and dynamically update?
Thanks in advance.
Hi, We can not place Chart objects in the UserForms.
Alternatively, you can build the chart in the worksheet and save it as image and load into the UserForms using Picture control.
Thanks!
Excellent Tutorial! Thanks for all your work.
These step by step VBA tutorial is very Clear and straight to the point.