Variables - Declaration and Assignment
Part:
1
2
This chapter describes:
- Variable Declaration
- Assigning Values to Variables
- Variable Default Values
Variable Declaration
Like many other programming languages, Visual Basic (VB) uses variables to reserve memory
to store data and to name that memory location.
A variable must be declared with a name and a specific data type. Here are the rules on variable declaration:
1. Explicit Declaration - A variable is declared with the "Dim" statement in the following syntax:
Dim variable_name As data_type
where "variable_name" is a text label to identify this variable; and "data_type" is one of the data type key words:
"Byte", "Integer", "Long", "Single", "Double", "Currency", "String", "Boolean", "Date", and "Variant".
If a variable is declared without "As" and the data type key word, it will be assumed with the "Variant" data type.
2. Implicit Declaration - A variable name is used on the left side of an assignment statement without
being declared previously. The data type of an implicitly declared variable is "Variant".
Visual Basic Scripts Restriction: Visual Basic scripts used in IE or IIS only supports "Variant" type
of variables. So you:
- Can use implicit variable declaration.
- Can use explicit variable declaration without "As" and data type keywords.
- Can NOT use explicit variable declaration with "As" and data type keywords.
Just in case you want to know, "Dim" stands for "Dimension".
Assigning Values to Variables
Variables can be assigned with new values with the assignment statement in the following syntax:
variable_name = data_value
where "data_value" a data literal or an expression. We will look at expressions in details in other parts
of this book.
When assigning a new value to a variable, the data type of the new value must match the data type of the variable.
Since we can not declare specific variable types in VB scripts, I wrote the following VB code module
in Microsoft Access:
Sub Main()
' VariableType.bas
' Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
Dim c As Byte
Dim i As Integer
Dim l As Long
Dim f As Single
Dim d As Double
Dim y As Currency
Dim s As String
Dim b As Boolean
Dim t As Date
Dim v As Variant
(Continued on next part...)
Part:
1
2
|