0% found this document useful (0 votes)
13 views

Unit III Visual Basic

Uploaded by

vanshthakral2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit III Visual Basic

Uploaded by

vanshthakral2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Unit III

Control Structure
Prgrams are not monolithic sets of commands that carry out the same
calculation every time they are executed. Instead, they adjust their behavior
depending on the data supplied or based on the result of a test condition. Visual
basic 6.0 provides three-control flow, or decision structures to take a course of
action depending on the outcome of the test. They are:

 IF … Then
 If … Then … Else
 Select Case

IF Blocks in VB6.0
The If control flow blocks provide a great way for decision making where one or
more statements are executed depending upon a condition.

If-Then
In case of If-Then block, the condition is first checked. The condition can either
be True or False. If it is True, the statements inside the If-Then block is
executed. Otherwise, it does not execute the code in the If-Then block, the If-
Then structure is skipped. It starts executing the statements just after the 'End
if' phrase.

Syntax:
If Condition Then
statements
End If

Example: To check if the number is positive.


Dim num1 As Integer
num1 = 30
If num1 > 0 Then
Print "The number is positive"
End If

Output: The number is positive.

Single Line version of If-Then


Single line and single statement
If a > 0 Then b = 1

Single line and multiple statements


If a > 0 Then b = 1: c = 2

If-Else
An If-Else block has two parts. If the condition is True then the first part is
executed, otherwise the control goes to the second part and starts executing
the lines of statements in the second part of the If-Else block.

Syntax:

If Condition Then
statements1
Else
statements2
End If

If Condition is true then statements1 will be executed and if Condition is false,


statements2 will be executed.

Example: To print the larger number.

Dim num1 As Integer, num2 As Integer


num1 = 30
num2 = 50
If num1 > num2 Then
Print num1
Else
Print num2
End If

Output: 50

Single line version of If-Else


If a > 0 Then b = 1 Else b = 0

Nested If-Else
If you have programmed in other languages, you might probably know about
nested if-else control flow block. In VB it is the same concept. See the
syntax and the examples to capture the concept.

In nested if-else, the structure is little changed, little advanced better to say,
from the simple If-Block. Here if the first condition does not satisfy, it looks
for the next condition preceded by the ElseIf term, if that too does not
satisfy, it looks for the next, and it goes on until the end of the structure.

Syntax:
If Condition Then
statements
ElseIf Condition then
statements
ElseIf Condition Then
statements
.......................
......................
Else
statements
End If

Example:

a = Val(InputBox("Enter a no."))

If a > 0 Then
Print "Positive"
ElseIf a < 0 Then
Print "Negative"
Else
Print "Zero"
End If

In a nested if-else block, one If-Block can reside in another. See the example
below.

Example:

'If-statement inside another if-statement


Dim a As Integer
a = Val(txtNumber.Text)

If a > 0 Then
Print "Positive"
If a > 2 Then
Print "Greater than 2"
Else
Print "Less than 2"
End If
Else
If a < 0 Then
Print "Negative"
End If
End If

Boolean Operators : And, Or, Not, Xor


And indicates that all expressions are true, Or indicates that one of the
expressions or all are true, Not indicates negation, Xor indicates that one of the
expressions are true.

Example:

Dim num1 As Integer, num2 As Integer


num1 = InputBox("Enter 1st number")
num2 = InputBox("Enter 2nd number")

If (num1 > 0) And (num2 > 0) Then


MsgBox "Both the numbers are positive"
End If
If (num1 > 0) Or (num2 > 0) Then
MsgBox "Either 1st number or 2nd number or both are positive"
End If
If Not (num1 = 0) Then
MsgBox "The first number is non-zero"
End If

If (num1 > 0) Xor (num2 > 0) Then


MsgBox "Either 1st number or 2nd number is positive"
End If

Select Case Blocks


This lesson takes you through the Select Case block, a very useful decision
making structure in Visual Basic.

The Select Case block provides an efficient way for decision making which is
used to execute one block of statement(s) among a list of statement blocks
according to the determined value of an expression. The expression is preceded
by the "Select Case" phrase. The choices are made based on the value of this
expression

Syntax:

Select Case expression


Case value0
statements
Case value1
statements
Case value2
statements
...........
...............
Case else
statements
End select

Example:

Dim num As Integer


num = Val(Text1.Text)
Select Case num
Case 0
Print "You have entered zero"
Case 1
Print "You have entered one"
Case 2
Print "You have entered two"
Case Else
Print "The number you entered is greater than 2"
End Select

One block of statement(s) will be executed depending upon the value of num.
If num=0 then, Case 0 will be evaluated and if num =1 then Case 1 will be
evaluated.

See the other forms of Select Case Structure in the following programs.

Example:

Dim score As Integer


