Monday, May 28, 2018

The scope of the Variables in VBA - Part 1

The scope of the variables means when we declare variable to hold some information in it, we need to provide those variables with some datatypes. DataTypes could be anything. Integer, long, string, variant etc...

Sometimes we required a single variable to use it in multiple procedures and even throughout the whole project of the workbook sometimes.


To understand the scope of the variables, we need to understand the basic structure of the VBA. Whatever the procedure you create it depends on your declaration, how you want to use those subprocedures and variables.

There are three layers of the project.

1. Procedure
2. Module
3. Project

the bottom layer is Procedure

Like whatever you will define will stay up to that procedure only.

E.g.

insert the module and type the following sub-procedure.

'/------------------------------------------

Private Sub Testing1()
'This is the Procedure.
       Dim A as long
       A = 1
       msgbox A
End Sub

'/------------------------------------------

Private Sub Testing2()
       msgbox A
End Sub


'/------------------------------------------

The output of Testing1 will be "1"
and The output of Testing2 will be "0" or blank

Because we have declared variable A in sub procedure. and that variable A has the scope of up to that Testing1 Procedure only.

So it's seems a private variable declaration.

you can notice... procedural declaration has effect until its own procedure only. that's the concept. we can do more and more.

But Scope is not only limited up to variables. It also applies to the declaration of procedure too. but we will look forward to it in next part.

thank you.

- Kamal Bharakhda

No comments:

Post a Comment

IsValidPasswordString Function

'Following function will verify if the password string contains following characters or not? Rem : List of Characters Group - ASCII Rem ...