SELECTION
Selection arises when a condition exists in a problem and you need to take a decision or make a
choice.
In Visual Basic, a condition is coded by using a data name (or a variable) which compared with a
value or a text, depending on whether the variable is numeric or string.
Types of selection
Simple selection
Binary selection
Multiple selection
Relational operators
A relational operator is used to separate a condition and its value or text.
Operator Meaning
= Equal to
> Greater than
< Smaller than
>= Greater or equal to
<= Smaller or equal to
<> Not equal to
Simple Selection
Syntax IF condition THEN
Statement
Endif
Example If average > 40 Then
Print “Passed”
Endif
Worked example
Question
Write a program that will input two numbers. If the first number is greater than the second number, then print the word
‘greater’.
Answer
Rem Declare Variables
Dim First As Integer
Dim Second As Integer
Private Sub Form_Load( )
Rem Input numbers
First = InputBox ( “ enter a number” )
Second InputBox ( “ enter another number” )
Rem compare values
If First > Second Then
[Link]
Print “greater”
End If
End Sub
Binary Selection - Format 1
Syntax IF condition THEN
Statement(s)
Else
Statement(s)
ENDIF
Example IF average > 40
Print “Passed”
Else
Print “Failed”
ENDIF
Worked example
Question
A manager pays his staff members a car allowance depending on the size of their
cars. If the engine size is less than or equal to 1300 cc, an allowance of $10 per mile
is paid. If it is greater, an additional Rs 5 per mile is paid. Write a program that will
input number of miles travelled and the engine size. Calculate and print the car
allowance received by the staff members.
Answer
Rem declare variables
Dim No_Miles As Integer
Dim Eng_size As Integer
Dim Allow As Integer
Private Sub Form_Load ( )
Rem input values
No_Miles = InputBox ( “ enter miles travelled” )
Eng_size =InputBox ( “ enter size of engine” )
Rem calculate allowance depending on engine size
If Eng_size <=1300 Then
Allow = 10 * No_Miles
Else
Allow = (10 + 5) * No_Miles
End If
Rem print results
MsgBox “Allowance “ & Allow
End Sub
Dry run the program with the following data and write the expected result
Miles Travelled Size of Engine Is Size <= 1330cc Expected Result
100 1 000
100 1 700
Binary Selection - Format 2
Syntax IF condition 1 THEN
Statement(s)
ElseIf condition 2 THEN
Statement(s)
Else
Statement(s)
ENDIF
Example IF Total Cost > 2 000 THEN
Print “Discount allowed”
ElseIf Total Cost = 2 000 THEN
Print “No Discount”
Print “Your purchase must be greater than 2 000”
Else
Print “No discount”
ENDIF
Note: The Print statements can be used in different ways:
[Link] :Prints the message in Form 1 form
Print :Prints the message on the screen
[Link] :Moves the cursor to a new line then prints the message on the screen
[Link] :Prints the message in the immediate window
[Link] :Prints the message on the printer
Print;Tab(20) :Position the cursor at column 20 then prints the message there
Activity 1
Write a program to input product code, quantity and price. Calculate total cost. A
message is displayed whether to allow a discount or not on the total cost depending on
its amount as shown in the above table. Write a program to perform this task.
Multiple Selection – Using logical operators OR/AND
When a selection is based on one or more conditions, logical operators are used to separate the
conditions
Syntax
OR AND
OR Syntax AND Syntax
IF (condition 1) OR (condition 2) THEN IF (condition 1) AND (condition 2) THEN
Statement(s) Statement(s)
ENDIF ENDIF
NB: You can have any number of conditions combined with OR and AND.
The following tables shows the result from separating 2 conditions using AND and OR
AND OR
Condition 1 Condition 2 Result Condition 1 Condition 2 Result
True True True True True True
True False False True False True
False False False False False False
False True False False True True
This indicates that the instruction following This indicates that after THEN will be executed
THEN will only be executed if both conditions if any of the condition is TRUE or both are TRUE
are TRUE
Activity
The following table shows the amount of tax payable based on the disposable income.
Disposable Income Tax Rate
15000 – 30000 10%
30001 - 50000 20%
> 50000 30%
Write a program to input the disposable income. Calculate and print the tax payable/
NESTED IF...ENDIF
The nested IF... ENDIF structure provides an easy method to code a problem with multiple
conditions insted of using too many OR / AND operators
Syntax IF condition(s) THEN
Statement(s)
ELSEIF condition(s) THEN
Statement(s)
ELSEIF condition(s) THEN
Statement(s)
ElseIf...
ELSE
Statement(s
ENDIF
SELECT...CASE STRUCTURE
In situations where you have too many conditions concatenated by either using logical operators
(OR/AND) or nested IF structure which makes your program longer, then the SELECT...CASE is
another way to do the job.
Syntax Select CASE variable
Case conditions
Statement(s)
Case conditions
Statement(s)
Case Else (match not found for above conditions)
Statement(s)
End Select
Example Dim grade As String
Private Sub Form_Load ( )
grade = InputBox (“Enter exam grade”)
Select Case UCase (grade)
Case “A”
Print “Excellent!”
Case “B”
Print “Can improve!”
Case “A”
Print “Must be more serious!”
End Select
End Sub
SELECTION USING CHECK BOX AND OPTION BUTTON
CHECK BOX
A Check Box provides a way to make choices from a list of items. You can select several, all, or none
of the items at one time.
Check Box Properties
Properties Effect
Caption Set the text to display beside the check box
Font Sets the font type
Value Value can be unchecked (0, vbUnchecked), checked, (1, vbChecked), or
grayed out (2, vbGrayed)
Check Box Event
Click Event obtained when you click on the check box at run-time
OPTION (RADIO) BUTTON
An Option Button allows you to select only one item from a list of options.
Option Button Properties
Properties Effect
Caption Set the text to display beside the option button
Font Sets the font type
Value If a button is selected, its value will be True, otherwise False.
Click Event obtained when you click on the option button.
USE OF FRAME WORK
A Frame groups controls in a form.
Properties Effect
Caption Set the text to display beside the check box
Font Sets the font type
Note:
Frames are useful to regroup control buttons and make the screen more presentable
You must insert frame first and the insert controls inside it.
Create the following form
Frame 1
Text Boxes (1-4)
Label 1 Option Buttons (1-4)
Labels(2-5)
Frames (2-4)
check boxes (1-4)
Command Buttons (1-3)
Set Properties
Form Properties
Use two forms
1st Form
Name :frmMember
Caption :Members Information
nd
2 Form
Name :frmOutput
Caption :Output
Labels properties
Label 1
Name : lblTitle
Autosize: True
Boarder Style: Fixed Single
Caption: Members Information
Font: Ms Sans Serif Regular 18
Alignment: 2-Center
Frame properties
All frames have the property: 1-Fixed Single for Border Style
- MS Sans Serif 12 , Bold for font
Frame 1 Name :frmPersonal
Caption :Personal Information
Frame 2 Name :frmSex
Caption :Sex
Frame 3 Name :frmStat
Caption :Status
Frame 4 Name :frmMeal
Caption :Meal
NB set properties for Labels 2-5 and Text box 1-4
Option button properties
Option button that belong to the same frame have similar names. After giving the first name and
while assigning further ones, Vbasic will prompt you to create a control array. Answer Yes.
Option button 1 Name :optSx
Caption :Male
Value :True
Option button 2 Name :optSx
Caption :Female
Option button 3 Name :optSx
Caption :Single
Value :True
Option button 4 Name :optSx
Caption :Married
Check Boxes properties
Check boxes that belong to the same frame have similar names. After giving the first name and
while assigning further ones, Vbasic will prompt you to create a control array. Answer Yes.
Check Box 1 Name :chkMeal
Caption :Veg
Check Box 2 Name chkMeal
Caption :Fish
Check Box 3 Name chkMeal
Caption :Chicken
Check Box 4 Name : chkMeal
Caption : Meat
NB set properties for Command Buttons (1-3)
CODE THE PROJECT
USE OF CMBO BOX
Combo allows you to select one item from a list.
There are two parts in the combo box:
A text box that contains the title
A list box that contains the list of possible data which you define and from which you have to
pick one data item at run-time.
Combo Box Properties
Properties Effect
Name Sets the name of the combo box
Font Sets the font type
Appearance Sets 3d or flat
List Allows you to give the items in the combo box list. Alternatively you can
use VB ‘With ... End’ with commands to do the same task
Sorted Selects ‘True’ to arrange the items in order, otherwise the items will be
displayed in order given
Style Sets the type of combo box you desire:
0 – dropdown Combo – provides the dropdown list when the down
arrow is selected. You can type an item directly (even if that item is
not in the list) or select an item from the list.
1 – Simple Combo – you are presented with the drop-down list at all
times. You can select an item from the list or type an item, even if it
is not in the list.
2 – Dropdown list – You cannot type an item; you have to select an
item from the list. This style is important when space is an
important element to consider.
Combo Box Event
Click Event obtained when you click or double-click or change the value, or
DbClick position on the combo box.
Change With these methods, you can define the operations to perform
Got focus,etc depending on the choice you have made
Example use of combo box
Design a form (Login) that will request for a password. If the password is correct, another form is
given, otherwise an error message is displayed.
Combo box
Properties
Form Properties
Name :frmLogin
Border Style :1 – Fixed Single
Caption :Login
Startup position:2 – CenterScreen
Label properties
Label 1
Name :lblUser_name
Caption :&User Name
Label 2
Name :lblPassword
Caption :&Password
Combo Box properties
Name :cboUser_name
Style :0 – Dropdown Combo
Text box properties
Name :txt
Border Style :1 - Fixed Single
PasswordChar :* (this will hide the password by displaying *)
Command Button properties
Command button 1
Name :cmdOk
Caption :&Ok
Command button 2
Name :cmdQuit
Caption :&Quit
Main Form
Form properties Label properties
Name :frmMain Name :lblTitle
Border Style :1 – Fixed Single Alignment :Center
Caption :Main Back Style :Transparent
Startup Position :2 – CenterScreen Border Style :1 – Fixed Single
Caption :WELCOME
Font size :24
Command properties
Name :cmdClose
Caption :Close
Fontsize :12
Code
Private Sub Form_Load()
'does the initial setup of the screen and defines what data
'the control box should provide
With cboUser_name
.List(0) = "Administrator"
.List(1) = "nooreen"
.List(2) = "abdal"
End With
End Sub
Private Sub cmdOk_Click()
'clicking on the ok button causes the main menu form to be dispalyed
If (cboUser_name.Text = "Administrator" And [Link] = "roshun") _
Or (cboUser_name.Text = "nooreen" And [Link] = "banu") _
Or (cboUser_name.Text = "abdal" And [Link] = "hassan") Then
'checks for valid password for given user name'
'displays a message if password is incorrect
[Link]
[Link]
Else
Beep
MsgBox "Wrong Password entered", vbCritical, "Error"
'message to state that a wrong password has been entered
End If
End Sub
Private Sub cmdQuit_Click()
'clicking the quit button causes the program to terminate
End
End Sub
Coding – Main Form
Private Sub cmdClose_Click()
End
End Sub
REPETITION – ITERATION
TYPES OF REPETITION
For ...Next
Syntax For counter = initial value Tofinal value
Instructions
Next counter
Instructions
Activity 1
Write a program using For ... Next that will output the integers from 1-5
Solution
Open a form with the following properties
Name :frmoutput
Caption :List Numbers
Type the following program in view code window
Rem program to print intergers from 1 – 5
Private Sub Form_Load ( )
[Link]
For counter = 1 – 5
Print Counter
Next Counter
End Sub
The STEP Clause
The STEP clause is used in For ... Next loops to enable the counter to increase or decrease by a
value which is greater than or less than 1
Activity 1
Write a program to print the even numbers less than 20
Solution
Open a form with the following properties
Name :frmEven
Caption :Even Numbers
Type the following program in view code window
Rem program to print even numbers less than 20
Private Sub Form_Load ( )
[Link]
For counter = 1 – 5
Print Counter
Next Counter
End Sub
Do While ... Loop
Syntax instructions
Initialise counter
Do While condition
Instructions
Increment or decrement counter
Loop
Instructions
NB condition is the number of times you want to execute the program segment.
Activity
Write a program using Do While ... Loop that will output the integers from 1-5
Solution
Open a form with the following properties
Name :frmList
Caption : Numbers
Type the following program in view code window
Rem program to print intergers from 1 – 5
Private Sub Form_Load ( )
[Link]
Counter = 1 – 5
Do While counter < 6
Print Counter
Counter = ounter + 1
Loop
End Sub
Do ... Loop Until
Syntax instructions
Initialise counter
Do While condition
Instructions
Increment or decrement counter
Loop
Instructions
NB condition is the number of times you want to execute the program segment.
Activity
Write a program using Do... Loop Until that will output the integers from 1-5
Solution
Open a form with the following properties
Name :frmListintegers
Caption : Integers
Type the following program in view code window
Rem program toList intergers from 1 – 5
Private Sub Form_Load ( )
[Link]
Counter = 1
Do
Print Counter
Counter = ounter + 1
Loop Until counter > 6
End Sub
Practise Questions
1. Write a program that will input 5 numbers. Calculate and print the total and average of these
numbers.
2. Write a program to input a number. Print the arithmetic table for that number.
3. A quality control inspector tests ovens by setting them to 200o and the measuring the actual
temperature inside the oven five times at ten minute intervals. Write a program to input the five
measurement and then print
a) The average temperature
b) The maximum temperature
c) The minimum temperature
During the test period.
4. Write a program that will enable you to input a password and output a message to inform you
whether it is correct or not. If you enter a wrong password, you will be given the chance to enter
it again up to a maximum of 3 times.
ERRORS IN VB
A bug is an error in the code which can prevent your program from running properly.
Debugging is the process of finding and removing errors.
The debug toolbar and Debug menu provide aids in tracking down logic errors.
Types of error
There are three types of errors:
Syntax errors – is a mistake in the grammar of Visual Basic. Examples include misspelling
keywords (e.g. Lop instead of Loop, forgetting an End If, an opening parenthesis without a
closing parenthesis.)
Run-time errors – causes the program to stop working. Example is trying to store a number that
is too big for a number (e.g. integer values can store up to 32767, if you try to store a number
bigger than this will cause overflow), attempting to divide a number by zero, trying to open a file
which is already open
Logic or semantic errors - error results from a mistake in the logic of your program code.
Examples are using the wrong logical operators (AND/OR) in loop conditions or assigning an
incorrect value to a variable or to use a wrong arithmetic symbol e.g. a + b instead of a - b.
Visual Basic’s Debug toolbar and menu
1. Stepping through code
The Debug toolbar and menu have three options for stepping through a code – executing it
one line at a time.
a) Step into : Runs the current line of code. If this line calls a general procedure this
procedure is entered.
b) step over: Runs the current line, but if this is a general procedure call the procedure is
executed without stepping through its code.
2. Watches
A watch allows you to see the value of a variable or expression as the program runs. As you
step through the code this value is displayed in the Watch window (Immediate window).
The Immediate window lets you do a variety of things such as look at and change the
contents of variables, carry out commands and so on.
3. Using Breakpoints
A breakpoint is a place in the code where the program will temporarily stop.
You can set as many of these as you like.
When the program stops at breakpoint, you can examine the contents of variables and
expression in the Watch window if you have set watches, or you can use Immediate
window.
The Debug Object
Visual Basic supplies the Debug object to help you debug a program directly from the code itself.
It has no properties and only two methods.
The Print method is useful one.
[Link] <variable identifier> in your code displays the contents of a given variable in the
Immediate Window.
Handling runtime errors
You have seen that debugging is about tracking down logic errors which will probably produce
incorrect errors but won’t stop the program running.
Handling errors at run time which will crush the program requires special code.