score = Val(Text1.Text)
Select Case score
Case 900 To 1000
Print "First position"
Case 800 To 899
Print "Second position"
Case 700 To 799
Print "Third position"
Case Else
Print "No position, try again"
End Select

Example:

Dim num As Integer


num = Val(Text1.Text)
Select Case num
Case Is > 0
Print "Positive number"
Case Is < 0
Print "Negative number"
Case 0
Print "Zero"
End Select
Example:

Select Case value


Case 0, 1, 2, 3, 4, 5
Print "The values are 0,1,2,3,4,5"
Case Else
Print "Other values"
End Select

Do Loops
Loops are used to execute a block of statements repeatedly based on a condition.

There are different forms of Do Loops in Visual Basic 6. These are:

i) Do While...Loop
ii) Do...Loop While
iii) Do...Loop Until.

i) Do While...Loop: The Do While...Loop structure is used to execute statements


repeatedly based on a certain condition.
It first tests the condition then evaluates the loop. If the condition is True, the
statements block is executed. If the condition is false, the statements inside the
loop are not executed and the control is transferred to the line after the loop
statements.

The repeated execution of the statements inside the loop goes on as long as the
condition is true. When the condition becomes False, it exits the loop.

Syntax:

Do While Condition

statement(s)

Loop
Example: To print from 0 to 9.

Dim num As Integer


num = 0
Do While num < 10
Print num
num = num + 1
Loop

The program first checks the condition. If num is less than 10, the statements
inside the Do While...Loop are executed. Again, the condition is checked. If it is
True, the statements are executed. In this way, the iterative execution goes on.
When the value of num becomes 10, the loop ends.

ii) Do...loop while:

This loop structure first executes the statements and after that tests the condition
for the repeated execution.

Syntax:

Do

statement(s)

Loop while Condition

Example: To print from 0 to 10.

Dim num As Integer


num = 0
Do
Print num
num = num + 1
Loop While num <= 10
Another example: Though the condition does not satisfy, the program will print
11 as this loop structure first executes the statements and after that tests the
condition.

Dim num As Integer


num = 11
Do
Print num
num = num + 1
Loop While num < 10

Output: 11

iv) Do...loop until:

The Do...Loop Untill structure executes the statements repeatedly until the
condition is met. It is an infinite loop if the condition does not satisfy. In this
case, the program cannot be stopped. Press Ctrl+Break key combination to
force it to stop. The loop continues until the condition is met. The repeated
execution of the statements stops when the condition is met.

Syntax:

Do

statement(s)

Loop Until Condition

Example:

'x is incremented until x becomes greater than 10

Dim x As Integer
x=0
Do
x=x+1
Loop Until x > 10

MsgBox x
For...Next Loops

For...Next loop structure is useful when a block of statements are to be executed for
unknown number of times. But if a block of statements are to be executed for specified
number of times then a For … Next loop is better choice. Unlike a Do loop, a For loop uses
a variable called a counter that increases or deceases in value during each repetition of the
loop.

Syntax

For counter = start To end [step increment]

Statements

Next [counter]

The argument counter, start, end, and increment are all numeric. The increment
argument can be either positive or negative If increment is positive, start must
be less than or equal to end or the statements in the loop will not execute. If
increment is negative, start must be greater than or equal to end for the body
of the loop to execute. If Step isn‟t set, then increment defaults to 1.

Example: To print 0 to 10.

Dim i As Integer
For i = 0 To 10
Print i
Next i

When the value of i is 0, the Print statement is executed then i is incremented


to 1. It checks whether the value of i is from 0 to 10. If it satisfies, the Print
statement is executed again. In this way, the loop goes on until the value of i
exceeds 10. Every time, the value of i is incremented by 1.

Example: To print 0 to 6 in steps of 2.

Dim i As Integer
For i = 0 To 6 Step 2
Print i
Next i

Every time, the value of i is incremented by 2.


Output:
0
2
4
6

Example: To print in descending order from 10 to 0 in step of -3.

Dim i As Integer
For i = 10 To 0 Step -3
Print i
Next i

Every time, the value of i is decremented by 3.

Output:
10
7
4
1

For Each … Next


A For Each … Next loop is similar to a For … Next loop, but it repeats a group
statements for each element in a collection of objects or in an array instead of
repeating the statements a specified number of times This is especially helpful
when the number of elements of a collection is not known.

Syntax

For Each element In group

Statements

Next element

Exit For and Exit Do statement


A For Next Loop can be terminated by an Exit For statement and a Do loop can
be terminated by an Exit Do statement.

Example: Exit For statement :


Dim i As Integer
For i = 0 To 10
If i = 3 Then
Exit For
End If
Print i
Next i

Output:
0
1
2

Example: Exit Do statement

Dim num As Integer


num = 0
Do While num < 10
Print num
num = num + 1

If num = 4 Then
Exit Do
End If

Loop

