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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Option Explicit 'declare variables accessible only to procedures in the current module Dim str_NamesFirst As String Private lng_NumberPhone As Long ' clearly, using PRIVATE is more readable than using DIM for this purpose 'declare variables accessible to procedures in/out-side the current module Public str_NamesLast As String Sub Dim_Statement_Procedure_Level_Examples() 'declare a procedure-level variable with data type Dim int_Age As Integer Dim sng_PlotDataXY(0 To 9, 0 To 1) As Single 'array of 10 x 2 size Dim obj_PlotCanvas As New Chart 'new Chart object 'without specifying a data type, the compiler assigns the variant type Dim var_Age 'declare multiple procedure-level variables in one Dim statement Dim int_CountFruits As Integer, byt_MonthDay As Byte, var_CountAnimals 'extend a procedure-level variable's lifetime beyond the current procedure Static str_NamesFull As String End Sub |