Excel VBA cheat sheet

The syntax you need most · excelversity.com

Download PDF

Variables & types

Option ExplicitTop of every module: forces you to declare all variables
Dim n As LongWhole number (use Long, not Integer)
Dim total As DoubleNumber with decimals
Dim name As StringText
Dim ok As BooleanTrue or False
Dim d As DateDate and/or time
Dim v As VariantAny type, including arrays and error values
Dim ws As Worksheet: Set ws = ActiveSheetObject variables need Set
Const RATE As Double = 0.2A value that never changes

Ranges & cells

Range("A1").Value = 10Write a value to a cell
Cells(2, 3).ValueRow 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).RowLast filled row in column A
Range("A1").CurrentRegionThe block of data around A1
Range("A2:A9").ClearContentsDelete values, keep formatting
Range("A1").Value2 = Range("A1").Value2Turn a formula into its value

Workbooks & sheets

ThisWorkbookThe workbook that contains the code
ActiveWorkbook / ActiveSheetWhatever 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 = xlSheetHiddenHide a sheet (xlSheetVeryHidden: hide from the menu too)
Workbooks.Open "C:\Data\Sales.xlsx"Open a workbook
wb.SaveAs fileName, xlOpenXMLWorkbookSave as .xlsx (51); .xlsm is xlOpenXMLWorkbookMacroEnabled (52)
wb.Close SaveChanges:=FalseClose without saving

If / Select Case

If x > 0 Then MsgBox "Positive"One-line If
If x > 0 Then ... ElseIf x = 0 Then ... Else ... End IfBlock If with several branches
If a > 0 And b > 0 ThenBoth conditions must be true
If a > 0 Or b > 0 ThenAt least one condition is true
If Not IsEmpty(Range("A1")) ThenCell is not empty
Select Case scoreStart a multi-way choice on one value
Case 90 To 100A range of values
Case "A", "B"Several values
Case Is >= 50A comparison
Case ElseAnything not matched above

Loops

For i = 1 To 10 ... Next iCount from 1 to 10
For i = 10 To 1 Step -1Count backwards (use when deleting rows)
For Each c In Range("A1:A10") ... Next cEvery cell in a range
For Each ws In ThisWorkbook.WorksheetsEvery sheet in a workbook
Do While x < 100 ... LoopRepeat while a condition is true
Do Until IsEmpty(Cells(r, 1)) ... LoopRepeat until a condition becomes true
Exit For / Exit DoLeave the loop early
If i Mod 2 = 0 ThenEvery second item (remainder of division)

Strings

s = "Hello " & nameJoin 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 / TimeToday / 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 LongFixed 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").ValueRead a range into a 2-D array (1-based)
Range("E1").Resize(UBound(v), 3).Value = vWrite an array back in one step
Erase aClear an array

Subs & functions

Sub DoWork() ... End SubA macro you can run
Function Tax(amount As Double) As DoubleReturns a value; usable in cells as =Tax(A1)
Tax = amount * 0.2Set the return value by assigning to the name
Call DoWork / DoWorkRun 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 FunctionLeave early

Error handling

On Error GoTo FailJump to the label Fail: when an error occurs
Fail: MsgBox Err.DescriptionThe handler; Err.Number holds the code
Exit Sub (before Fail:)Stop normal runs from falling into the handler
On Error Resume NextIgnore errors on the next lines (keep it short)
On Error GoTo 0Switch normal error handling back on
If Err.Number <> 0 ThenCheck whether the last line failed
Resume NextIn 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 ThenAsk yes or no
vbOKCancel / vbExclamation / vbCriticalOther 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 xWrite to the Immediate window (Ctrl+G)

Speed & events

Application.ScreenUpdating = FalseNo redrawing while the macro runs
Application.Calculation = xlCalculationManualPause formulas (restore xlCalculationAutomatic)
Application.EnableEvents = FalseStop event macros firing (switch back on!)
Application.DisplayAlerts = FalseNo 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 SubReact only to changes in column B
DoEventsLet Excel repaint and respond during a long loop