Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

VBA Code Basics Cheat Sheet: Key Syntax Explained

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

A VBA cheat sheet is a compact reference for the handful of syntax rules that cover most Excel macro work: how to declare variables, write If and loop blocks, refer to cells and ranges, call subroutines and functions, handle errors, and read or write files. You do not need to learn the whole language to be productive — a page of correct syntax gets you through the majority of everyday automation. To follow along, open Excel, press Alt+F11 to launch the Visual Basic Editor, and use Insert > Module to get a blank code window where you can paste and run the examples below. Menu labels can differ slightly between Excel versions, in the Mac version, and in non-English regional builds, so look for the equivalent item if a name does not match exactly, and note that Excel for the web has no VBA editor at all — you need the desktop app.

What You'll Need

  • Microsoft Excel for Windows or Mac, installed as a desktop application (not the browser version).
  • A workbook you can experiment in — ideally a copy, because macros cannot be undone with Ctrl+Z once they have written to cells.
  • Macro security set so macros are not blocked: on Windows, File > Options > Trust Center > Trust Center Settings > Macro Settings, then choose the setting that enables macros with notification so you get a prompt. On a Mac, Excel > Preferences > Security.
  • A basic comfort with spreadsheet concepts (cells, ranges, worksheets) — no prior programming required.

Step-by-Step

  1. Open the editor and add a module. In Excel press Alt+F11 (on a Mac, Option+F11 or the Developer tab). In the editor choose Insert > Module. Everything you write in a standard module can be run from the Macros dialog (Developer > Macros, or Alt+F8). If the Developer tab is hidden, enable it in File > Options > Customize Ribbon and tick Developer.
  2. Write the smallest possible macro. Every procedure starts with Sub and the name, and ends with End Sub. For example: Sub Hello() then MsgBox "Hello" then End Sub. Indentation is cosmetic but makes nested blocks readable; the editor will not complain about it. Run it with F5 while the cursor is inside the procedure.
  3. Declare your variables at the top. The pattern is Dim, a name, As, a type: Dim i As Long, Dim total As Double, Dim label As String, Dim found As Boolean, Dim ws As Worksheet, Dim r As Range. Add Option Explicit as the very first line of the module so any misspelled variable name raises an error instead of silently becoming a new empty variable — this one line prevents a large share of beginner bugs.
  4. Refer to sheets and cells precisely. Use Worksheets("Sheet1").Range("A1").Value rather than relying on whichever sheet happens to be active. Better still, assign the sheet once: Dim ws As Worksheet then Set ws = ThisWorkbook.Worksheets("Data"). Note the Set keyword — object variables need it, plain numbers and text do not. Always name the workbook (ThisWorkbook or Workbooks("Book1.xlsx")) so the macro does not act on the wrong file.
  5. Learn the six blocks that do most of the work. Condition: If x > 10 Then … ElseIf x = 10 Then … Else … End If, or the one-line form If x > 10 Then y = 1. Select-case: Select Case x with Case 1, Case 2 To 5, Case Else, then End Select. Counting loop: For i = 1 To 10 … Next i, optionally Step -1 to count down. Collection loop: For Each r In ws.Range("A1:A10") … Next r. Condition loop: Do While x < 5 … Loop, and its sibling Do Until. Inside a For loop, Exit For jumps out early.
  6. Use With to avoid repeating a long reference. Write With ws.Range("B2"), then inside it .Value = 5, .Font.Bold = True, .Interior.Color = vbYellow, and close with End With. Each leading dot refers to the object after With. This is the single biggest readability improvement in day-to-day VBA.
  7. Split logic into Sub and Function. A Sub does something and returns nothing; a Function returns one value. A function looks like Function Tax(amount As Double) As Double … Tax = amount * 0.2 … End Function, where assigning to the function's own name sets the return value. Pass parameters ByVal (a copy) unless you deliberately want the caller's variable modified, in which case use ByRef.
  8. Add error handling. At the top of the procedure write On Error GoTo Failed, then before End Sub write Exit Sub, a label Failed:, and a line such as MsgBox "Error " & Err.Number & ": " & Err.Description. This stops a failed file open or a type mismatch from dumping the user into the debugger with a cryptic highlight. Use On Error Resume Next only around a single line you genuinely expect to fail, and turn it off again immediately with On Error GoTo 0.
  9. Speed up loops that touch many cells. Reading and writing one cell at a time across thousands of rows is slow. Build results in a variant array with Dim arr As Variant and arr = ws.Range("A1:A10000").Value, work through the array in memory, write it back in one statement, and wrap the block with Application.ScreenUpdating = False and = True, plus Application.Calculation = xlCalculationManual and xlCalculationAutomatic. Always restore these in the error handler too, or the user is left with a workbook that never updates.
  10. Save in a macro-enabled format and sign the project. A workbook containing macros must be saved as .xlsm; .xlsx silently discards the code. File > Save As, choose Excel Macro-Enabled Workbook. To stop the security warning on your own files, add the folder to trusted locations, or sign the project: in the editor choose Tools > Digital Signature. Never enable macros in a file from an untrusted source — VBA can delete files and change system settings.

Common Mistakes

Forgetting Set when assigning an object is the classic error, producing "Object variable or With block variable not set". Omitting Option Explicit hides typos: cel.Value silently creates a new empty variable and the loop appears to do nothing. Relying on ActiveSheet breaks the moment the user clicks another tab mid-run. Reusing a variable name that clashes with a built-in term causes odd behaviour. And editing a loop counter inside its own For loop produces results that are hard to predict — use a separate variable instead.

Tips

Press F8 to step through a procedure one line at a time, and hover over a variable to see its current value; the Immediate window (Ctrl+G) accepts ? myVariable to print values as you debug. Use Debug.Print to log intermediate results without message boxes. Keep each procedure short and give it a descriptive name such as FormatQuarterlyReport. Comment with a single apostrophe, and write comments that explain why, not what. Back up your .xlsm files before editing code — there is no undo in the editor either.

Troubleshooting

If nothing happens when you run a macro, check that the cursor is inside the right procedure, the Developer tab is visible, and macro security is not blocking the workbook. If you get a compile error the editor will usually highlight the offending line after you click OK — read the first error rather than the last. A "Subscript out of range" almost always means a sheet or workbook name is wrong or the file is not open. "Type mismatch" means you are assigning text to a numeric variable, often because a cell holds a number stored as text. If the macro runs but seems to ignore your changes, a stuck ScreenUpdating = False or manual calculation setting may be persisting — set both back explicitly. For workbook corruption after a failed run, close without saving and use the previous copy.

Frequently Asked Questions

Do I need the Developer tab to write VBA?

No. Alt+F11 opens the Visual Basic Editor regardless. The Developer tab just gives you convenient buttons for macros and the editor.

Can I undo a macro?

No. VBA changes are not placed on the undo stack. Work on a copy of the workbook, or have the macro save a backup first.

Why does my .xlsx file lose the code?

Standard workbooks cannot store macros. Save as .xlsm and the code persists; your old .xlsx remains unchanged.

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

No. Editing and running VBA requires the desktop Excel application on Windows or Mac.

What is the difference between a Sub and a Function?

A Sub performs actions and returns nothing; a Function returns a single value and can be called from a cell formula or from other code.

Is On Error Resume Next safe?

Only in a narrow scope. It hides every error on the lines that follow, so use it around a specific expected failure and reset with On Error GoTo 0 straight after.