Output:
0
1
2
3

The OptionButton Control


This control lets you choose from several items among other in a list. This is
one of the mostly frequently used controls in application developement. When
you click on an OptionButton, it is switched to selected state or ON state, and
all other option buttons in the group become unselected or OFF.
Example:
Private Sub Command1_Click()
If Option1.Value = True Then
Print "Option1 is ON"
Else
Print "Option1 is OFF"
End If
End Sub

Output:

When Option1.value = True then the Option Button is ON and when


Option1.value = False then the Option button is OFF.

Example:

Private Sub cmdCheck_Click()


If optWindows.Value = True Then
Print "Windows is selected"
ElseIf optLinux.Value = True Then
Print "Linux is selected"
ElseIf optMac.Value = True Then
Print "Mac is selected"
End If
End Sub
Output:

Check Box Control


This control has three states : checked, unchecked and grayed. The value
property determines the checkbox state.

Example:

Private Sub cmdShow_Click()


If Check1.Value = 1 Then
Print "Checked !"
ElseIf Check1.Value = 0 Then
Print "Unchecked !"
End If
End Sub

Output:
If you assign Check1.Value =1 then the CheckBox is checked and if
Check1.Value = 0 then it is unchecked. If Check1.Value = 2 then the checkbox
is grayed.

Example: The previous program can also be written in the following way.

Private Sub cmdShow_Click()


If Check1.Value = vbChecked Then
Print "Checked !"
ElseIf Check1.Value = vbUnchecked Then
Print "Unchecked !"
End If
End Sub

Output:

'vbChecked' and 'vbUnchecked' are vb constants whose values are 1 and 0


respectively.
The grayed state can be set using the 'vbGrayed' vb constant whose value is 2.

Example: Program to make multiple choices.

Private Sub cmdShow_Click()


If chkTea.Value = 1 Then
Print "Tea"
End If

If chkCoffee.Value = 1 Then
Print "Coffee"
End If

If chkPizza.Value = 1 Then
Print "Pizza"
End If
If chkChocolate.Value = 1 Then
Print "Chocolate"
End If
End Sub

Output:

Select Case Blocks


The Select Case block provides an efficient way for decision making which is
used to execute one block of statement(s) among a list of statement blocks
according to the determined value of an expression. The expression is preceded
by the "Select Case" phrase. The choices are made based on the value of this
expression.

Syntax:
Select Case expression
Case value0
statements
Case value1
statements
Case value2
statements
...........
...............
Case else
statements
End select
Example:
Dim num As Integer
num = Val(Text1.Text)
Select Case num
Case 0
Print "You have entered zero"
Case 1
Print "You have entered one"
Case 2
Print "You have entered two"
Case Else
Print "The number you entered is greater than 2"
End Select

One block of statement(s) will be executed depending upon the value of num.
If num=0 then, Case 0 will be evaluated and if num =1 then Case 1 will be
evaluated.

See the other forms of Select Case Structure in the following programs.

Example:
Dim score As Integer
score = Val(Text1.Text)
Select Case score
Case 900 To 1000
Print "First position"
Case 800 To 899
Print "Second position"
Case 700 To 799
Print "Third position"
Case Else
Print "No position, try again"
End Select

Example:
Dim num As Integer
num = Val(Text1.Text)
Select Case num
Case Is > 0
Print "Positive number"
Case Is < 0
Print "Negative number"
Case 0
Print "Zero"
End Select

Example:
Select Case value
Case 0, 1, 2, 3, 4, 5
Print "The values are 0,1,2,3,4,5"
Case Else
Print "Other values"
End Select
Arrays
An array is a collection of items of the same data type. All items have the same
name and they are identified by a subscript or index. When you need to work
with several similar data values, you can use array to eliminate the difficulties
of declaring so many variables. For example, if you want to compute the daily
sales and sum the sales amount after 30 days, you don't need to have 30
variables. Just simply declare an array of size 30 and get your work done !

Declaring an array
Syntax: Dim Variable_Name(index) As [Type]

Example:
Dim month(10) As Integer '11 elements
'or
Dim month(1 to 12) as Integer '12 elements

In the first line, month(10) is a collection of 11 integer values or items.


month(0) is the 1st item and month(10) is the 10th & last item of the array. So
0 and 10 are respectively the lower bound and upper bound of the array.

In the other line, month(1 to 12) is a collection of 12 integer values or elements


or items where month(1) is the 1st item and month(12) is the last. So 1 and 12
are respectively the lower bound and upper bound of the array.

Types of array
The array used in the example is a one-dimensional and fixed-size array. An
array can have more than one dimension. The other types of arrays are multi-
dimensional arrays, Dynamic arrays and Control arrays.

Fixed-Size Array: We know the total number of items the array in the above
example holds. So that is a Fixed-Size array.
The LBound and UBound functions
The LBound and Ubound functions return the lower bound and upper bound of
an array respectively.

