×

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 AutoFilter

One of the reasons for Excel VBA’s popularity is its capability to filter and analyze data from huge database with the help of a method known as AutoFilter. This method permits a...

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 CBool Function

VBA CBool Function: The CBool function in VBA calculates an expression and returns the result as a Boolean data type. Syntax CBool (Expression) Parameter Expression (required) – This parameter represents the expression that that you want...

1 minute read.

Excel VBA INT Function

VBA INT Function: The INT function in VBA rounds the given supplied number down and returns an integer value. The positive numbers are rounded to zero, and the negative numbers are rounded away from zero. Syntax Int...

1 minute read.

VBA ListBox

What is a ListBox? ListBox refers to a permanently displayed control (usually box-shaped) which contains a list of objects (or attribute, or elements) from which the user can select single or multiple attributes....

8 minutes read.

Excel VBA Split Function

Excel VBA Split Function: The Split function in VBA is used to split a string into several substrings and return a one-dimensional array of substrings. Syntax Split (Expression, [Delimiter], [Limit], [Compare]) Parameter Expression (required) – This parameter...

2 minutes read.

Excel VBA: IF THEN Statement

VBA Excel: IF THEN StatementThis conditional statement enables you to check one condition and on the basis of that then run one or multiple statements if the condition holds. If...

1 minute read.

ActiveX Controls

ActiveX Controls are one of the most used Excel Controls to automate applications with Excel VBA. It has the same controls, unlike Form Controls (Command Button, combo box, checkbox, etc.), but it...

3 minutes read.

Four VBA Clear methods

Four VBA Clear methods In Microsoft Excel, many times, a situation arises where the user wants to clear the data or any specific range of data. What if the user automates this task with...

6 minutes read.

Excel VBA String Function

The String function in VBA creates a String, consisting of several repeated characters. Syntax String (Number, Character) Parameter Number (required) – This parameter represents the number of characters in the returned String. Character (required) – This parameter...

1 minute read.

Excel VBA- Pivot Table Fields

VBA- Pivot Table Fields: The Pivot Fields collection contains all the fields from the data source, including any calculated fields. The main aspect of adding a field is its Position...

4 minutes read.

For Next loop in VBA

For Next Loop The ”For Next” loop is used for a fixed number of times. It works by implementing the loop for the specified number of times. In this, the user specifies how...

3 minutes read.

Excel VBA: IF…..THEN …ELSE Statement

VBA : IF…..THEN …ELSE Statement: This function enables you to check one condition and, based on that, then run one of the two statement blocks present. If the ‘IF’ condition...

2 minutes read.

Excel VBA Atn Function

VBA Atn Function: The Atn function in VBA returns the arctangent between quadrant -?/2 and +?/2 for the specified number, in radians. Syntax Atn (Number) Parameter Number (required) – This parameter represents the number that...

1 minute read.

Excel VBA User-Defined Functions

User-Defined Functions One of the advantages of VBA is that you can create your own functions using macros. These functions can be called and used as other functions in excel and use them. You can...

3 minutes read.

Excel VBA Format Function

VBA Format Function The format function in VBA applies a specified format to an expression and returns the result as a string. Syntax Format (Expression, [Format], [FirstDayOfWeek] , [FirstWeekOfYear] ) Parameter Expression (required)- This parameter represents the expression that you want to format. Format...

3 minutes read.

VBA Dim

What is Dim? DIM or Dimension or Declare in Memory is a keyword that is used in VBA to declare a variable with the different data types (Integer, String, variable, Boolean, Double, etc.)...

7 minutes read.

VBA Charts

What is a Chart? A chart is used to visually show numbers or data in a spreadsheet (or spread over multiple spreadsheets) so that the end-user can look at the chart...

3 minutes read.

CodeIgniter File Uploading Class

The Codeigniter provides a file Uploading library class which is used to upload any file such as images, pdf, mp3, etc. to the codeigniter’s application. It also allows to set various preferences such...

5 minutes read.

Excel VBA Sgn Function

VBA Sgn Function: The Sgn function in VBA returns an integer (+1, 0, or -1), stating the arithmetic sign for the specified number. Syntax Sgn (Number) Parameter Number (required) –This parameter represents the number that...

1 minute read.