Lifetime and Scope

The difference between lifetime and scope is quite simple.
Lifetime - Refers to how long or when the variable is valid (i.e. how long will it retain its value for).
Scope - Refers to where the variable can be accessed.
The Lifetime is how long the variable retains its value for.
The scope refers to where the variable can be used.


Variable Lifetime

The lifetime of the local variable "imylocal" extends from the moment ProcedureOne is entered to the moment ProcedureOne has finished.
However the local variable "imylocal" still exists when ProcedureTwo is called, it is just out of scope.

Public Sub ProcedureOne() 
Dim imylocal As Integer
   imylocal = 5
   Call ProcedureTwo()
   imylocal = 10
End Sub

Public Sub ProcedureTwo()
'do something
End Sub

Variable Scope

Every variable has a scope associated with it.
This scope refers to the area of code where the variables will be recognised.
Variables (and constants) have a defined scope within the program.
The scope for a variable can either be:
Procedure Level - Also known as a local variable.
Module Level - A private module level variable is visible to only the module it is declared in.
Global Level - A public module level variable is visible to all modules in the project.

Global var1 As String 
Public var2 As String
Private var3 As String
Dim var4 As String

Global Const var5 As String
Public Const var6 As String
Private Const var7 As String
Const var8 As String

Public Sub VariableScope()
   Dim var9 As String
   Const var10 As String
   Static var11 As String

Option Private Module

When used in host applications that allow references across multiple projects, Option Private Module prevents a module's contents from being referenced outside its project.

Option Private Module 

If used, the Option Private statement must appear at module level, before any procedures.
When a module contains Option Private Module, the public parts, for example, variables, objects, and user defined types declared at module level, are still available within the project containing the module, but they are not available to other applications or projects.
Option Private is only useful for host applications that support simultaneous loading of multiple projects and permit references between the loaded projects.


Remember

Local variables (in different subroutines and functions) can use the same name without any conflict.
Module level public variables (or global) should be prefixed with a "g".
Module level private variables should be prefixed with a "m".


© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext