×

Scope in Visual Basics

Definition of Scope

The scope of any programming language implies the area of code where the variables will be identified, accessed, and used. Every variable has a scope associated with it. The scope of a variable is defined at the time the variable is declared.

The available scope for a variable can be the either of the three scopes i.e., procedure, module, and public:

 Procedure Level - Procedure is also known as a local variable. They are only declared within the specific procedure or function.

 Module Level - A module-level variable is accessible to only the module it is declared in.

 Global Level – Global is also known as public variable. A public module-level variable is accessible to all modules present in the worksheet.

Procedure Level

A local variable or procedure level variable is recognized only within the specific procedure or function in which it is declared and is not accessible outside the subroutine. Hence, Local variables can only be used in the procedure in which they are declared. When the procedure or function ends, the variable is removed automatically, and the memory is discharged. The advantage of using local variables is that we can use the same name in different subroutines without any discord.

Declaration Statement

Dim

Scope

Only available in the sub in which it is declared.

Lifetime

It is destroyed at End Sub of the Sub in which it was declared, or end statement.

Types

A local variable is declared either with a Dim or Static statement. One can use the Dim, Static, or Private statement within a specific subroutine or function.

  1. Dim

To explicitly declare local variables in VBA, Dim statement is being used. In Dim statement, the variable only persists in existence as long as the procedure in which it is declared is running. Usually, when the procedure is finished, the values of the local variables declared in the procedure are not preserved, and the memory allocated to those variables is released. The next time when the same procedure is executed, all its local variables are reinitialized.

The most common way to declare a local variable is to use the Dim statement between the Sub and End Sub statements.

In the following macros, the variable ‘LVar’ is declared in each of the modules. Wherein each variable ‘LVar’ is independent of the other, i.e., the variable is only accessible within its specific subprocedure.

Program 1

 Sub DimLocalVariableExample1()
       Dim LVar As Integer
       ' Local variable, with Dim Scope.
       LVar = 10
       MsgBox "The value of LVar is " & LVar
    End Sub 

Output

Scope in Visual Basics

Program 2

 Sub DimLocalVariableExample2 ()
       Dim LVar As String
       ' Local variable, with Dim Scope.
       LVar = "Hello VBA"
       MsgBox "The value of Variable is " & LVar
    End Sub 

Output

Scope in Visual Basics 1


2. Static

A local variable declared with the Static statement remains in existence the whole time the VBA is underuse. The static variable is reset when any of the following cases happen:

  • The macro generates an untapped run-time error.
  • Visual Basic is halted.
  • You quit Microsoft Excel.
  • You can change or edit the VBA module.

Program

Sub StaticLocalScope()
       Static Factorial
       Factorial = 1
       ' Static Local variable that will hold its value even after the module has finished its executing.
       num = Application.InputBox ( prompt:="Enter a number: ", Type:=1)
       For i = 1 To num
       Factorial = Factorial * i
       Next
        MsgBox "The factorial of " & num & " is " & Factorial
    End Sub 

Output

Scope in Visual Basics 2
Scope in Visual Basics 3

Module scope

A “module-level” variable that is accessible amongst all the procedures available in a module sheet. A module-level variable is visible or available to all the procedures in that module, but it is not visible to procedures present in another module. It remains in existence the entire time VBA is running until the module in which it is declared is edited or modified. 

Declaration Statement

Private or Dim


Lifetime

Destroyed either when the workbook is closed or a “stop” is hit in the VBE, or a new sub is added to the module or End statement.

Scope

Only available in the module in which it is declared.

Types

Module-level variables can be declared either with a Dim or Private statement above the first procedure definition at the top of the module. They cannot be declared within the procedure. 

In Module level variable Dim statement, this is equivalent to a Private statement. Hence, there is no difference between Dim and Private. But, generally, Private statement is used for Module, as Dim is particularly used for local variables only. This makes the scope of a variable clearer.

Program 1

Sub ModuleScopeExample1()
 'Declaring the variable in another procedure
 Dim Var1 As Double
 'Declaring the variable in another procedure
 Private Var2 As Double
 End Sub
 Sub ModuleScopeExample2()
    'Calling the Var1 and Var2 in another procedure
     Var1 = 100
     Var2 = 200
     'The output will be null as private scope
     MsgBox "The value of Var1 is " & Var1
     MsgBox "The value of Var2 is " & Var2
 End Sub

Output

Scope in Visual Basics 4
Scope in Visual Basics 5

Global Scope

A “Global level” variables are also known as public variable, project level or global variables. These variables are visible or accessible to all modules present in the project and have the broadest scope of all variables.

Project level variables are declared in the “General Declarations Area” i.e., at the top of the module, above the first procedure definition. It cannot be declared within a procedure. A public variable is always declared with a "Public" statement.

