Control Statement (Visual Basic)
Control Statement (Visual Basic)
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.
Syntax of the If...Then selection
If <condition> Then
statement
End If
e.g.: If average>75 Then
txtGrade.Text = "A"
End If
If...Then...Else selection structure
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.
Syntax of the If...Then...Else selection
If <condition > Then
statements
Else
statements
End If
e.g.: If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection
structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
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
If average > 75 Then
txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If
Select...Case selection structure
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.
Syntax of the Select...Case selection structure
Select Case Index
Case 0
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
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
A repetition structure allows the programmer to that an action is to be repeated until given condition is
true.
Do While... Loop Statement
The Do While...Loop is used to execute statements until a certain condition is met. The following Do
Loop counts from 1 to 100.
Dim number As Integer
number = 1
Do While number <= 100
number = number + 1
Loop
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.
While... Wend Statement
A While...Wend statement behaves like the Do While...Loop statement. The
following While...Wend counts from 1 to 100
Dim number As Integer
number = 1
While number <=100
number = number + 1
Wend
Do...Loop While Statement
The Do...Loop While statement first executes the statements and then test the condition after each
execution. The following program block illustrates the structure:
Dim number As Long
number = 0
Do
number = number + 1
Loop While number < 201
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.
Do Until...Loop Statement
Unlike the Do While...Loop and While...Wend repetition structures, the Do Until... Loop structure tests
a condition for falsity. Statements in the body of a Do Until...Loopare executed repeatedly as long as the
loop-continuation test evaluates to False.
An example for Do Until...Loop statement. The coding is typed inside the click event of the command
button
Dim number As Long
number=0
Do Until number > 1000
number = number + 1
Print number
Loop
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command button.
The For...Next Loop
The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition structure
handles all the details of counter-controlled repetition. The following loop counts the numbers from 1 to
100:
Dim x As Integer
For x = 1 To 50
Print x
Next
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 following loop counts numbers as 1, 3, 5, 7..etc
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.
Dim number As Integer
For number = 1 To 10
If number = 4 Then
Print "This is number 4"
Else
Print number
End If
Next
In the output instead of number 4 you will get the "This is number 4".
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
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
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
In the above coding, the object Text1, which is a text box is evaluated only once instead of every
associated property or method. This makes the coding simpler and efficient.
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:
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
+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
* Multiply 5*4 20
Relational Operators
Logical Operators
Operators Description
AND Operation will be true only if both the operands are true
An Array
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:
' This is a static array.
Dim Names(100) As String
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:
If you're creating an array that's local to a procedure, you can do everything with a single 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."