Control Flow Statements in Visual Basic
Control Flow Statements in Visual Basic
Decision making process is an important part of programming because it can help to solve practical problems
intelligently so that it can provide useful output or feedback to the user. For example, we can write a program that
can ask the computer to perform certain task until a certain condition is met. An application needs a built in
capability to test condition and take different course of action depending on the outcome of the test. Visual basic
provides three control flow, or decision, structures:
1. If..Then
2. If..Then..Else
3. Select case
If…Then : The If…Then structure tests the condition specified and it is True, execute the statement(s) follows.
The If structure can have a single-line or a multiple-line syntax. To execute one statement conditionally, we use
single line syntax as follows
If <condition> Then <statement>
Visual Basic evaluate the condition, and if it is True, execute the statement that’s follows. If the condition is False,
it continues with the statement following the If structure.
You can execute multiple statement by separating them with a colon :
If condition Then statement:statement:statement
Eg: If Month(date) = 1 Then Year = Year + 1
You can break the If statement into multiple lines
If Month(date) = 1 Then
Year = Year + 1
End If
If..Then..Else: The If…Then…Else statement executes one block of statements if the condition is True and
another block of statement if the condition is False. The syntax for If..Then..Else statement is as follows
If <condition> Then
Statement block 1
Else
Statement block 2
End If
Visual basic evaluate the condition, and if it is True, it executes the first block of statements and then jump to the
statement following the End If statement. If the condition is False, Visual basic ignore the first block of statement
and execute the block following the Else keyword
Multiple If..Then..Else Statement: The multiple If…Then…Else Statement uses several conditions with ElseIf
keyword. The syntax for multiple If…Then…Else statement is as follows
If condition1 Then
Statement Block 1
ElseIf condition2 Then
Statement Block 2
ElseIf condition3 Then
Statement Block 3
Else
Statement Block 4
End If
The conditions are evaluated from the top, and if one of them is true, the corresponding block of statement is
executed. The Else clause will be executed if none of the previous conditions are true.
Example
Score = InputBox(“Enter Score”)
If Score < 50 Then
Result = “Failed”
ElseIf Score < 75 Then
Result = “Pass”
ElseIf Score < 90 Then
Result = “Very Good”
Else
Result = “Excellent”
End If
Select Case: The Select Case Structure compares one expression to different value. The advantage of the Select
Case statement over multiple If…Then…Else statement is that it makes the code easier to read and maintain. The
syntax for Select Case statement is given below:
Loop Statement
The loop statement allow you to execute one or more lines of code repetitively. Looping Structures are an
important part of any programming language. Visual basic supports the following loop statements:
- Do…Loop
- For…Next
- While…Wend
Do…Loop: The Do…Loop execute a block of statements for as long as condition is True. Visual basic evaluates
an expression, and if it is True, the statements are executed. If the expression is False, the program continues and
the statement following the loop is executed.
There are two variation of the Do…Loop statement and both used the same basic model. A loop can be executed
either while the condition is True or until the condition becomes True. The two variation used the keywords While
and Until to specify how long the statement are execute.
To execute a block of statements while a condition is True, use the following syntax
Do While Condition
Statement Block
Loop
To execute a block of statement until the condition becomes True, use the following syntax
Do Until Condition
Statement block
Loop
For…Next: The For…Next loop is one of the oldest loop structures in programming language. Unlike the Do
Loop, the For…Next loop requires that you know how many times the statement in the loop will be executed.
The For…Next loop uses a variable(it’s called the loop’s counter) that increase or decreases in value during each
repetition of the loop. The syntax for For…Next loop is given below:
For counter = start To end [Step increment]
Statements
Next [counter]
The keywords in the square bracket are optional. The arguments counter, start, end and increment are all numeric.
The loop execute as many times as required for counter to reach (or exceed) the end value. In Executing a
For…Next loop, Visual Basic completes the following steps:
1. Set the counter equals to start
2. Test if the counter is greater than end. If so exit the loop. If the increment is negative, visual basic test to
see if the counter is less than end. If it is it exits the loop.
3. Execute the statement in the block
4. Increment counter by the amount specified with the increment argument. If the increment argument is not
specified, the counter is incremented by 1
5. Repeat the statements.
While…Wend: The While…Wend execute a block of statements while a condition is True. The syntax for
While..Wend is
While condition
Statement Block
Wend
If the condition is True, all statements are executed and when the Wend statement is reached, control return to
the while statement. While statement evaluate the condition again. If the condition is still True, the process is
repeated. If the condition is False, the program resumes with the statement following the Wend statement.
Nested Control structure
Control structures in visual basic can be nested in as many levels as you want. Its common practice to indent the
bodies of the nested decision and loop structure to make program easier to read. Given below is an example of a
nested For…Next loop that scans all the element of a two dimensional array:
For irow = 0 To Ubound(Array2(0))
For icol = 0 To Ubound(Array2(1))
{ process element Array2(irow, icol)) }
Next icol
Next irow
The Exit Statement
The Exit statement allow you to exit prematurely from a block of statement in a control structure, from loop, or
even from a procedure. Suppose you have a For…Next loop that calculates the square root of a series of numbers.
Because the square root of a negative number cant be calculated(the Sqr() function generates a runtime error),
you might want to halt the operation if the array contain an invalid value. To exit the loop prematurely, use the
Exit For statement as follows:
For I = 0 To UBound(nArray())
If nArray(i) < 0 Then Exit For
nArray(i) = Sqr(nArray(i))
Next
If a negative element is found in this loop, the program exit the loop and continues with statement following the
Next statement
String Manipulation in Visual Basic
The Len Function: The Len() function return an integer value which is the length of the phrase or sentence
(including the empty spaces).
Syntax: Len(Phrase)
The Right() Function: The right function extract a subtring from phrase starting from the right.
Syntax: Right(phrase, n) where n is the number of character to be extracted.
Eg: Right(“Visual Basic”, 4) = “asic”
The Left() Function: The Left() function extract a substring from a phrase starting from left
Syntax: Left(phrase, n) where n is the number of character to be extracted
Eg: Left(“Visual Basic”, 4) = “Visu”
The Ltrim() Function: The function Trim the empty spaces of the left portion of the phrase
Syntax: Ltrim(phrase)
Eg: Ltrim(“ name”) = “name”
The Rtrim() Function: The function Trim the empty spaces of the right portion of the phrase
Syntax: Rtrim(phrase)
Eg: Rtrim(“name ”) = “name”
The Trim() Function: The function Trim the empty spaces irrespective of the side of the phrase
Syntax: Rtrim(phrase)
Eg: Trim(“ name ”) = “name”
The Mid Function: The mid function extracts a substring from the original phrase or string.
Syntax: Mid(phrase, postion, n)
position specify the postion of the phrase from which the extraction process will start.
n specify the number of character to be extracted.
Eg: Mid(“Visual Basic”, 3, 6) = “sual B”
The InStr Function: The InStr Function look for a phrase that is embedded within the original phrase and return
the starting position of the embedded phrase.
Syntax: InStr(n, Original Phrase, embedded)
Where n is the postion where the InStr function will begin to look for embedded phrase.
Eg: InStr(1, “Visual Basic”, “Basic”) = 8
The UCase and LCase Function: The UCase Function convert a string or phrase to upper case. Likewise LCase
convert a string or phrase to lower case.
The Str and Val Function: The Str function convert a number to a string while the Val function convert a
numeric string to a number.
The Chr and Asc Function: The Chr Function return the string that correspond to an ASCII code
Syntax: Chr(Character Code)
Eg: Chr(65) = “A”
Asc Function convert an ASCII character or symbol to the corresponding ASCII code.
Syntax: Asc(“B”) = 66
String function: The string function has two argument, a number and a single character string and it return a
string consisting of specified character repeated specified number of time.
Syntax: String(n, “Character”)
Eg: String(10, “#”) will produce
“##########”
Converting Variable Type
In some situation, you need to need to convert variables from one type into another. Following are the Visual
basic functions that perform data type conversion.
CBool Boolean Data Type Any valid Char or String or numeric expression.
Byte.MinValue (0) through Byte.MaxValue (255) (unsigned);
fractional parts are rounded.1
CByte Byte Data Type Starting with Visual Basic 15.8, Visual Basic optimizes the
performance of floating-point to byte conversion with
the CByte function; see the Remarks section for more information. See
the CInt Example section for an example.
CDate Date Data Type Any valid representation of a date and time.
-1.79769313486231570E+308 through -4.94065645841246544E-324
CDbl Double Data Type for negative values; 4.94065645841246544E-324 through
1.79769313486231570E+308 for positive values.
Int32.MinValue (-2,147,483,648)
through Int32.MaxValue (2,147,483,647); fractional parts are
rounded.1
CInt Integer Data Type
Starting with Visual Basic 15.8, Visual Basic optimizes the
performance of floating-point to integer conversion with
the CInt function;
Int64.MinValue (-9,223,372,036,854,775,808)
through Int64.MaxValue (9,223,372,036,854,775,807); fractional parts
are rounded.1
CLng Long Data Type
Starting with Visual Basic 15.8, Visual Basic optimizes the
performance of floating-point to 64-bit integer conversion with
the CLng function; see the Remarks section for more information. See
the CInt Example section for an example.
-3.402823E+38 through -1.401298E-45 for negative values;
CSng Single Data Type
1.401298E-45 through 3.402823E+38 for positive values.
Returns for CStr depend on the expression argument. See Return
CStr String Data Type
Values for the CStr Function.
Cvar Variant Data Type Convert a other data type into variant data type