VBA Tutorial

Variables & Data Types

Dim, Long, String, and the importance of Option Explicit

Declaring Variables (Dim)

In VBA, you declare a variable using the Dim (Dimension) keyword.
vba
Dim name As String
Dim age As Integer
Wait! By default, VBA allows you to use variables without declaring them. This is dangerous! Always add Option Explicit to the very top of your module. It forces you to declare every variable, preventing typos from causing hidden bugs.

Common Data Types

TypeDescription
StringText data ("Hello")
IntegerWhole numbers up to 32,767
LongWhole numbers up to 2 billion (Use this for Row counts!)
DoubleLarge decimals and scientific numbers
BooleanTrue or False
DateDate and Time values
VariantA "catch-all" type that can hold anything (Slow and memory-heavy)

Constants (Const)

If a value never changes, declare it as a constant.
vba
Const PI As Double = 3.14159

The Long Rule

Wait! Professional VBA developers almost always use Long instead of Integer. Modern computers are optimized for 32-bit (Long) numbers, and an Integer is too small to hold the row count of a modern Excel sheet (over 1 million rows).

Summary

TermDescription
DimDeclaring a variable
AsDefining the data type
Option Exp.Force variable declaration (Safety first!)
LongThe standard type for whole numbers
VariantThe default type if you don't specify one
Best ForEfficient memory usage and bug prevention
Logic"Strong typing for business data"
SafetyPrevents "undeclared variable" typos
ModernEven in old VBA, type safety is critical
StandardUse Long for all counters and row indices
IdentityVariables in VBA are cleared when the macro finishes