Variable
In Visual Basic, as in any other programming language, variables store values during a program’s execution. A variable is a named storage location that can contain a value, which can contain a value, which can be modified during the program execution or if the value of a specified memory location changes at run time then it is defined to be a variable. The name with which we assign or manipulate the memory location at runtime is called a variable name. each variable has a Name (which uniquely identifies it), value and type. For example, the variable Name can have the value “Ram”, and the variable Age can have the value 24. here name and age are variable name an “ram” and 24 are their values, and string and integer are types of variables name and age respectively.
Declaring variables
In most programming languages, variable must be declared. In other words, compiler must be told in advance, about the variable to be used. If the compiler knows the variables and their types, it can produce optimized code. When the compiler is informed that the variable age will hold a number, then it will set required bytes in memory to make ready to use it.
Note: the complier is a translator that translates the programming code into the
Machine’s understandable form in order to make it ready to execution
|
A variable name:
- Must begin with a letter
- Can’t contain an embedded period or embedded type declaration character
- Must not exceed 225 characters.
- Must be unique within the same scope.
Explicit declaration
To declare variables and to allocate storage space the dim statement is used as in the following:
Dim meters as Integer
Dim greetings as String
The first variable, meters will store as integer value such as 10 or 388, and the second variable, greetings, will store a text such as “Happy Birthday”. When the compiler finds as Dim statement, it creatures place holder by reserving some space in memory and assigning a name to it. Each time this name is used its subsequent statement, Visual Basic uses this area in memory to read or set it value. For instance, when the following statement is used.
Meters = 143
Visual Basic places the value 143 in the place holder reserved for the variable meters. When the program asks for the value of this variable, Visual Basic get it from the same area of memory.
Types of Variables
The type of a variable determines how to allocate storage space in the computer’s memory to their values. All variables have that determines what kind of data they can store.
Visual Basic recognizes the following types of variables:
- Numeric
- String
- Variant
- Date
- Object
The numeric Data Types
Visual Basic supplies several numeric data types- integer, long (long Integer) single (single –precision floating point), double (double-precision floating point), and currency. Using a numeric data type generally uses less storage space than a variant. If it is known that a variable. Will store whole numbers (such as 12,388,60 etc) rather than numbers with a fractional amount (such as 3.57, 0.7876, etc) then it is better to declare it as an integer or long type variable. Operations are faster with integers, and these types consume less memory than other data types.
Different type of variables can be declared in a single Dim statement. For example, the following declaration statements.
Dim var1as single
Dim var2 as Double
Dim var3 as Currency
Can be minimized as in the following
Dim var1 as single, var2 as double, var3 as currency.
Different types of numbers are represented internally in different formats. All numeric values are truncated to a certain extent. The result of the operation 1/3 is 0.333333… (an infinite number of digits 3). It will fill the total capacity of RM with the digit3, and the result will still be truncated. Here’s simple but illuminating example.
Dim a as single, b as double
Single and Double are two basic data types for storing floating point number (numbers that have a fractional part), and the double type can represent these numbers more accurately than the single type. The following statements.
A=1/3
Debug. print a
Will produce the result in the immediate window.
0.3333333
And if the following statements are executed subsequently:
A= a*100000
The output will be
33333.34
The above result is not accurate, as it is not rounded properly. If this result is divided by 10000, its result will be 0.3333334, which is different from the initial result (0.33333333). This is an import at point in numeric calculations, and it is called error propagation. In long sequences of numeric calculations, errors propagate. If the above same operation is performed with the variable b, which is declared as double as in the following:
B=1/3
Debut. Print b
The result will be
0.333333333333333333
33333.33333333333
Which is more accurate.
The choice of data types of variable can make a difference in the result of the calculations. The proper variable types are determined by the nature of the values they present. The choice of data types is frequently a trade off between precision and speed of execution (less precise data type are manipulated faster). The following table shows rage and storage space allocated for each type of numeric variable.
Data type | Storage
size |
Range |
Integer | -32,768 to 32,767 | |
Long (long integer) | -2,147,483,648 to 2,147,483,647 | |
Single (single – precision floating
– point ) |
-3402823E38 to -1401298E-45 for
negative values; 1,4019298R-45 |
|
Double (double – precision floating
– point) |
-1.7976931348623E308 to –
4.940656445841247E for negative |
|
Currency (scaled integer) | -922,337,203,685,477.5808 to 922 |
The byte data type
The byte type holds basically an integer in the range 0 to 225 and they are declared with the following statement.
Dim varname as Byte
As the name implies bytes allocated in the memory for byte data type is one. Byte variables are frequently used to access files, image and second files, and so on. All operators that works on integers work with the byte data type except unary minus. Since byte is an unsigned type with the range 0-255, it cannot represent a negative number.
String variables
The string data type stores only text, and string variable are declared with the following statements;
Dim varname as string
By default, a string variable is variable length string: the string grows or shrinks as new data is assigned to it. String variables can also be declared with fixed length as in below:
Syntax
Dim string * size
For example, to declare a string that is always 50 characters long, the following statement is used.
Dim Emp Name As string *50
If a string of fewer than 50 characters is assigned, the Emp Name is padded with enough trailing spaces to total 50 characters. If a string that is to long for the fixed-length string is assigned, Visual Basic simply truncates the characters.
If a string variable’s size will change drastically during the course of an application, it is better to declare it as fixed-length to prevent Visual Basic form having to resize it constantly, which slows down the execution speed.
The Boolean Data Type
The Boolean data type stores true/false values. Although a single bit would be adequate, for efficiency reasons Visual Basic allocates two bytes t this data type. Boolean variables are declared as
Dim Running as Boolean
These variables are combined with the logical operators AND, OR and Not. The Not operator toggle the value of a Boolean variable. The following statement.
Running = true then
Running = false
Else
Running = true
End if
The Data Variable
Data and time values are stored internally as in a special way. A variable declared as
Data:
Dim expiration as date
Can store both date and time values. The following are all valid assignments.
Expiration = “01/01/2003”
Expiration = “01/23/2003”
Expiration = “13:03:05: AM”
EXPIRATION = “02/23/2003 13:03:05:AM”
Two date variables can be subtracted to know the difference as in the following:
Dim Date 1 as date, Date2 as date;
Dim days as integer;
Date1-“01/02/2003”
Date2 = “01/08/2003”
Days = Date2-Date1
In the above example the integer variable days will hold he value 6 which is the difference between the dates date1 and date2 . The value are stored in the date variables in mm/dd/yyyy (mm-month, dd-day, year-year) format
Integer values can be added to a date variable to add days. For example, if date holds the date “01/01/2003” the following line
Debut. print date 1+10
Will print the value “01/11/2003”
Note: to add an hour to a date variable, add 1/24 of a day; to addaminute add 1(24*60) of a day |
Object variables
Object variables are stored as 32-bit (4byte) addresses that refer to object within an application or within some application. A variable declared as object is one that can subsequently be assigned (using the set statement) to refer to any actual object recognized by the application.
For example, it has been assumed that a form in a Visual Basic application has two command buttons namely command 1 and command 2. and two object variables are declared as follows:
Dim a as command button, b as command button;
Each of these two object variables can be set to one of the two command button with the following statements:
Set a= command1
Set b= command2
From now on the command buttons properties can be manipulated through the variables a and b. to change the caption property of the first command button, the following statement is used:
a.Caption = “Click me”
To turn on the bold attribute of the second command button (so that is caption appears in bold), the following statement is used;
b.font Bold = true
This section just briefed about object variables. Objects and object variables are explained in detail in chapter “Object Programming in Visual Basic
The variant variable
A variant variable is capable of storing all system-defined types of data. Variant variables are declared without specifying a type as follows:
Dim var
Or for cleaner code it cab be declared as Dim var as variant. Variant variable an be used in both numeric and string calculations. There is no need to perform any type of conversions. Visual Basic automatically performs any necessary conversion. For
Example
Dim some value ‘variant by default.
E value =”17” ‘some value contains “17”
Some value = some value-15 ‘some value now contains the
“numeric value2.
Some value = “U” & Some value ‘some value now contains “U2” (a
tow character string)
Constants
some variable don’t change value during the execution of a program. These are constants that appears many times in the program code. Math calculations, the value of pi (3.14159) may appear many times in the program code.
These values are best represented by constants. Instead of typing the value 3.14159 over and over again, a constant will be defined with a constant name say pi, and it can be used in the program code as follows;
Area = pi* radius ^2
Creating Your Own Constants
The syntax for declaring a constant is:
[public| private] Const constantname [As type] = expression
The argument constant name is a valid symbolic name (the rules are the same as those for creating variable names), and expression is composed of numeric or string constants and operators; however, you can’t use function call in expression.
A const statement can represent a mathematical or date/time quantity:
Const con Pi = .141592265358979
Public Const con max plants as Integer =9
Const con release date =#1/1/95#
The const statement can also be used to define string constants:
Public const con version “07.10A”
Const con code name = “Enigma’
You can place more than one constant declaration of a single line if you separate them with commas:
Public const con Pi = 3.14, con Max Planets =9,_
Con Worldpop =3E+09
The expression on the right side of the equal sign (=) is often a number or literal sting, but it can also be an expression that results in a number or string (although that expression can’t contain calls to functions). You can even define constants in terms of previously defined constants:
Const con Pi2 = con pi*2
Once you define constants, you can place them in your code to make it more
Readable. For example:
Static SolarSystme 91 to con Max planets)
If num people >con World Pop then Exit sub
Operators
Operators can be classified into three main categories
- Arithmetic Operators
- Relational or Comparison Operators
- Logical Operators
The table lists the operators available in vbscript and most of them are self explanatory.
Arithmetic | Comparison | Logical | |||
Description | Symbol | Description | Symbol | Description | Symbol |
Exponentiation
|
^
|
Equality
|
=
|
Logical
Negation |
Not
|
Unary Negation
|
–
|
Inequality
|
<>
|
Logical
Conjunction |
AND
|
Division
|
/
|
Greater than
|
>
|
Logical
Exclusion |
Xor
|
Multiplication
|
*
|
Less than
|
<
|
Logical
Disjunction |
Or
|
Integer
|
\
|
Less than or
equal to |
<=
|
Logical
Equivalence |
Eqv
|
Modulus
Arithmetic |
mod
|
Grater than or
equal to |
>=
|
Logical
Implication |
Imp
|
Addition
|
+ | Object
equivalence |
Is | ||
Subtraction | – | ||||
String
Concatenation |
& |
ARRAYS
A standard structure for storing data in any programming language is an array. Whereas individual variables can hold single entities, such as a number, a date, or a string, arrays can hold sets or related data. An array has a name, as does a variable, and the values stored in it cab be accessed by an index.
Suppose if salary for 10 employees is to be stored, then variables Salay1, salary2 …Salay10 could be created to hold all 10 employee’s salary. But if number of employee’s goes to very large extent then it is impossible to create a variable for each employee. This way it not elegant too. Arrays are useful here, as they allow to refer to a series of variables by the same name and to use a number (an index0 to tell them apart. Arrays are declared as in the following;
Dim salary (99) as Integer
This declaration create an array named salary with 100 elements, with index numbers running from 0 to 99 and holds 100 values; salaries of 100 employees. Salary (0) is the first person’s salary, salary (1) the second person’s salary and so no. values are assigned to the elements of arrays as follows:
Salary (0) = 1000
All elements in an array have the same data type, of course, when the date type is variant, the individual elements can contain different kinds of data. By default, the first element of an array has index 0 (lower-bound) and the number that appears in parentheses in the Dim statement is the array’s upper limit (upper-bound). However, the array’s first element need not be zero. Lower limit (lower-bound) can explicitly be specified as in the following:
Dim Salary (1 to100) as integer
The lower bound can have any other value, provided it is smaller than the upper bound. The following declarations are valid:
Dim Greetings (10 to 20) as String
Dim Amounts (100 to 101) as Double
Suppose if the array Salary contains salaries of all the employees, one thing that is to be remembered is which person corresponds to each salary. This can be avoided by declaring another array names as in the following:
Dim Names (1 to 100) as string
Now values to the elements of both arrays can be assigned as in the following:
Names (0) =’ Ekambaram”
Salary (0) = 2000
Names (1) = “prema”
Salary (1) = 15000
Name (2) = “Gayathri”
Salary (2) =50000
—————————–
—————————–
Multi – Dimensional Arrays
Sometimes when storing values in an arrays, its related information has also to be stored. For example, to keep track of each pixel on a computer screen, both X and Y coordinates are to be referred. This can be doe using a multidimensional array to store the values.
Arrays of multiple dimensions can be declared as follows:
Dim Matrix (9, 9) as double
The above statements declares a two dimensional 10 by 10 array. But arrays can be extended for more dimensions as in the following:
Dim Multi D (3, 1 To 10, 1 to 15)
This declaration creates an array that has three dimensions with sizes 4 by 10 by 15. The total number of elements is the product of these three dimensions, or 600.
The benefit of using multidimensional arrays is that they are conceptually easier to manage.
Dynamic Arrays
Sometimes when declaring arrays its required size may not be known. Instead of making it large enough to hold the maximum number of data (which means the most of the array may be empty), arrays can be declared dynamically.
A dynamic arrays can be resized at time. Dynamic arrays are among the most flexible and convenient features in Visual Basic and they help to manage memory efficiently. For example, a large array can be used for short time and then can be feed up memory to the system when that array is no longer used.
Dynamic arrays are created in the same way as normal arrays, but without specifying it dimensions as in the following:
Dim Dyn Array ()
Later in the program, when the number of elements to be stored in the array is known, the Redim statement is used to redimension the array with the required size as follows.
Redim Dyn Array (count) ‘Count is probably as user-
‘entered value.
The Redim statement can appear only in a procedure. Unlike the Dim statement Redim is executable and so, can appear only inside a procedure. An array can redimensioned to multiple dimensions as follows:
Dim Matrix () as Double
Redim Matrix (9, 9, 9)
Note: the Redim statement can’t change the type of the array. Moreover, subsequent
Redim statements can change the bounds of an array and number of its dimensions |
REM Statement
Rem comments
Used to include explanatory remarks in a program. Allows comments to be added to a program. Everything on the line after the Rem statement is ignored by Visual Basic. A apostrophe (‘) can also be used in lieu of Rem statement.
Syntax
Rem comment
Or
‘comment
The comment argument is the text of any comment you want to include. After the Rem keyword, a space is required before comment.
The following examples illustrates the use of Rem statement:
Dim MyStr1, MyStr2
MyStr1 = “Hello”: Rem comment after a statement separated by a colon.
MyStr2 = “Goodbye” ‘This is also a comment; no colon is need.
Rem Comment on a line with no code; no colon is needed.
End statement
Ends a procedure or block.
Syntax
End
End function
End if
End property
End select
End sub
End type
End with
The End statement syntax has these forms.
Statement Description
End terminates execution immediately. Never required by itself
but may be placed any where in a procedure to end code
execution, close files opened with the open statement
and to clear variables.
End Function Required to end a Function statement.
End If Required to end a block if .. then … Else statement.
End property Required to end a property Let, property Get, or property
set procedure.
End select Required to end a select case statement.
End Sub Required to end sub statement.
End Type Required to end a user-defined type definition (type
statement).
End with Required to end a with statement