VBA for MS Access 2010 tutorial- declare and access variables
Declare and access variables
-Declaring a variable at Local LevelAt local level is declared in Sub-procedure between Sub and End Sub or Function and End Function. By declaring the variable at the local level, the variable scope is limited to only the sub-procedure. This means that the variable can’t be used or accessed outside the sub-procedure. The variable declaration prototype is:
Dim variable_name As DataType
Example: To declare a variable called x to store integer value, you can write as seen below:
Dim x As Integer 'Declare a variable called x to store an integer value
-Declaring a variable at Global LevelYou can declare a variable at the global level by declaring it in the Form module or the Standard modul.+Form module: In the Form module, you will declare a variable in the general section of the form. By declaring the variable in the Form module, the variable can be accessed from any code block of the form but can’t be accessed from other forms.
Example: Create a Form (Create-> Form Design) then click on View Code icon in the Ribbon menu.
To declare a variable called lstname to store string value in the Form module, you can write as seen below:
Dim lstname As String
+Standard module: To declare a variable in the Standard module, you
need to create a module by using the Visual Basic Editor:
In the Standard module, you need to declare the variable with public or private keyword instead of Dim keyword. By declaring with the public keyword the variable can be accessed through out your application. However, with private keyword the variable can be accessed only within its module. The variable declaration in the Standard module can be generally written as shown below:
Public Variable_Name As Datatype Private Variable_Name As Datatype Example: To declare a variable called PI to store a float value in the Standard module, you can write:
Public PI As Single