Declaration statement

Public

Scope

Available to all subs in the project.

Lifetime

Destroyed at End Sub procedure in which the variable was declared.

Program

 ‘Declaring the public variable in sub procedure
 Sub GlobalScopeExample1()
     Public var As Double
 End Sub
 ‘Calling the above variable in another sub procedure
 Sub GlobalScopeExample2()
     var = 110
     MsgBox "The value for the variable is " & var
 End Sub 

Output

Scope in Visual Basics 6

Related Topics

Excel VBA IsMissing Function

VBA IsMissing Function: The IsMissing function in VBA checks if any parameter to a procedure is missing or not. It returns a Boolean value True if the specified parameter has not been...

1 minute read.

Excel VBA Left Function

VBA Left Function: The Left function in VBA returns a substring from the start of the specified string. Syntax Left (Str, Length) Parameter Str (required) – This parameter represents the string that you want to extract...

1 minute read.

Excel VBA DateValue Function

The DateValue function in VBA returns a VBA Date from the given String representation of a date wherein the time information is ignored. It is unable to interpret dates that include the...

1 minute read.

Excel VBA Error Function

VBA Error Function: The Error function in VBA returns the error message corresponding to a supplied error code. Syntax Error ([ErrorNumber]) Parameter ErrorNumber (optional) – This parameter represents the required error number. By default, the...

1 minute read.

VBA Creating, Displaying, Uploading UserForms

UserForm is a customized interface and acts as a VBA container and can add various controls as per the required functionality, each of which has certain usage and related properties. You can...

4 minutes read.

VBA ActiveCell Property

What is the ActiveCell Property? The active cell signifies the active selected cell in the current worksheet. The Active property acts as a reference point and is used to move the cell cursor...

5 minutes read.

Excel VBA : With End-with Constructs

With End-with Constructs The With-End With construct enables the user to perform multiple operations on a single object. If you are going to perform several different actions on the same object and typing the same...

4 minutes read.

VBA Pivot Table

What is a Pivot Table? One of the most powerful features of Excel VBA is the Pivot Table. A pivot table is a VBA tool that is used to create summary...

3 minutes read.

Excel VBA ABS Function

VBA ABS Function: The ABS function in VBA returns the absolute value of the specified number. Syntax Abs (Number) Parameter Number (required) – This parameter represents the number that you want the absolute value of. Return This...

1 minute read.

Excel VBA Day Function

The function Day in VBA returns the day number (from 1 to 31) for the given date value. Syntax Day (Date) Parameter Date (required) – This parameter represents the date. Return This function returns the day...

1 minute read.

Excel VBA Sin Function

VBA Sin Function: The Sin function in VBA returns the sine value for a supplied angle. Syntax Sin (Number) Parameter Number (required) –This parameter represents the angle (in radians) to calculate the sine value. Return This function...

1 minute read.

VBA Type Mismatch Error

What is a Type Mismatch Error? VBA Type Mismatch Error is a run time error in excel, which often occurs when the data types contained in a VBA code are not matched...

3 minutes read.

Looping in VBA

Looping in VBA There are many situations where a programmer needs to execute a block of the repetitive code number of times. Writing the same statement will make the program tedious and monotonous....

3 minutes read.

Excel VBA For Each Loop

A For Each loop executes a statement or a group of statements for each element in an array or collection. It repeats the statement/condition/code for each element in a collection. For Each Loops loop through every...

4 minutes read.

VBA Option Explicit

VBA Option Explicit The Option Explicit in VBA is used to declare the variables at the top of your macro code. It is the most secure and easy option to maintain your variables....

5 minutes read.

Excel VBA: Do Until….Loop

DO UNTIL….Loop The “Do Until” Loop is same unlike DO WHILE statement just that it will keep on looping till the condition is not met. This loop is used to repeat a set...

4 minutes read.

Excel VBA IsError Function

VBA IsError Function: The IsError function in VBA returns a Boolean value showing whether the specified Expression represents an error or not. Syntax IsError (Expression) Parameter Expression (required)- This parameter represents the variant that you...

1 minute read.

Excel VBA Exp Function

VBA Exp Function: The Exp function in VBA returns the value of the exponential function ex (mathematical constant ‘e’ raised to specified power) for the given value of x. Syntax Exp (Number) Parameter Number (required) –This parameter represents...

1 minute read.

Excel VBA Timer Function

Excel VBA Timer Function: The Timer function in VBA returns a Single data type, evaluating the number of seconds that have elapsed since midnight of the current day. Syntax Timer () Parameter NA Return This...

1 minute read.

Steps to Create a Chart in VBA

Steps to Create a Chart Charts are created either by directly working with the chart variable object that defines the chart data or by ChartObject method. In order to get to...

3 minutes read.