Thursday, November 24, 2022

VBA Statement - Dim

Dim statement is to declares variables and allocates storage space. For example Dim StrVar as String, Dim Int As integer and etc which is assigning any variables to data type or object.

Syntax : Dim Variable Name As Data Type

Actually the syntax consist many optional parts but required only 2 which is Dim and Variable name, to explain in detail refer below:

  1. Dim VarName
    This to declare VarName as default which is Variant.
  2. Dim VarName as String
    This to declare VarName as String.
  3. Dim VarName1 as string, VarName2 as string
    This to declare both VarName1 and 2 as String.
  4. Dim VarName1,VarName2 As Integer,VarName3 as Integer
    This to declare VarName1 default (Variant),VarName2 as integer and VarName3 as integer.

 Basically these 4 methods we can use to declare Variables.

VBA Vode:

Option Explicit
Sub Examples_DimDeclares()
    
    Dim myVar
    Dim MyVar1, MyVar2
    Dim MyVar3 As String, myVar4 As Integer
    Dim MyVar5, MyVar6 As Integer, MyVar7 As String

End Sub

Note:

  1. Don't use same Variable name with number because more likely become array. The above example just for reference.
  2. If we declare Variables with same name then Compile error: Duplicate declaration in current scope.
Read more about Dim statement, macro enabled excel, excel macro,
vba coding, vba code at below links.

Microsoft Reference-Dim-statement
Other Reference-Dim-statement

Leave your comments if you have any request.
Practice makes perfect.
Thank You.

No comments:

Post a Comment