The Dim Statement | VBA Declaration Statements

Declaring Variables - the Dim statement’s syntax. Square brackets, [ ], indicate optional items while vertical bars, |, indicate mutually exclusive items.
Declaring Variables - the Dim statement’s syntax. Square brackets, [ ], indicate optional items while vertical bars, |, indicate mutually exclusive items.
The Dim statement declares VBA variables and objects. It is ubiquitous in most VBA programs, so it is worthwhile exploring it in-depth as you'll do here.

In this article:

2 minutes read

Introducing the Dim Statement

The Dim statement declares variables and objects. The header image above shows its syntax. Moreover, based on its location in code, it can confer different levels of scope on variables and objects.

The image below shows the different scope levels in VBA. Also, we’ve delved into scope levels in a separate article, make sure to check it out if you need a refresher.

VBA Program Identifiers – Scope Levels [from the narrowest (block level) to broadest (application level)]
VBA Program Identifier Scope Levels – from the narrowest (block-level) to broadest (application level)

The Dim statement may be placed in blocks or procedures, or it can sit atop modules (outside all procedures). In each case, it confers block, procedure, module, or project level scope on a variable or object, respectively.

Salient Points for Usage

A few additional things to note about the Dim statement:

  • A module-level variable’s scope (which is private by default) is editable. But you can’t alter a block-level or procedure-level variable’s scope. In fact, the Private and Public keywords are legal only at the module-level.
  • You can only use one among the Dim, Private, and Public keywords in a declaration. Also, the Dim and Private keywords have the same effect at the module-level. However, using Private instead of Dim improves code readability.
  • A single Dim statement can declare several variables. To do this, insert a comma after each variable’s name (or data type, if specified). In this use-case, a Private or Public keyword applies to all the variables in the statement. Moreover, if a variable’s data type is set, then that of all other variable’s in the statement must also be set.
  • If you omit a variable’s data type, the compiler assigns the variant data type to it.
  • Replacing the Dim keyword with the Static keyword extends the lifetime of a procedure-level variable.

Sample Code (Examples)

The sample code below shows the Dim statement in use. It also illustrates the salient points discussed above.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Keep Learning

Related Articles

Keep Learning

Related Articles