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.
| Row | A | B |
|---|---|---|
| 1 | Type | Holds |
| 2 | Long | Whole numbers up to about 2.1 billion, such as a row number |
| 3 | Double | Numbers with decimals, such as a rate of 0.035 |
| 4 | String | Text |
| 5 | Date | A date |
| 6 | Boolean | True or False |
| 7 | Range | Cells. Give it its cells with Set, as in Set prices = |
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
Option ExplicitSub NewPriceHeading() Dim quarter As StringDim header As Rangequarter = "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 WithEnd Sub
& joins text, so D1 reads Price Q3 2026. Next quarter, only the line that sets quarter changes.
Common mistakes
header =withoutRange( "A1:E1") Set. A variable that holds cells needsSet, and without it VBA stops with "Object variable or With block variable not set".Dim rate,. Only amount is a Double; rate gets no type of its own. Give each variable its ownamount As Double 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 Typedeclares a variable; useLongfor whole numbers and rows, andDoublefor decimals.- Give a variable its cells with
Set. Option Explicitat the top of a module catches misspelled names, andWithsaves repeating an object.
Practice
Premium4 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.
Have one? Sign in