Excel VBA cheat sheet
The syntax you need most · excelversity.com
Variables & types
Option Explicit | Top of every module: forces you to declare all variables |
Dim n As Long | Whole number (use Long, not Integer) |
Dim total As Double | Number with decimals |
Dim name As String | Text |
Dim ok As Boolean | True or False |
Dim d As Date | Date and/or time |
Dim v As Variant | Any type, including arrays and error values |
Dim ws As Worksheet: Set ws = ActiveSheet | Object variables need Set |
Const RATE As Double = 0.2 | A value that never changes |
Ranges & cells
Range("A1").Value = 10 | Write a value to a cell |
Cells(2, 3).Value | Row 2, column 3 (C2) |
Range("A1:C10") | A block of cells |
Range("B2").Formula = "=SUM(A1:A9)" | Write a formula |
Range("A1").Offset(1, 2) | One row down, two columns right |
Range("A1").Resize(5, 3) | Grow to 5 rows by 3 columns |
Cells(Rows.Count, "A").End(xlUp).Row | Last filled row in column A |
Range("A1").CurrentRegion | The block of data around A1 |
Range("A2:A9").ClearContents | Delete values, keep formatting |
Range("A1").Value2 = Range("A1").Value2 | Turn a formula into its value |
Workbooks & sheets
ThisWorkbook | The workbook that contains the code |
ActiveWorkbook / ActiveSheet | Whatever is on screen right now |
Worksheets("Data") | A sheet by name |
Worksheets.Add After:=Sheets(Sheets.Count) | Add a sheet at the end |
ws.Name = "Report" | Rename a sheet |
ws.Visible = xlSheetHidden | Hide a sheet (xlSheetVeryHidden: hide from the menu too) |
Workbooks.Open "C:\Data\Sales.xlsx" | Open a workbook |
wb.SaveAs fileName, xlOpenXMLWorkbook | Save as .xlsx (51); .xlsm is xlOpenXMLWorkbookMacroEnabled (52) |
wb.Close SaveChanges:=False | Close without saving |
If / Select Case
If x > 0 Then MsgBox "Positive" | One-line If |
If x > 0 Then ... ElseIf x = 0 Then ... Else ... End If | Block If with several branches |
If a > 0 And b > 0 Then | Both conditions must be true |
If a > 0 Or b > 0 Then | At least one condition is true |
If Not IsEmpty(Range("A1")) Then | Cell is not empty |
Select Case score | Start a multi-way choice on one value |
Case 90 To 100 | A range of values |
Case "A", "B" | Several values |
Case Is >= 50 | A comparison |
Case Else | Anything not matched above |
Loops
For i = 1 To 10 ... Next i | Count from 1 to 10 |
For i = 10 To 1 Step -1 | Count backwards (use when deleting rows) |
For Each c In Range("A1:A10") ... Next c | Every cell in a range |
For Each ws In ThisWorkbook.Worksheets | Every sheet in a workbook |
Do While x < 100 ... Loop | Repeat while a condition is true |
Do Until IsEmpty(Cells(r, 1)) ... Loop | Repeat until a condition becomes true |
Exit For / Exit Do | Leave the loop early |
If i Mod 2 = 0 Then | Every second item (remainder of division) |
Strings
s = "Hello " & name | Join text with & |
Len(s) | Number of characters |
Left(s, 3) / Right(s, 3) / Mid(s, 2, 4) | Parts of a text |
InStr(1, s, "x", vbTextCompare) | Position of x (0 if not found), ignoring case |
Replace(s, "old", "new") | Replace every occurrence |
Trim(s) / UCase(s) / LCase(s) | Remove outer spaces / capitals / lower case |
Split("a,b,c", ",") | Text to array: a, b, c |
Join(arr, ", ") | Array to text |
s Like "INV-*" | Pattern match: * any text, ? one character, # one digit |
Format(1234.5, "#,##0.00") | Number as formatted text: 1,234.50 |
Dates
Date / Now / Time | Today / now / current time |
DateSerial(2026, 3, 15) | Build a date from year, month, day |
Year(d) / Month(d) / Day(d) | Parts of a date |
Weekday(d, vbMonday) | Day of week, Monday = 1 |
DateAdd("m", 1, d) | One month later ("d" days, "yyyy" years) |
DateDiff("d", d1, d2) | Days between two dates |
Format(d, "yyyy-mm-dd") | Date as text; nn = minutes, mm = months |
DateSerial(Year(d), Month(d) + 1, 0) | Last day of the month |
IsDate("2026-03-15") | Can this text be read as a date? |
Arrays
Dim a(1 To 5) As Long | Fixed array of 5 numbers |
Dim a() As String: ReDim a(1 To n) | Size an array at run time |
ReDim Preserve a(1 To n + 1) | Grow it and keep the contents (last dimension only) |
arr = Array("a", "b", "c") | Quick Variant array (starts at 0) |
LBound(a) / UBound(a) | First and last index |
v = Range("A1:C100").Value | Read a range into a 2-D array (1-based) |
Range("E1").Resize(UBound(v), 3).Value = v | Write an array back in one step |
Erase a | Clear an array |
Subs & functions
Sub DoWork() ... End Sub | A macro you can run |
Function Tax(amount As Double) As Double | Returns a value; usable in cells as =Tax(A1) |
Tax = amount * 0.2 | Set the return value by assigning to the name |
Call DoWork / DoWork | Run another procedure |
Sub Report(ByVal n As Long) | ByVal: the procedure gets a copy |
Sub Fill(ByRef total As Double) | ByRef (default): changes reach the caller |
Optional ByVal label As String = "x" | Argument with a default value |
Private Sub Helper() | Visible only inside this module |
Exit Sub / Exit Function | Leave early |
Error handling
On Error GoTo Fail | Jump to the label Fail: when an error occurs |
Fail: MsgBox Err.Description | The handler; Err.Number holds the code |
Exit Sub (before Fail:) | Stop normal runs from falling into the handler |
On Error Resume Next | Ignore errors on the next lines (keep it short) |
On Error GoTo 0 | Switch normal error handling back on |
If Err.Number <> 0 Then | Check whether the last line failed |
Resume Next | In a handler: continue after the failing line |
Err.Raise vbObjectError + 1, , "Bad input" | Raise your own error |
MsgBox & InputBox
MsgBox "Done" | Simple message |
MsgBox "Saved", vbInformation, "Title" | Message with icon and title |
If MsgBox("Delete?", vbYesNo) = vbYes Then | Ask yes or no |
vbOKCancel / vbExclamation / vbCritical | Other buttons and icons, combine with + |
s = InputBox("Name?") | Ask for text (Cancel returns "") |
v = Application.InputBox("Qty?", Type:=1) | Ask for a number; Cancel returns False |
Set r = Application.InputBox("Pick", Type:=8) | Let the user select a range |
Debug.Print x | Write to the Immediate window (Ctrl+G) |
Speed & events
Application.ScreenUpdating = False | No redrawing while the macro runs |
Application.Calculation = xlCalculationManual | Pause formulas (restore xlCalculationAutomatic) |
Application.EnableEvents = False | Stop event macros firing (switch back on!) |
Application.DisplayAlerts = False | No confirmation dialogs |
Application.StatusBar = "Working..." | Message in the status bar (False to reset) |
Private Sub Worksheet_Change(ByVal Target As Range) | Sheet module: runs when cells are edited |
Private Sub Workbook_Open() | ThisWorkbook module: runs when the file opens |
If Intersect(Target, Range("B:B")) Is Nothing Then Exit Sub | React only to changes in column B |
DoEvents | Let Excel repaint and respond during a long loop |