Example:

Private Sub cmdDisplay_Click()


Dim arr(10) As Integer
a = LBound(arr)
b = UBound(arr)

MsgBox "Lower bound = " & a & " Upper bound = " & b

End Sub

Initializing an array
You can use For Loop to initialize an array.

Example:
Dim day(10) As Integer, i As Integer
For i = 0 To 10
day(i) = InputBox("Enter day value")
Next i

You can also initialize each array item separately in the way a variable is
initialized.

Example: This program inputs the Sale amount of each day and sums the total
amount of 5 days.

Private Sub cmdStart_Click()


Dim SaleDay(1 To 5) 'Sale in a particular day
Dim i As Integer, Sale As Long
Sale = 0

For i = 1 To 5
SaleDay(i) = InputBox("Enter Sale amount of Day " & i)
Sale = Sale + SaleDay(i)
Next i

MsgBox "Total Sale of 5 days = $" & Sale

End Sub

Multi-Dimensional Arrays:
An array can be multi-dimensional that means, it can have more than one
dimension. A list of data is represented in a one-dimensional array where a
multi-dimensional array represents a table of data. An array can be two
dimensional, three dimensional and so on. We generally don't need an array of
more than two dimensions, it is enough to use one and two dimensional arrays.
You can use a higher dimensional array when the program is too complex. A
two dimensional array takes the row-column form.

Declaration:
Dim value(5, 5) As Integer 'two dimensional
'Or,
Dim value(1 to 5, 1 to 5) As Double
Dim number(6, 9, 8) As Integer 'three dimensinoal

Initialization:

To initialize the array elements, you first need to recognize the array elements.
For example, the array 'value(2, 2)' has 9 elements. They are
value(0,0), value(0,1),value(0,2), value(1,0), value(1,1), value(1,2), value(2,0
), value(2,1), value(2,2). For the initialization, you may wish to use For Loop or
initialize each element like variables. Using For Loop is a better choice as it
reduces the number of lines of code. But sometimes, separately initializing each
element like a variable is much more convenient. And it also depends on the
type of program you are writing.

Addition of 2D matrices : Example of a two


dimensional array
Example:

Private Sub cmdSum_Click()


Dim matrix1(1, 1) As Integer, matrix2(1, 1) As Integer
Dim sum(1, 1) As Integer
'initializiation of matrix1
matrix1(0, 0) = Val(Text1.Text)
matrix1(0, 1) = Val(Text2.Text)
matrix1(1, 0) = Val(Text3.Text)
matrix1(1, 1) = Val(Text4.Text)

'initializiation of matrix2
matrix2(0, 0) = Val(Text5.Text)
matrix2(0, 1) = Val(Text6.Text)
matrix2(1, 0) = Val(Text7.Text)
matrix2(1, 1) = Val(Text8.Text)

'Summation of two matrices


For i = 0 To 1
For j = 0 To 1
sum(i, j) = matrix1(i, j) + matrix2(i, j)
Next j
Next i

'Displaying the result


Print "The resultant matrix"
For i = 0 To 1
For j = 0 To 1
Print sum(i, j);

Next j
Print ""
Next i
End Sub

Static array
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:

' An array defined in a BAS module (with Private scope)


Dim Customers() As String
...
Sub Main()
' Here you create the array.
ReDim Customer(1000) As String
End Sub

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:

ReDim Customers(1 To 1000) As String

Dynamic Array

In case of a fixed size array, we have seen that the size of the array is fixed or
unchanged, but there may be some situations where you may want to change
the array size. A dynamic arraycan be resized at run time whenever you want.
Declaring dynamic arrays
1. Declare the array with empty dimension list.
Example : Dim arr() As Integer

2. Resize the array with the ReDim keyword.


Example : ReDim arr(5) As Integer
or, ReDim arr(2 To 5) As Integer

Example:

Dim ar() As Integer


ReDim ar(2) As Integer

Note: Unlike the Dim and Static statements, the ReDim statements are
executable. So a ReDim statement can only be in a procedure and when you
execute the ReDim statement, all the values stored in the array are lost. You
can use the ReDim statement repeatedly to change the array size.

Preserving the values of Dynamic arrays


The ReDim statement deletes all the values stored in the array. You can
preserve the element values using the Preserve keyword. So using Preserve
keyword with ReDim statements enables you to change the array size without
losing the data in the array.

Example:

Dim arr() As Integer


ReDim arr(2) As Integer

For i = 0 To 2
arr(i) = InputBox("Enter the value")
Next i

ReDim Preserve arr(3) As Integer


arr(3) = 9
Print arr(0), arr(1), arr(2), arr(3)

Output: If the input values through InputBox are 5,6,7 then the following will be
printed on the form.
5 6 7 9

You might also like