Variable scope and lifetime

The variable, after declaration, has its own lifespan and it lasts until the subroutine in which it was created is completed. Sometimes we want her to keep its value even after leaving the subroutine. Also, the variable is visible only within the module in which the it is located. Is there a need for it to be seen outside the module? How to define the range and extend the life span of variables will be found in the text that follows.

If we want the variable to retain its value after the completion of the routine in which it is located, it is necessary, when we declare it, to use the Static command instead of Dim. These two commands have the same syntax. Let’s see how this works on one simple example:

Sub VLC()

Static a As Integer
MsgBox a
a = 10

End Sub

When you first run this subroutine, it will display a value of 0 within the dialog window. This happens because it gets a value after the dialog window is initially displayed. If you run it again the value 10 will be displayed, and this happens because, after leaving the subroutine, variable has retained its value

When we declare a variable it can be invoked exclusively from the module in which it is located. We can especially emphasize this if we use Private instead of Dim. If we want it to be visible outside of the module we should declare it with Public command. Variables can also be declared outside the subroutines, in which case they can apply for multiple subprograms. Let’s show this in the example:

Public a As Integer
Private b As Integer

Sub VQ()

Dim c As Integer
a = 2
b = 10
c = a + b
MsgBox (c)

End Sub

Private/Public commands could be also used when you declare a subroutine or a function. By entering it in front of Sub/Function command you will set its visibility through the application.