Week 2 Visual Basic Tutorial
Week 2 Visual Basic Tutorial
By default Visual Basic variables are of variant data types. The variant data type can store numeric, date/time or
string data. When a variable is declared, a data type is supplied for it that determines the kind of data they can store.
The fundamental data types in Visual Basic including variant are integer, long, single, double, string, currency, byte
and boolean. Visual Basic supports a vast array of data types. Each data type has limits to the kind of information and
the minimum and maximum values it can hold. In addition, some types can interchange with some other types. A list
of Visual Basic's simple data types are given below.
1. Numeric
Use to store alphanumeric values. A variable length string can store approximately 4 billion characters
3. Date
Use to store date and time values. A variable declared as date type can store both date and time values and it can
store date values 01/01/0100 up to 12/31/9999
4. Boolean
Boolean data types hold either a true or false value. These are not stored as numeric values and cannot be used as
such. Values are internally stored as -1 (True) and 0 (False) and any non-zero value is considered as true.
5. Variant
Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare a variable without any
data type by default the data type is assigned as default.
Arithmetical Operators
Result
Operators Description Example
Operators Description
OR Operation will be true if either of the operands is true
AND Operation will be true only if both the operands are true
Variables in Visual Basic 6
Variables are the memory locations which are used to store values temporarily. A defined naming strategy has to be
followed while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255
characters. It must be unique within the same scope. It should not contain any special character like %, &, !, #, @ or
$.
There are many ways of declaring variables in Visual Basic. Depending on where the variables are declared and how
they are declared, we can determine how they can be used by our application. The different ways of declaring
variables in Visual Basic are listed below and elucidated in this section.
Explicit Declaration
Scope of Variables
Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a variable should be declared
before using it. Automatically whenever Visual Basic encounters a new variable, it assigns the default variable type
and value. This is called implicit declaration. Though this type of declaration is easier for the user, to have more
control over the variables, it is advisable to declare them explicitly. The variables are declared with a Dim statement
to name the variable and its type. The As type clause in the Dim statement allows to define the data type or object
type of the variable. This is called explicit declaration.
Syntax
For example,
Intcount = intcont + 1
This calculation will result in intcount yielding a value of 1 as intcount would have been initialized to zero. This is
because the intcount variable has been mityped as incont in the right hand side of the second variable. But Visual
Basic does not see this as a mistake and considers it to be new variable and therefore gives a wrong result.
In Visual Basic, to prevent errors of this nature, we can declare a variable by adding the following statement to the
general declaration section of the Form.
Option Explicit
This forces the user to declare all the variables. The Option Explicit statement checks in the module for usage of any
undeclared variables and reports an error to the user. The user can thus rectify the error on seeing this error
message.
The Option Explicit statement can be explicitly placed in the general declaration section of each module using the
following steps.
Check Require Variable Declaration option and then click the OK button
Scope of variables
A variable is scoped to a procedure-level (local) or module-level variable depending on how it is declared. The scope
of a variable, procedure or object determines which part of the code in our application are aware of the variable's
existence. A variable is declared in general declaration section of e Form, and hence is available to all the
procedures. Local variables are recognized only in the procedure in which they are declared. They can be declared
with Dim and Static keywords. If we want a variable to be available to all of the procedures within the same module,
or to all the procedures in an application, a variable is declared with broader scope.
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to the code inside the
procedure and can be declared using the Dim statements as given below.
The local variables exist as long as the procedure in which they are declared, is executing. Once a procedure is
executed, the values of its local variables are lost and the memory used by these variables is freed and can be
reclaimed. Variables that are declared with keyword Dim exist only as long as the procedure is being executed.
Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and therefore retains or preserves value
even when a procedure ends. In case we need to keep track of the number of times a command button in an
application is clicked, a static counter variable has to be declared. These static variables are also ideal for making
controls alternately visible or invisible. A static variable is declared as given below.
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulate was declared with Dim instead of static, the previously accumulated values would not be
preserved accross calls to the procedure, and the procedure would return the same value with which it was called. To
make all variables in a procedure static, the Static keyword is placed at the beginning of the procedure heading as
given in the below statement.
Example
The following is an example of an event procedure for a CommandButton that counts and displays the number of
clicks made.
The first time we click the CommandButton, the Counter starts with its default value of zero. Visual Basic then adds 1
to it and prints the result.
A module level variable is available to all the procedures in the module. They are declared using thePublic or
the Private keyword. If you declare a variable using a Private or a Dim statement in the declaration section of a
module—a standard BAS module, a form module, a class module, and so on—you're creating a private module-level
variable. Such variables are visible only from within the module they belong to and can't be accessed from the
outside. In general, these variables are useful for sharing data among procedures in the same module:
You can also use the Public attribute for module-level variables, for all module types except BAS modules. (Public
variables in BAS modules are global variables.) In this case, you're creating a strange beast: a Public module-level
variable that can be accessed by all procedures in the module to share data and that also can be accessed from
outside the module. In this case, however, it's more appropriate to describe such a variable as a property:
You can access a module property as a regular variable from inside the module and as a custom property from the
outside:
' From outside Form1 module...
Form1.CustomerName = "John Smith"
The lifetime of a module-level variable coincides with the lifetime of the module itself. Private variables in standard
BAS modules live for the entire life of the application, even if they can be accessed only while Visual Basic is
executing code in that module. Variables in form and class modules exist only when that module is loaded in
memory. In other words, while a form is active (but not necessarily visible to the user) all its variables take some
memory, and this memory is released only when the form is completely unloaded from memory. The next time the
form is re-created, Visual Basic reallocates memory for all variables and resets them to their default values (0 for
numeric values, "" for strings, Nothing for object variables).
A variable can have the same name and different scope. For example, we can have a public variable named R and
within a procedure we can declare a local variable R. References to the name R within the procedure would access
the local variable and references to R outside the procedure would access the public variable.
Visual Basic offers different types of procedures to execute small sections of coding in applications. The various
procedures are elucidated in details in this section. Visual Basic programs can be broken into smaller logical
components called Procedures. Procedures are useful for condensing repeated operations such as the frequently
used calculations, text and control manipulation etc. The benefits of using procedures in programming are:
It is easier to debug a program a program with procedures, which breaks a program into discrete logical limits.
Procedures used in one program can act as building blocks for other programs with slight modifications.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the
statements between Sub and End Sub are executed. The syntax for a sub procedure is as follows:
arglist is a list of argument names separated by commas. Each argument acts like a variable in the procedure. There
are two types of Sub Procedures namely general procedures and event procedures.
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an underscore(_), and the event
name. The following syntax represents the event procedure for a Form_Load event.
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statements in a separate procedure (general procedure) and then call
them in the event procedure.
The Add Procedure option is chosen from the Tools menu, which opens an Add Procedure dialog box as
shown in the figure given below.
Under Scope, Public is selected to create a procedure that can be invoked outside the module, or Private to
create a procedure that can be invoked only from within the module.
We can also create a new procedure in the current module by typing Sub ProcedureName, Function
ProcedureName, or Property ProcedureName in the Code window. A Function procedure returns a value and a Sub
Procedure does not return a value.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They are especially useful for
taking one or more pieces of data, called arguments and performing some tasks with them. Then the functions
returns a value that indicates the results of the tasks complete within the function.
The following function procedure calculates the third side or hypotenuse of a right triangle, where A and B are the
other two sides. It takes two arguments A and B (of data type Double) and finally returns the results.
The above function procedure is written in the general declarations section of the Code window. A function can also
be written by selecting the Add Procedure dialog box from the Tools menu and by choosing the required scope and
type.
Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create read only properties for
Forms, Standard modules and Class modules. Visual Basic provides three kind of property procedures-Property Let
procedure that sets the value of a property, Property Get procedure that returns the value of a property, and Property
Set procedure that sets the references to an object.
Control Structures in Visual Basic 6.0
Control Statements are used to control the flow of program's execution. Visual Basic supports control structures such
as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do While...Loop, While...Wend, For...Next
etc method.
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is
skipped.
If <condition> Then
statement
End If
The If...Then...Else selection structure allows the programmer to specify that a different action is to be performed
when the condition is True than when the condition is False.
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structures
inside If...Then...Else structures.
Method 1
Method 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of statements from
among multiple block of statements. Select...case is more convenient to use than the If...Else...End If. The following
program block illustrate the working of Select...Case.
e.g.: Assume you have to find the grade using select...case and display in the text box
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select
Note: In this example I have used a message box function. In later lessons you will learn how to use message box
functions