Skip to content

Store values in variables, and shorten code with With

Write VBA9 minPremium

Builds on Read VBA as objects, properties and methods.

A pricing analyst in Lyon updates the price list every quarter. Her macro writes a heading with the quarter's name and formats the header row, and the quarter is different every time it runs.

How it works

A variable is a named place to keep a value while the macro runs. Declare it with Dim, a name and a type, then give it a value with an equals sign.

RowAB
1TypeHolds
2LongWhole numbers up to about 2.1 billion, such as a row number
3DoubleNumbers with decimals, such as a rate of 0.035
4StringText
5DateA date
6BooleanTrue or False
7RangeCells. Give it its cells with Set, as in Set prices = Range("C2:C40")

Integer is an older type that stops at 32,767, so use Long for rows: a sheet has 1,048,576 of them.

Put Option Explicit at the top of the module, and VBA won't run a macro that uses a name no Dim declares. A misspelled variable then stops the macro with "Variable not defined" before it does anything. In the editor on Windows, Tools > Options > Editor > Require Variable Declaration adds the line to every new module.

With names an object once for several lines. Between With and End With, a line that starts with a dot works on that object.

Example

VBA
Option Explicit
Sub NewPriceHeading()
Dim quarter As String
Dim header As Range
quarter = "Q3 2026"
Set header = Range("A1:E1")
Range("D1").Value = "Price " & quarter
With header
.Font.Bold = True
.Interior.Color = RGB(221, 235, 247)
.HorizontalAlignment = xlCenter
End With
End Sub
Writes a heading with the quarter in it, then formats the header row in one With block.

& joins text, so D1 reads Price Q3 2026. Next quarter, only the line that sets quarter changes.

Common mistakes

  • header = Range("A1:E1") without Set. A variable that holds cells needs Set, and without it VBA stops with "Object variable or With block variable not set".
  • Dim rate, amount As Double. Only amount is a Double; rate gets no type of its own. Give each variable its own As.
  • A misspelled name without Option Explicit. VBA makes a new, empty variable, and the macro runs with a 0 where your number should be.

In short

  • Dim name As Type declares a variable; use Long for whole numbers and rows, and Double for decimals.
  • Give a variable its cells with Set.
  • Option Explicit at the top of a module catches misspelled names, and With saves repeating an object.

Practice

Premium

4 exercises: 3 macros and 1 quiz question.

Practice is part of Premium

Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.