Control Structures selection In Visual Basic 6
Control Structures selection In Visual Basic 6
Visual Basic uses building blocks such as Variables, Data Types, Procedures, Functions and
Control Structures in its programming environment. This section concentrates on the
programming fundamentals of Visual Basic with the blocks specified.
Modules
Code in Visual Basic is stored in the form of modules. The three kind of modules are Form
Modules, Standard Modules and Class Modules. A simple application may contain a single
Form, and the code resides in that Form module itself. As the application grows, additional
Forms are added and there may be a common code to be executed in several Forms. To avoid
the duplication of code, a separate module containing a procedure is created that implements
the common code. This is a standard Module.
Class module (.CLS filename extension) are the foundation of the object oriented programming
in Visual Basic. New objects can be created by writing code in class modules. Each module can
contain:
Declarations : May include constant, type, variable and DLL procedure declarations.
Procedures : A sub function, or property procedure that contain pieces of code that can be
executed as a unit.
These are the rules to follow when naming elements in VB - variables, constants, controls,
procedures, and so on:
1. Numeric
Byte Store integer values in the range of 0 - 255
Integer Store integer values in the range of (-32,768) - (+ 32,767)
Store integer values in the range of (- 2,147,483,468) - (+
Long
2,147,483,468)
Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)
Double Store large floating value which exceeding the single data type value
store monetary values. It supports 4 digits to the right of decimal
Currency
point and 15 digits to the left
2. String
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.
+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
* Multiply 5*4 20
Logical Operators
Operators Description
AND Operation will be true only if both the operands are true
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
Using Option Explicit statement
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,
It may be convenient to declare variables implicitly, but it can lead to errors that may not be
recognized at run time. Say, for example a variable by name intcount is used implicitly and is
assigned to a value. In the next step, this field is incremented by 1 by the following statement
Intcount = Intcount + 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.
Or
Scope of variables
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.
Variables have a lifetime in addition to scope. The values in a module-level and public variables
are preserved for the lifetime of an application whereas local variables declared with Dim exist
only while the procedure in which they are declared is still being executed. The value of a local
variable can be preserved using the Static keyword. The follwoing procedure calculates the
running total by adding new values to the previous values stored in the static variable value.
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 the Public 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:
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.
The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.
Syntax of the If...Then selection
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.
e.g.:
If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If
Method 1
Method 2
e.g.: Assume you have to find the grade using nested if and display in a text box
e.g.: Assume you have to find the grade using select...case and display in the text box
Note: In this example I have used a message box function. In later lessons you will learn how
to use message box functions
A repetition structure allows the programmer to that an action is to be repeated until given
condition is true.
The Do While...Loop is used to execute statements until a certain condition is met. The
following Do Loop counts from 1 to 100.
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is
tested; if condition is True, then the statements are executed. When it gets to the Loop it goes
back to the Do and tests condition again. If condition is False on the first pass, the statements
are never executed.
The Do...Loop While statement first executes the statements and then test the condition after
each execution. The following program block illustrates the structure:
The programs executes the statements between Do and Loop While structure in any case.
Then it determines whether the counter is less than 501. If so, the program again executes the
statements between Do and Loop While else exits the Loop.
4 . Do Until...Loop Statement
An example for Do Until...Loop statement. The coding is typed inside the click event of the
command button
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the
command button.
Dim x As Integer
For x = 1 To 50
Print x
Next x
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Print x
Next
The above coding will display numbers vertically on the form. In order to display numbers
horizontally the following method can be used.
For x = 1 To 50
Print x & Space$ (2);
Next
To increase the space between the numbers increase the value inside the brackets after the &
Space$.
Following example is a For...Next repetition structure which is with the If condition used.
A For...Next loop condition can be terminated by an Exit For statement. Consider the
following statement block.
Dim x As Integer
For x = 1 To 10
Print x
If x = 5 Then
Print "The program exited at x=5"
Exit For
End If
Next x
The preceding code increments the value of x by 1 until it reaches the condition x = 5.
The Exit For statement is executed and it terminates the For...Next loop. The Following
statement block containing Do...While loop is terminated using Exit Do statement.
Dim x As Integer
Do While x < 10
Print x
x=x+1
If x = 5 Then
Print "The program is exited at x=5"
Exit Do
End If
Loop
With...End With statement
When properties are set for objects or methods are called, a lot of coding is included that acts
on the same object. It is easier to read the code by implementing the With...End
With statement. Multiple properties can be set and multiple methods can be called by using
the With...End With statement. The code is executed more quickly and efficiently as the
object is evaluated only once. The concept can be clearly understood with following example.
With Text1
.Font.Size = 14
.Font.Bold = True
.ForeColor = vbRed
.Height = 230
.Text = "Hello World"
End With
An array is a consecutive group of memory locations that all have the same name and the
same type. To refer to a particular location or element in the array, we specify the array name
and the array element position number.
The Individual elements of an array are identified using an index. Arrays have upper and lower
bounds and the elements have to lie within those bounds. Each index number in an array is
allocated individual memory space and therefore users must evade declaring arrays of larger
size than required. We can declare an array of any of the basic data types including
variant, user-defined types and object variables. The individual elements of an array are all of
the same data type.
Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the number of
elements required by the array so that the compiler may reserve the appropriate amount of
memory. Arrays may be declared as Public (in a code module), module or local. Module arrays
are declared in the general declarations using keyword Dim or Private. Local arrays are
declared in a procedure using Dim or Static. Array must be declared explicitly with keyword
"As".
Fixed-size array : The size of array always remains the same-size doesn't change during the
program execution.
Dynamic array : The size of the array can be changed at the run time- size changes during
the program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit
should always be within the range of long data type.
Declaring a fixed-array
In the above illustration, numbers is the name of the array, and the number 6 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6
elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower and
upper limit along with the To keyword. An example for this is given below.
In the above statement, an array of 10 elements is declared but with indexes running from 1 to
6.
A public array can be declared using the keyword Public instead of Dim as shown below.
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent
tables of values consisting of information arranged in rows and columns. To identify a
particular table element, we must specify two indexes: The first (by convention) identifies the
element's row and the second (by convention) identifies the element's column.
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays. Note that multidimensional arrays can have more than two dimensions.
Visual Basic supports at least 60 array dimensions, but most people will need to use more than
two or three dimensional-arrays.
It is also possible to define the lower limits for one or both the dimensions as for fixed size
arrays. An example for this is given here.
An example for three dimensional-array with defined lower limits is given below.
Basically, you can create either static or dynamic arrays. Static arrays must include a fixed
number of items, and this number must be known at compile time so that the compiler can set
aside the necessary amount of memory. You create a static array using a Dim statement with a
constant argument:
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101
items.
Most programs don't use static arrays because programmers rarely know at compile time how
many items you need and also because static arrays can't be resized during execution. Both
these issues are solved by dynamic arrays. You declare and create dynamic arrays in two
distinct steps. In general, you declare the array to account for its visibility (for example, at the
beginning of a module if you want to make it visible by all the procedures of the module) using
a Dim command with an empty pair of brackets. Then you create the array when you actually
need it, using a ReDim statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an
Option Base 1 statement is placed at the beginning of the module. My suggestion is this: Never
use an Option Base statement because it makes code reuse more difficult. (You can't cut and
paste routines without worrying about the current Option Base.) If you want to explicitly use a
lower index different from 0, use this syntax instead:
Dynamic arrays can be re-created at will, each time with a different number of items. When
you re-create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose
the data it contains. If you want to resize an array without losing its contents, use the ReDim
Preserve command:
When you're resizing an array, you can't change the number of its dimensions nor the type of
the values it contains. Moreover, when you're using ReDim Preserve on a multidimensional
array, you can resize only its last dimension:
Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual
Basic releases the memory allocated for its elements (and you can't read or write them any
longer); if the array is static, its elements are set to 0 or to empty strings.
You can use the LBound and UBound functions to retrieve the lower and upper indices. If the
array has two or more dimensions, you need to pass a second argument to these functions to
specify the dimension you need:
UDT structures can include both static and dynamic arrays. Here's a sample structure that
contains both types:
Type MyUDT
StaticArr(100) As Long
DynamicArr() As Long
End Type
...
Dim udt As MyUDT
' You must DIMension the dynamic array before using it.
ReDim udt.DynamicArr(100) As Long
' You don't have to do that with static arrays.
udt.StaticArr(1) = 1234
The memory needed by a static array is allocated within the UDT structure; for example, the
StaticArr array in the preceding code snippet takes exactly 400 bytes. Conversely, a dynamic
array in a UDT takes only 4 bytes, which form a pointer to the memory area where the actual
data is stored. Dynamic arrays are advantageous when each individual UDT variable might
host a different number of array items. As with all dynamic arrays, if you don't dimension a
dynamic array within a UDT before accessing its items, you get an error 9—"Subscript out of
range."
Variables of different data types when combined as a single variable to hold several related
informations is called a User-Defined data type.
A Type statement is used to define a user-defined type in the General declaration section of a
form or module. User-defined data types can only be private in form while in standard modules
can be public or private. An example for a user defined data type to hold the product details is
as given below.
The user defined data type can be declared with a variable using the Dim statement as in any
other variable declaration statement. An array of these user-defined data types can also be
declared. An example to consolidate these two features is given below.
A User-Defined data type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of
a TextBox namely text1 is to be assigned the name of the electronic good, the statement can
be written as given below.
Text1.Text = ElectronicGoods.ProdName
Text1.Text = ElectronicGoods(i).ProdName
User-defined data types can also be passed to procedures to allow many related items as one
argument.
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 Code window is opened for the module to which the procedure is to be added.
The Add Procedure option is chosen from the Tools menu, which opens an Add
Procedure dialog box as shown in the figure given below.
The name of the procedure is typed in the Name textbox
Under Type, Sub is selected to create a Sub procedure, Function to create a Function
procedure or Property to create a Property procedure.
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.