0% found this document useful (0 votes)
6 views46 pages

Visual Basic Programming 6.0 Lesson 1

The document provides an overview of Visual Basic Programming 6.0, detailing the programming process, types of programming languages, and the Visual Basic environment. It explains the steps to create applications, including designing the graphical user interface, setting properties, and writing code. Additionally, it covers concepts such as event-driven programming, variables, constants, data types, and mathematical operators.

Uploaded by

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

Visual Basic Programming 6.0 Lesson 1

The document provides an overview of Visual Basic Programming 6.0, detailing the programming process, types of programming languages, and the Visual Basic environment. It explains the steps to create applications, including designing the graphical user interface, setting properties, and writing code. Additionally, it covers concepts such as event-driven programming, variables, constants, data types, and mathematical operators.

Uploaded by

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

VISUAL BASIC PROGRAMMING 6.

INTRODUCTION
Program is a set of instructions and commands to a computer to perform a specific task.
Hence programming is the process of writing these set of instructions and commands to a
computer
Commands e.g. open, close, save etc

Programme Language-
Is a language which can be used to write the programmes.Programmes is a written
instruction (codes) in various programming language. Some directly understandable by
the computer and others that require intermediate steps.

A) Low-Level languages

Consist of
i) Machine Language(I’s and O’s)
Natural language of a particular computer which is a collection of very detailed
instruction that control computer internal circuits. It is defined by the hardware design
of that computer. It consists of strings of bits (I’s & O’s) that instruct computer to
perform the most elementary operations.
ii) Assembly Language
Since machine language was tedious to develop, English like-Abbreviation were
developed to present elementary operations of the computer thus to an auto-translator
called Assembler were developed to convert assembly language programs to a
machine language.

B) High-Level languages

These are languages which are compactable with human languages and notations.
Allows programmers to write everyday English-like instructions and mathematic
notations e.g.

i) Basic (Beginners All Purpose Symbolic Instruction Code)

ii) FORTRAN (Formular translator)

iii) COBOL (Common Business Oriented Language)

iv) JAVA (Used for designing Web-Page Object Oriented to run over the Internet)

v) Visual Basic (An Object Oriented version of Basic Programmes)

vi) Pascal (Teaching Programmes)

1
vii) C++ (Object Oriented Languages)

Visual Basic-(data base)


Since assembler are slow working in translation.Compilars were developed to
translate High level languages into machine languages

Computer languages have developed over the years. This development is referred to
as generations
4th Generation Languages
Forpro, Visual Basic, JAVA, Visual, C++ etc

3rd Generation languages


FORTRAN, COBOL and Pascal

2nd Generation languages


Assembly language

1st Generation languages


Machine languages

VISUAL BASIC- 6.0


Is a two part programming process
i) Visual Programming
Entails the creations of the graphical users interface (G.U.I)
It uses images or objects and texts as means of interactions with users. Here you
simply add the build objects into place on the screen and set their properties.

ii) Coding
This is the writing of program instructions using the language Basic

Starting visual Basic


 Start button select
 Program
 Visual Basic 6.0
 From resorting menu
 Select Ms Visual Basic 6.0
 When V.B is loaded New project dialog is displayed where one can choose what
type of V.B program to create
 Standard EXE-Allows programmers to create an executable Programmes which
uses most common V.B features.

The Visual Basic Environment

2
V.B – Contain 3 tabs
New –New projects
Exist – Already created projects
Recent- Opening recently created projects

 Click open after selecting standard EXE to get to Integrates Development


Environment(I.D.E)
Elements on I.D.E
1. Title Bar
It shows the name of the projects applications you are creating
(Project 1 Ms Visual Basic design)

2. Menu Bar
Display the commands for developing over maintaining and executing programs
e.g. File Edit, View, Project, Format, Debug etc

3. Toolbar
Contains icons (Buttons) for commonly used commands in the programming
environment

4. Working Area ( Project 1-Form 1)


Is a window you customize to design an interface of your application. You add
objects (controls), graphics and pictures to the form to create graphical user
interface (G.U.I)

5. Toolbox(General)
Contains controls (objects) used to customize the form.

Examples of controls are:

i) Textbox (txt)
Textbox is a control used for accepting user input can also display text as an
output.

ii) A-Label (lbl)


A-Label display visual text to the user

iii) Commandbutton (cmd)


Commandbutton represent a button the user presses or clicks to initiate a
buttons.

iv) Optionbutton (opt)


Optionbutton is a radio button used in groups where only one choice is true.
v) Frame (frm)
Frame is a control used for grouping other controls

3
vi) Combobox (cbo)
Combobox are controls that provides short list of items

vii) Listbox (lst)


Listbox are control that provides a list of items

viii) Checkbox (chk)


Checkbox to pick an item

ix) Vscrollbar is used for pressing vertical scrollbar

x) Hscrollbar is used for pressing horizontal scrollbar

xi) Image is the control for display images

xii) Line is for drawing lines

xiii) Data is a control for connecting to the Database

xiv) Timer is a control that performs a task that specify the interval

Project Explorer Window

Consist of:
Form 1(frm)
List all the forms and modules in your current
Project 1
Is the collects of file you used to build an applications
Contains three buttons i.e. View code-which shows a window for writing V.B codes.
View object-display the form.
Toggle Folders-It toggles (alternately hides or shows) form folders.
Form Folder contains a list of all the forms in the current object

Properties Window
List the properties settings for the selected forms or objects. A properties is a list
characteristics or attributes of an object e.g. size, colour, caption, name etc
Properties are listed alphabetically or categorized (keep in categorizes) in appearance,
behaviour, font etc

Form Layout window


Allows you to specify the form position on the screen at run time.

Editor Window

Is used for entering an application code

4
CREATING AN APPLICATION
As three major steps.

1. Create the interface.


This involves drawing or placing control on the form

2. Set properties.
This involves setting the properties for each of the objects you’ve created
including the form

3. Writing codes.
A code consists of language statements, Constance and decorations.
To open the code window click on view code button or double click on
view code form or the control for which you want to write the code.

Example 1.

A simple application which displays a line of text

1. Setting forms title bar-Caption property determines what is displayed


in the form title bar. Set caption property to WELCOME
2. Setting form name-The name property uniquely identifies a form or a
control. Set name property to FRMWELCOME
3. Setting the form background color-The back color property specifies a
form or controls background color. Set it to RED
4. Adding a label-Double click on the label control. It is paste on the
form with the word label 1 displayed on it by default. Preposition it by
dragging and also re-size it by using the handlebars.
5. Setting label properties
a) Caption property determines what text the label displays. Set the
property to WELCOME TO V.B
b) Name property-is used to identify the label. Set it to LBLWELCOME
c) Set the back color to yellow.
d) Set fore color to blue-This determines the color in which the text is
displayed
e) Font property-Click on font property. This causes an ellipses button
to appear. When clicked, the font window appears. Specify the name,
style and font size and click on OK button.
6. Running a Programme-This means execution. From the Run menu,
select start or click on start button on the tool bar or press F5 key on
the keyboard.
Execution of Programme

5
From Run menu, select or click the button on the tool bar. This terminates
the Programme execution and places the IDE in design mode.

Saving a project

V.B creates a separate file for each form and assigns it an extension frm
and an additional file for the projects and assigns it an extension vbp.To
save from file menu, select save project,V.B prompts you to save the
forms hence specify its name and click on save button.

EVENT DRIVEN PROGRAMMES

These are applications that execute code in response to event. An event is


an action that can be received by a control.e.g. Action of clicking
command button. The events are triggered by the user of the application.

Event driven Programmes are built to work in the windows environment.

Example 2

A program which prints a line of text on the form after receiving an event.

Print “Welcome to Visual Basic”


Add a new form to your project and let the G.U.I have the following
objects and properties.

Form: Name: - frmprint


Caption: - printing text

Command button: - Name: cmdprint


Caption: - print
For the Programme to print the form, code must be written. If the words
will be printed after pressing print button, then code must be written for
this button, therefore double click on the button and between private sub
and end-sub type prints
Input Box ("Welcome to Visual Basic")

CREATING EVENT PROCEDURES

Code in V.B is divided into smaller blocks or procedures.

An event procedure contains code that is executed when an event occurs.


The event procedure for a control combines the actual control name

6
(specified in the name property), an underscore and the event name e.g.
Private sub cmdprint_click ( )

Example 3

A program that finds area of a rectangle

7
Private Sub cmdcalculate_Click ( )
Dim Length As Integer
Dim Height As Integer
Dim Area As Integer

Length = txtlength.Text
Height = txtheight.Text
Area = Length * Height
txtarea.Text = Area

End Sub

Private Sub cmdexit_Click()


End

MEMORY CONCEPTS

Variable and Constants

A variable is a named location in the computers memory where a value can be


stored for use by the computer. Variable names such as Length, Height and Area
correspond to locations in the computers memory. Every variable has a name,
type, size and the value stored.
Variable name-is any value identifier and cannot be a key word (e.g. Sub, End,
Private, If, Case, Print and must begin with a letter.

-The maximum length of variable is 255 Characters containing only letters,


numbers and underscores thus must not contain spaces, fullstops or dots, commas
or mathematics operators.

- V.B is not case sensitive i.e. LENGTH = length.


- The key word DIM is used to declare a variable.
- The AS key word describes the variable datatype i.e. what
type of information can be stored.
- The statements Length=txtlength.text places into lengths
memory location.
The text in the textbox.txtlength
- Area=Length*Height

8
Multiplies values in length and height in memory location and
assigns the results to Area memory location
- txtarea.text=Area
Get the value in Area memory location and displays it or
output it as text in txtarea.text
- The syntax for declaring a variable is DIM ( variable name
AS(variable datatype)

Data types

- This describes the type and size of information that are


variable stored in the memory
- The different data types are :-
1. Integer- stores odd numbers in the range of -32,000 to 32,000
2. Long – stores big odd numbers in the rate of –
2,147,000,000,000 to 2,147,000,000,000
3. Single- stores small decimal point numbers
4. Double- This stores a big decimal point number
5. Byte- store bits ( 0’s and 1’s)
e.g. 0001
0010
0011
0100
6. Currency- stores monetary value with 4 decimal places
7. Date- stores date and time.
8. String- stores a string of characters between 0 and
2,000,000,000
N.B
When assigning a string to variable, the string must be enclosed in quotes e.g. DIM
message as string = “welcome to Visual Basic”

9. Variant-Stores any type of data above. It is a default data type


for variable that are not declared as specific data type e.g.
means height can be any data type. The data type has a special
symbol type declaration characters e.g. the declaration Dim
sum as integer can be declared as Dim Sum% where the
percentage sign (%) is the integer type declaration character.
Others are:-
@ (At sign) for currency
# (Hash sign) for double
& (Ampersand) for long
! (Exclamation mark) for single
$ (Dollar sign) for string
Dim height %

9
Dim length%
Dim area%

Single line declaration


Dim height%, length%, area%

Constants

Visual basic allows programmers to declare a value, which cannot


change during execution. These values are referred to as
Constants e.g. Pi = 22/7

They are declared with the key word const.The syntax for
declaring a constant is const. (constant name) = (value)

Example 4

10
Private Sub cmdfind_Click ()
Dim area As Double
Dim radius As Double

Const pi = 22 / 7

Radius = txtradius.Text
Area = pi * radius ^ 2
txtarea.Text = area
End Sub

THE DOT NOTATION

This is used when accessing an object property or method.


The dot can be read as “is a member of” and it is read from
right to left e.g.
Txtheight.text means text property is a member of txtheight.
Dot is placed between an object and its property or method
i.e. Object. property
Object. method
NB
The name property uniquely identifies a control or objects on the form. The name is
given a 3 letter prefix that denotes the type of control it is e.g.

Control Prefix
Form frm
Label lbl
Textbox txt
Command button cmd
Combobox cbo
Optionbutton opt
Line lin
Data dat
Adode ado
Frame fra

Private sub cmddisplay_click( )


Txtdisplay.text = “Visual Basic”
Txtdisplay.backcolour = vbyellow
Txtdisplay.forecolour = vbred
Txtdisplay.fontsize = 18

11
Txtdisplay.fontbold = true
Txtdisplay.ToolTipText= “This is a textbox”
Commenting your Code
-A Comment or remark is a short statement written inside the Programme code for the
purpose of explaining what the code is achieving.
-It is not read (executed) by visual basic hence it does not interfere with the Programme
execution. A comment is started with either an apostrophe (‘) or Rem.It is highlighted in
green color.

Mathematical Operators
Performs arithmetic manipulation of numbers. They include:-

i) Additional Operators (+)-Performs addition of numbers


ii) Subtraction Operators (-) - Performs subtraction of one number from another.
It is also used as a negation sign of numbers
iii) Multiplication Operators(*)-Performs multiplication of numbers
iv) Division Operators (/ and \)-the fore slash and back slash performs integer
division. Visual Basic rounds off the number into integer and then performs a
division. If the answer has a fraction part its truncated (decimal is not
seen)e.g.
7\4=1
17\5=3
77\42=8\4=2
The fore slash (/) performs floating-point division i.e. division of numbers that
have decimal parts.
7/4=1.85
17/5=3.4
77/42=1.83333

v) ^ Exponent Operators-raises a number to a given power e.g. 8^2 eight raised


to power 2
vi) Modulus Operators –Perform integer division of 2 numbers and returns the
remainder of the division e.g.
5 mod 2 = 1
5/2=2 Rem 1
8 mod 5 = 3

Logical Operators

Performs logical evaluation of data

i) AND- Returns true if both expressions on either side of it are true and
false if one or both expressions are false.
ii) OR- Returns true if any one of the expressions or either side is true or
both, and false when both expressions are false.

12
iii) XOR- yields true only if one of the expressions on either side of it is
true, but not if both expressions are true. Returns false when both
expressions are false.
iv) NOT-Reverses the logical state of the expression that is in its
immediate right e.g. if a mango is not a fruit, then run.
v) EQV-Compares whether the expression on both sides are equivalent.

Comparison Operators

These are normally used for comparison of values

i) >-Greater than
ii) <-Less than
iii) =-Equals
iv) <>-Not equal
v) >=-Greater than or equal to
vi) <=-Less than or equal to.

NB
Comparison equal sign and assignment equal sign are similar. The assignment
operator always appears to the right of a variable and to the left of the value
that is being assigned to the variable.

13
Operators Precedence

1. ( ) Bracket – Expression enclosed in


2. ^ Exponent
3. _ Negation
4. * Multiplication
5. / Floating division
6. \ Integer
7. mod modulus
8. + Addition
9. – Subtraction
10. Comparison sign-If there are several, they are evaluated from left to right
11. NOT
12. AND
13. OR
14. XOR

i) Evaluate:
2*5^2 + 3 * 5 +7
2*25 +3*5+7
50 +15+7
65+7
= 72
ii) P*r^q+w/x-y (BODMAS)

Concatenation Operators

Concatenation is the joining of two values to form a string


The two operators are:-
i) The addition sign(+)
The plus sign performs the concatenation of 2 strings. It can only join values
which are of string type e.g.
“black” + “board” yields blackboard
black + “board” yields an error
ii) The Ampersand(&)
Can join any two values regardless of whether they are of string type or not e.g.
“black”& “board” yields blackboard

14
black & “board” yields blackboard
1 & 2 yields 12
“1” & “2” yields 12

Private sub cmdok_click ( )


Dim y
Dim x
Y=1
X =7
Print y + x
Print y & x

Y= “1”
X = “7”
Print y + x
Print y & x

End sub

Program which compares two numbers

Private sub cmdok_click ( )

Dim Num 1%, Num 2%


‘Get values from users
Num 1 = inputbox (“Enter first number”)
Num 2 = inputbox (“Enter second number”)
‘Comparing the numbers
If num 1 > num 2 then
Msgbox (“num1”+ “is greater than”+ “num2”)
Else
If num 1 < num2 then
Msgbox (“num 1”+ “is less than” + “num2”)
Else
num 1 = num 2 then
Msgbox (“num 1”+ “is equal to”+ “num2”)
End If
End If
End Sub

15
Program which test whether a year is leap or not and report the number of days
in it.

Private sub cmdtest_click ( )


Dim year as integer
Dim outcome as string
‘Input values of the year
Year = inputbox (“Enter year in 4 digits”)
If year mod 4 = 0 then
Outcome= Msgbox (year & “is a leap year and has 366 days”, vb yesno +vb
Exclamation, “Test leap year”)
Else
If year mod 4 <>0 then
Outcome = Msgbox (year & “is not leap year and has 365 days”,
vbokcancel+vbquestion, “Test leap year”)
End if
End if
End sub

Msgbox Function
Is used to display a message
The syntax is Msgbox (prompt, button + icon, title)

Prompt
Must be supplied when calling the message box and it is the message that appears on
the box

Button + Icon
These are values that specify the kind of buttons and icons to appear on the message
box e.g. for buttons:-
i) Vbok only displays ok button.
ii) VB yesno displays Yes and No button
iii) VB yesnocancel displays Yes, No and Cancel button
iv) VB okcancel displays ok and cancel
v) VB retrycancel displays Retry and Cancel button
vi) VB abortretryignore display Abort, Retry and Ignore button

The icons can be:-


1. Vbexclamation ! -Used to draw the users attention to the message being
displayed
2. Vbquestion ? - Used when a user must make a decision
3. Vbcritical X - Used when a problem occurs
4. Vbinformation i - Used to give the user information about an action

Title

16
It is the text that appears on the title bar of the box. It is optional and if omitted the title of
the application appears

Inputbox ( ) Function
Is used to display a prompt in a dialog box and wait for the user to input text or click a
button.
The syntax is Inputbox (prompt, title, default, xpos, ypos)

Prompt
Is the guiding statement that appears on the dialogbox

Title
Is the text that appears on the title bar of the dialogbox.It is optional and if omitted the
title of the project or application appears in the dialogbox title.

Default
This is a text which appears on the inputbox default.

Xpos and Ypos


The two arguments specify the Vertical and Horizontal placement of the dialogbox on the
screen.
They are expressed on twips and maybe thought as the dialog boxes left and top
properties. By default the upper left point on the screen and has the co-ordinate (0, 0) i.e.
The origin. Twips is the default measurement for forms and most controls whereby
1440twips make 1 inch or 567 twips per cm. Other measurements are points commonly
used for fonts, 72 points per inch; Pixels commonly used with images and represents the
smallest unit of resolution on a screen. Others are inch, mm & cm 120 twips make 1
character.
To change to a specific scale, specify it using the scale mode property.

Help File and content


Are optional but they must appear together if: Help file is the name of help file that is
open should the help button be click context is the name of the help topic.

Assignment
Develop a program which displays the following message box

17
Floppy 3 1/2
A. Drive Is not accessible

Abort Retry Cancel

Solution:
Outcome =Msgbox (“A Drive A is not Accessible”, vbcritical +
vbAbortretrycancel,”Floppy 3 ½”)

OBJECTS, PROPERTIES, EVENTS AND METHODS

Are important concepts in object oriented programming


Object:-is a general name for any control e.g.form, textbox, frame, command button
etc
Property:-are attributes or facts that describe a control e.g. a form has properties such
as Name, caption, height, width, fore color, back color etc
Events: - are actions that can be received by a control. Events can be triggered by the
user (e.g. Click, mouse over, key press, double-click etc), program code or system
(e.g. Form load event, where a form is loaded to the memory.
Method:-is a response of the object to specific event.e.g.move, show, seeks, update
etc

Object Property Event Method


 Dining  Colour,width,height,  Drag,hit,lift,drop,heat  Move,vibrate,rise,
table  Weight,name,material  Break, burn
Bell Colour,name,height Hit,drop,shake,heat Vibrate,ring,melt,
Width Expand, crack
Textbox Name,text,enabled, Change, click Move,setfocus
Width,multiline

Exercise 1.
Write a program which prompts a user for the year and returns whether the year is a
leap year or Not and also the number of days in that year.

CONTROL STRUCTURE:

18
Introduction
Normally statements in a program are executed one after the other in the order in
which they are written. This is called sequential execution, but the execution can be
transferred to another line other than the next. This referred to as transfer of control.
All programs can be written in terms of three structures.
Namely:
1. Sequence structure: Unless directed otherwise, the computer executes VB
statements one after the other in the order in which they are written.
2. Selection structure or decision structure is used to choose among alternative
cause of action
a) IF/THEN
b) IF THEN ELSE
c) SELECT CASE
3. Repetition or Loop or Iteration structures:-Allows the programmer to specify that
an action is to be repeated based on the truth or falsity of some condition
They include:-
Do/while…loop
Do/until…loop
For…next

Exercise 2

A bank wishes to develop a program that will calculate the amount of money on
deposit at the end of 10 years. The bank’s representative should enter the initial
deposit amount and the interest rate. The amount of money on deposit at the end of
each year is calculated and displayed on a listbox.
Using the For/Next loop write a program that computes the compound interest for the
10 years. Use the formulae amount = principle *(I + Rate) ^years.

Private Sub cmdcompute_Click()


Dim amount As Currency
Dim rate As Single
Dim principle As Currency
Dim year As Integer
principle = txtprinciple.Text
rate = txtrate.Text
lstamount.AddItem "year" & vbTab & "Amount on Deposit" & vbTab & Now()
For year = 1 To 10
amount = principle * (1 + rate / 100) ^ year
lstamount.AddItem year & vbTab & amount
Next
End Sub

Exercise 3.

19
Explain the function of the following v.b statement
‘lstdisplay.additem”year”&space$(7)&”Amount on Deposit”

Program design Tools

Introduction to Algorithms
Algorithm is a sequence of steps which result in a plan or strategy on how to go about
in solving a problem. There are three major ways of presenting an algorithm i.e.
pseudocode, flowcharts and Jackson structure Diagrams

PSEUDOCODE
Is an artificial informal language (English like statements) that helps programmers
develop an algorithm that will be converted to a structure program.
e.g. the pseudocode for display student remarks can be written as
-Enter the marks
-If mark is greater than or equal to 60
- Display “passed”
- Otherwise display “Fail”.

In VB this can be written as


Marks=inputbox (“enter Mark”)
If Marks>=60 then
Lbldisplay.caption= “Passed”
Else
Lbldisplay.caption= “Failed”
End If.

FLOW CHART

Is a graphical representation of an algorithm or its portion


They show clearly how control structure operates. The basic elements, which are used
to makeup flow charts, are as follows.

20
SYMBOLS:

Operation Start/Stop

Flow Lines

Decisio
n

4 Connectors
Input/Output

Types of Flow Charts

Sequential flow charts


e.g. Flow charts showing how to find area of a rectangle

Start Input 1, h, find area display Stop

Decision flowcharts (branch)

21
Start

Input num 1, num


2

Is
Num
1<num2
YES Num 1>, NO
Num 2

Display num 1 is
greater than num 2 NO YES
Display num 1 is
equal to num 2

Display num 1 is
less than num 2

Stop

Loop flowcharts
e.g. Flow Chart which prints values x = 0 to 10

22
Start

X=
0

Print X X=X+1

Is No
X
>10
Yes

Stop

IF/THEN SELECTION STRUCTURE

Performs an indicated action only when the condition is true otherwise the ACTION IS
SKIPPED. The IF/THEN/ELSE selection structure allows the Programmes to specify that
a different action is to be performed when the condition is True than when the condition
is False e.g. Kamau owns an umbrella and a jacket. He wears the jacket if it gets cold and
carries an umbrella if it rains, otherwise he carries nothing. This can be written as

If weather = cold THEN


Wear jacket
ELSEIF Weather = Raining THEN
Carry Umbrella
ELSE
Carry nothing
END IF
END IF
Note
The use of the IF statement is subject to the following conditions.
1. Every IF must have THEN and a matchupEND IF
2. You can have many ELSEIF Branches inside an IF statement, but only
one ELSE is allowed.

23
Select Case
Is a multiple selection structure. It is similar in function to the If statement. Its purpose is
to replace the if statement in situations where you would be forced to use too many Elseif
clauses e.g.

Dim weather As string


Weather = txtweather .text
Select case weather
Case” Raining”:
Weather =Msgbox(“Carry Umbrella”)
Case “Cold”:
Weather=Msgbox(“Wear Jacket”)
Case Else:
Weather =Msgbox("Carry Nothing”)
End Select

Example

Private Sub cmdcheck_click


Dim number as integer
Number = txtnumber.text
Select Case number
Case 1:
Number = msgbox(“Moja”)
Case 2:
Number = msgbox(“Mbili”)
Case 3:
Number = msgbox(“Tatu”)
Case 4:
Number = msgbox(“Nne”)
Case 5:
Number = msgbox(“Tano”)
Case 6:
Number = msgbox(“Sita”)
Case 7:
Number = msgbox(“Saba”)
Case 8:
Number = msgbox(“Nane”)
Case 9:
Number = msgbox(“Tisa”)
Case 10:
Number = msgbox(“Kumi”)

24
Case else:
Number = msgbox(“Numbari uliyoandika haijasajiliwa”)
End select

Arrays
A program to determine arrays
Private sub end print _ click ()
Dim MyArray (9) as integer
Print “positions” & space (7) & “Values”
For X = LBound (myARRAY_ to ubound (myArray)
myArray (x) = 2 + x
print x & space $(7) & myArray (x)
next
end sub

CREATING A SOURCE DATABASE.


Click on Add-in
My Access Database – 7.0
From Add-in’s Menu
Select Visual data manager from the windows that appears. Click on
file menu select New.
Then Ms Access
Then Version 7.0 from window that appears right lick on properties and
then select New table.

25
Student table
Add fields, click on it.
Admission number (ADMNO) Primary key
First name
Middle name
Last name
Home address
Date of birth (DOB)
Adm Date
Parent’s ID
Form ID
Gender
Fees balance

Parent’s Table
Parent’s ID (Primary Key)
Father’s Address
Father’s Telephone
Mother’s Names
Mother’s Address
Father’s Profession
Mother’s profession
Adding AdoData control
The Ado Data control needs a form to an existing database control is
connected to a set of record on the target database. This sets of
records constitutes the record set object of the data control depending
on the cursor type property of the data control. The table record can
be added. Modified or deleted on the target database from the visual
Basic form. The custom property is the Name including the path which
the data control is connected. The record source property holds the
name of the table to which the data control is connected.
The cursor type can be:-
i) Ado penkey set – which specifies that the record can be
added, altered or deleted and can once be done on a single
table.
ii) Adopen dynamic – This is dynamic set of record that maybe
used to add, alter or delete records from underline table. This
type of cursor can contain field from one or more table.
iii) Adopenstatic – This type of cursor means the record cannot
be updated.

BOUND CONTROL
Is a data aware control that can provide access to a specific field or
fields in a specific field or fields in a database through the Ado data
control. It is typically bound to Ado data control and data field.

26
Click on a text box e.g Txt First Name and set it data sources property
to Ado student by selecting.

Record set object


Is one of the properties of the Ado data control and refers to the
records that have been pointed to the Ado data control.
Record navigation involves the use of the record set properties and
methods.
These includes:-
1. Move First Method – This method moves the record pointer such
that it points at the first record in a set of records i.e the First record
becomes the current record.
2. Move Next – Move the record pointer such that it points at the next
record from the current record in a set of records. Thus the next
record becomes the current record.
3. Move previous – It moves the records pointer such that it points at
the previous record from the current record in a set of record.
4. Move last method – This method moves the pointer such that it
points at the last record thus becoming the current record.
5. EOF Property – End of File. It specifies whether the record pointer is
pointing beyond the last record or not, when EOF is true – the
record pointer beyond the last pointer which is not a varied record.
This will result in an error being generated if any record access is
altered.
BOF – Beginning of File property specifies whether record pointer is
pointing at a location before the First Record or not. If the property is
true then the pointer is pointing at a location before the first record.

NB: Field property is a property of record set object of the data control.
This property contains the name of all the fields that are in the record
set in order to referred to a particular fields. Its name is given in
bracket and enclosed in quotas offer the record field. This references
content of that field for the current record.

PROGRAM CONTROL STRUCTURES


Program control structures are blocks of statements that determine
how statements are to be executed. In structured programming
languages, there are three control structures namely;
Sequence, selection and iteration (looping)

SEQUENCE
In sequence control structure, the computer needs instructions from a
program file. Starting from the first top lines and proceeding
downwards one-by-one to the end. This is called sequential program
execution.
Start Statement 1 Statement 2 Statement 3

27
SELECTION
In selection control, execution of statements depends on a condition
that returns true or false. The condition must be a Boolean expression
is x > = 20. In such a case the condition is true if x is equal to or
greater than 20. Any other value that is less than 20 is therefore false.
Generally, the four types of selection controls used in most high-level
programming languages are:-
IF ---THEN
IF ---THEN---ELSE
NEST IF
CASE Selection

IF -----THEN
IF ___THEN selection is used if only one option is available. In a school
environment, the administration may decide to reward only those
students who attain a mean mark of 80% and above the rest are
ignored
Pseudo code
If mark > = 80 then
Print”. Give reward”
End if

Flow chart extract

Mark> yes
= 80?

No
Print” Reward”

Stop

In general the format of the IF_____THEN

28
IF < condition> THEN
Statements;
End if
IF _____THEN____ELSE
IF ___THEN ___ ELSE selection. When there are two available options
Example is a player in a football match does a mistake is given a red
card. Otherwise a given yellow card as warning.
Pseudo segment
IF fault = Serious THEN
PRINT “Give red card”
ELSE
Print “ Give yellow card”
END IF
Flow chart extract
start

No Fault = yes
serious

Print “yellow card” Print ”red card”

Stop

In general the format of this construct can be written as:


IF < condition > THEN
Statement;
ELSE
Statement;
END IF

Nested IF selection
Nested IF selection is used where two or more options have to be
considered to make a selection.
Example in Olympics track event Medals are awarded for the first three
athletes.

(a) Position 1 : Gold Medal


(b)Position 2: Silver Medal
(c) Position 3: Bronze Medal

Pseudo code segment

29
IF position = 1 THEN
Medal = “Gold”
ELSE
IF Position = 2 THEN
Medal = “Silver”
ELSE
IF Position = 3 THEN
Medal = “bronze”
ELSE
Medal = “nil”
END IF
END IF
END IF
Flow chart

start

No No No
Position 1? Position 2? Position 3?

Yes Yes Yes

Medal = “Gold” Medal = Medal = “Bronze”


“Silver”

Medal = “Nil”
Print Medal Stop
This general format of the Nested IF
IF <Condition> THEN
Statements
ELSE
IF < condition> THEN
Statements
ELSE
IF<condition> THEN
Statements
ELSE
Statements
END IF
END IF
END IF

CASE Selection

30
CASE selection is an alternative to the nested IF especially where there
are several options to choose from. It is only to reduce many links of
code.
The b……… expression for the case selection can only be expressed
using integers and alphabetic characters only

General format of case;


CASE X IF
Label 1 : Statement 1
Label 2 : Statement 2
Label 3 : Statement 3
:
:
Label ˜: statement ˜
END CASE

Pseudo code
CASE average OF
80……..100: Grade = ‘A’
70………79: Grade = ‘B’
60………69: Grade = ‘C’
50………59: Grade = ‘D’
40………49: Grade = ‘E’

ELSE
Grade = ‘F’
END CASE

Flow chart extract

No No No
Average Average Average Average Average
80-100 70-79 60-69 50-59
40-49

Yes Yes Yes


Grade = A Grade = B Grade =C Grade = D Grade = E

Print Grade Grade = F

Note: The flow char Is not different from that of the Nested IF construct
Iteration (Looping)

31
Iteration also referred to a looping repetition is designed to execute
the same block of code again and again until a certain condition is
fulfilled.
Example, assume that you are writing a program that will use the
same formula to calculate the average marks of three subjects for
each student in a class and that the student records are stored in a
computer file.
To calculate the average score for each student in a class the program
should repeatedly read record by record from the file then se the
formula after each read operation to calculate the average.

The three main looping control are:


The WHILE loop
The REPEAT ____UNTIL loop
The FOR loop
THE WHILE Loop

The ‘WHILE’ loop is used if a condition has to be met before the


statements within the loop are extracted.

Therefore this type of loop allows the statements to be executed zero


or many times.
Examples in banking to withdraw money using an automated teller
machine (ATM) a customer must have a balance in his/her account.

Pseudocode
WHILE balance > 0 Do
Withdraw cash
Update account
END WHILE
Flowchart extract

Balance Yes Withdraw cash


 0? Update account

No
Exit loop
In our cash above,
1. The condition balance > 0 is first tested.
2. If it is true, the account holder is allowed to withdraw cash.
3. The program exits the loop once the balance falls to zero.

REPEAT -------UNTIL LOOP


REPEAT-----UNTIL allow the statements within it to be executed at least
once since the condition is tested at the end of the loop.

32
Example consider the ATM cash withdraw case. If the REPEAT -----
UNTIL is used, then the client will be able to withdraw the cash at least
once since availability of balance is tested at the end of the loop.

Pseudo code
REPEAT
Withdraw cash
Update account
UNTIL balance < 0;
Flow chart extract

Withdraw cash
Update account

Balance
> 0?

Exit loop

The FOR loop


The FOR loop is used in circumstances where execution of the chosen
statements has to be repeated and predetermined number of times.
For example, consider a program that can be used to calculate the sum
of ten numbers provided by the user. The ‘FOR’ loop can be used to
prompt the user to enter the 10 numbers at most ten times. Once the
numbers have been entered, the program calculates and displays the
accumulated sum. The loop is predetermined because it has to be
repeated 10 times as shown by the algorithms below.

Pseudo code
FOR Count = 1 to 10 Do
PRINT “ Enter a number (N)’’
INPUT N
Sum = Sum + N
END FOR

33
Display Sum

Flow chart extract

Lower limit = count + 1

Count = Lower limit


Sum = sum + N

Yes

No

SUM

Explanation
The FOR loop in the problem above function as follows:
1. The loop variable (Count) is first initialized to the lower limit, in
this case a value of 1.
2. The lower limit is then tested against the upper limit whose value
is set to 10.
3. If the lower limit is less than or equal to 10, the program prompts
the user to enter a number N, otherwise the computer exits the
loop.
4. After the last statement in the loop has been executed, the loop
variable count is intermitted by a 1 and stored in the lower limit
i.e. lower limit = count +1.
5. The lower limit is then stored in count and stop (2) is repeated.

The For loop can also be used to count downwards from the upper limit
to the lower limit. For example, in the above against the lower 1 as
follows

34
For Count = 10 DOWN to 1 Do

Therefore the general format of the For loop can be represented using
two sets of algorithms.

1. Pseudocode for ‘For’ loop


For loop variable = lower to upper limit DO;
Upper limit DO
Statement;
END For
2. For loop variable = upper limit to lower limit DO
Statements;
END For

Flowchart extract
A For loop that counts upwards

Lower limit = loop


variable + 1
Loop variable =
lower limit

Statement

No

Condition?

35
yes

A For loop that counts downwards

Lower limit = loop


Loop variable = variable - 1
lower limit

Statements

NO
Condition?

Yes

PROJECT 1
Write a program that can be used to find the roots of a quadratic
expression.
2x2 + b x + c = 0
The formulas to solve the values of x in this expression are:
X1 = -b – Sqr (b2 - 4ac)
2a
X2 = b + Sqr (b2 - 4ac)
-

2a
X = -b i.e if b2 = 4ac = 0 or
2a
b2 = 4ac

36
To crate the project, proceed as follows:
1) Test whether b2 is larger than or equal to 4* a* c. if it is true,
then:

2) Create a new project that would be used to calculate the values


of X, X1 and X2 also called roots of the quadratic equation.

3) In the appropriate event procedure e.g the calculate button, add


the code listed below:

Calculating roots of a quadratic Equation


Dim a,b,c As Integer
Dim Z, X, X1, X2 As Double
Z = (bˆ2 – 4 * a * c)
IF Z > 0 THEN
X1 = (-b + Sqr (d) ) / (2*a)
X2 – X1 = (-b – Sqr (d) ) / (2*a)
ELSE
IF Z = 0 THEN
Print ( “ This quadratic equation is not soluble”)
END IF
END IF
END IF

Explanation
1. The expression bˆ 2 – 4* a * c is first assigned to variable Z

2. Z is the tested if it is greater than 0. if greater, the program


calculates the values of X1, X2, and X, otherwise a message “This
quadratic equation is not soluble” is displayed.

PROJECT 2
The case constructs.
‘Display weekday
Dim D As integer
SELECT CASE D
CASE 0
Print (“Sunday”)
CASE 1
Print (“Monday”)
CASE 2
Print (“Tuesday”)
CASE 3
Print (“Wednesday”)
CASE 4
Print (“Thursday”)

37
CASE 5
Print (“Friday”)
CASE 6
Print (“Saturday”)
CASE ELSE
Msgbox (“Error – That is not a day in the week”)
End .SELECT

PROJECT 3
Write a program using the DO loop that will write numbers between 1
and 20 on the screen then stop.
Solution:
1. Double click the form to display its code window.

2. Add the following code listing between the private sub form –load
and End sub.

X=0
Counter = 0
Do WHILE counter < = 20
X=x+1
Counter = Counter + 1
Print x
Loop
Do While loop
Open the project and replace its code with the code below
Dim x As integer, counter as integer
X=0
Counter = 0
While counter < = 20
X=x+1
Counter = counter + 1
Print x
Wend
The FoR – NEXT Loop
Open the project for and replace the code with the listing below:
Dim Number As Integer, Counter as Integer
Number = 0
FoR Counter = 1 To 20 STEP 2
Number = Number + Counter
Print Number
Next Counter.
FUNCTION CALL
Function Call
Date Z = Date ( )

38
Exp Z = Exp (w)
Sqr Z = Sqr (w)
Log Z = Log (w)
Str Z = Str (w)
Cos Z = Cos (w)
Abs Z = Abs (w)
Ucase Z = Ucase (w)
Int Z = Int (w)
Time Z = Time
Format Z = Format
Description
1. Returns the current date

2. Returns the value of w


3. Returns the square root of w

4. Returns the natural logarithm of w

5. Returns a string whose characteristics are w.

6. Returns the cosine of w

7. Returns the absolute value of w

8. Returns the upper case equivalent of w

9. Returns the largest integer that is algebraically less than w.

10. Returns the current system time.

11. Formats the output to appear as stated.

PROCEDURE
It is a block of code that perform a specific task. They allow a program
to be broken down to small functions unit or modules. In V. B there are
two types of procedures.
Sub procedure and Function procedures

SUB – PROCEDURES
Is a block of V.B Code that appears between sub and End sub.
Sub procedure can either be private or public. A private sub procedure
is not available for use by any module other than module in which it is
contained.
A public sub procedure is available for use by external modules. There
are two types of sub procedures.
i) Event procedures
Is a sub procedure that is invoked (activated) by an event.

39
Cmd checks the name of an event
Sub-procedure is derived from the name of a control that is associated
and the event for which the procedure is to be written.
ii) General procedure
Is a sub procedure i.e not associated with any event hence general sub
procedure has to be invoked (called) by name. Since there is no way in
which the system can invoke them automatically. It can either be
public or private, but generally its better to have public general sub-
procedure since they can be accessed from any module in your
project. The naming route for general procedure are similar to naming
variable.
Example:
Assuming you’ve a general sub-procedure that says goodbye to the
user before application closes then it looks as follows:
General sub-procedure
Public sub-goodbye ( )
Msgbox ( “ goodbye”)
End sub
Exit end Exit

Private sub end Exit


Goodbye
End
End Sub
Assuming that quitting application involves clicking on a button called
end exit, goodbye sub procedure can be invoked as follows:
Private sub end Exit – Click
Goodbye
End
End sub
Private sub end Exit _click
Call goodbye ( )
End
End sub.
FUNCTION PROCEDURES
Is a block of V.b code that appears between function and end.
Function key words. They can either be public or private. The
difference between a function procedure and sub procedure is that
function procedure returns a value i.e it gives feedback to the calling
procedure.

Private Sub cmd.squareoot_click ( )


Dim Number as integer
Dim Square as single
Number = Text Number
Square = Sqr (Number) ‘Function

40
Msgbox (“The Square is “& square procedures)
End sub

Public Function Sqr (Number as integer) as single


Dim Number as integer
.. Sqr = Number ˆ ½
End Function

Parameter:
Is a data value that is passed to a procedure during a call. i.e whe it is
invoked. It is also known as an argument.
The list argument and their data types that are required by the
procedures are always specified in the procedure declaration and held
(that come after the procedure name)

Example
Suppose we need a function that calculate the interest and in a saving
account.
The function will require the amount in the account the interest rate
and the period of time the money has been in the account. The
function then return the interest. The code will look as follows:
Public Function Interest (amount @ Rate #, time #) AsDouble
Interest = Amount x Rate/100 x time
End Function
When the Function is being called all the required parameter must be
specified.
Suppose the interest will be calculated after you click on a button
called cmdinterest and value display on a text box called txtinterest,
then the event procedure will be
Private sub cmdinterest_click ( )
Dim simple interest as Double
Dim Amount as Currency
Dim Rate as Double
Dim Time as Double
Amount = Txtamount.Text
Rate = TxtRate.Text
Time = Txttime/Text
simpleInterest = interest (Amount, Rate, Time)
Txtinterest.Text = simpleInterest
End sub

Variable Scope

41
Is visibility of a variable within a variable. There are two type of
variable scope:
(i) Global – A variable that has been declared in the general
section of a module is known as a Global variable. It can be
read and after by any procedure in the module it is declared
by using the key word e.g public length as integer

(ii) Local Variable – Is variable that has been declared within a


procedure can only be read and after with the procedures

Dim length as integer or static length as integer


Array

Visual Basic Data Structures


A part from using simple data structure such as integer, single,
double etc.
Visual Basic comes with features that allow the programmer to
create complex data structures. These include arrays, records and
files.
Arrays
An Array is a data structure that stores several data items of the same type hence it is called a
homogeneous data structure.
20 30 80 120 200 250
0 1 2 3 4 5

The above table shows how data of type integer is stored in an


array.
The array has cells. The numbers 0 to 5 are called array indices or
subscripts. In Visual Basic, an array starts from cell 0 as shown in
the table.

Declaring an array
To declare an array, use the statement Dim Array Name (n), where
n stands for the number of elements in the array. For example:
Dim Scores (4) is an array that holds five elements.
An elements is an item in an array that can be accessed using the
array variable name and a subscript. For example consider an array
of 5 elements called “Scores to display the 4th element use:
Score 4 = Scores (3)
Print Score 4
The value stored in the variable scored 4 print on the form. To store
a value in an array variable use the statement Array Variable
(index);
For example, to assign a numeric constant 90 to the fifth cell use
Scores (4) = 90
This statement will assign a value 90 in the cell 4 th of the array.

42
NB: If the array was very large and you wish to read or enter values
in it, it would be read or enter values in it, it would be very tedious
entering a value cell by cell i.e
Score (0) = 10
Score (1) = 20
Score (3) = 30
Score (n) = x
To avoid this the FoR …..loop, can be used.
Remember that this loop is used where the number of iterations are
pre-determined hence its suitability for use with arrays.
For example, if you wish to request the user to enter six values in
array named A, the following FoR loop can be used:
Dim A (5) As Integer
Dim Index As Integer
Private Sub Enter Array Values ( )
For index = 0 to 5
A (Index) = Val (TextI. Text)
Next Index
End Sub
Notice that the array is declared this time outside the subroutine in
order to make it a general procedure that can be accessed by other
subroutines.
To Display values of the array on the form the following statement
can be used.
Private Sub-Display Array valves ( )
For index = 0. To 5
Text2. Text = Str (A (Index) )
Next Index
End Sub.

Two dimensional arrays.


A two dimensional array is a data structure in which elements are
arranged in rows and columns. TWO subscripts are used to identify
an item. For example, Dim Score (2,4) means that the element is in
the 3rd row, 5th column. This is because the array was declared to
start from row 0 column 0 same as Dim Score (0 to 2, 0 to 4) To
manipulate elements, stored in a two dimensional array, we use the
nested For------Next loop

Dim iRom As Integer


Dim j Column As Integer
For I Row = 1 to 3
For j column = 1 to 5
Score (i Row, j Column)
Next j column
Next i Row

43
Records
A record comprises of a series of related data items, (fields). They
differ from arrays in that whereas all elements in an array are of the
same data type, data items in a record may differ in type. For
example, when you want to store a students record with the fields
Name, Registration number and date of Birth in a file as a unit, then
you can define a record that would hold all this data items in one
structure. For example the following declaration will create student
details record.:

Type student Details


Name As string 15
Registration Number As String 10
DateofBirth As Date
---------------------------
End Type.
The first line in the type declaration gives the name of the data
structure i.e student Details. The other three lines define fields in
the data type.
Notice that each fields has its own data type and that the string
data types are of fixed length. The last line i.e End type marks the
end marks the end of the record definition. A record is defined in a
standard code module or the general declaration section of a form
module.
It is not possible to access the elements of a data structure directly.
This is why after defining data structure; you must declare a
variable that will be used to hold the records. This is done by
declaring a variable whose type is the data structure.
The general format of such a declaration is:
Dim RecordvariableName As RecordName
For example the studentDetails record can be declared as a variable
using the statement:
Recordvariable.FieldName e.g student.Name

Array of Records
A set of user defined data types can be stored and accessed in arras
too. Consider the record declared below:
Type student
RegistrationNumber As Integer
Name As string * 20
End Type
An array of the student record can then be declared as follows:
Dim StudentArray (39) As student.
This means that the array can store fourty student records. To
access a field in the array of records use the statement:

44
Arrayname (index). FieldName e.g
StudentArray (20). Name will return the name of the student whose
record is in the 20the cell.

Example . s.
Arrays should be declared with Dim in the general declarations
area, or with Redim in a procedure.
Examples of array declarations;
Dim Results (50) As Integer
This creates a one dimensioned array of 51 integers numbered from
0 to 50
Dim Employees (1….200) As string.
This will hold 200 text items, each of any length up to 64k. in this
case the subscripts numbering starts at 1.
Dim Table (10,20) As single.
This array has two dimension when you could think of as 10
columns and 20 rows.
Dim 0 X 0 Grid (3,3,3) As Integer.
It is a three dimension noughts and crosses with 4 layers of 4 rows
and 4 columns.

Arrays and loops


Private sub cmd Results _click ( )
For element = 0 to 9
Total = Total + dataset (element)
Next element
Average = total/10
Msgbox “Total values = “& total &
“Average = “& Average.
End sub.

ARRAYS
Array Contents
Names (0) Fred
Names (1) Jim
Names (2) Sally
Names (3) Dick
Names (4) Karen
Names (5) Jo

45
This array would have been set up with the line:
Dim Names (5) As string
This has 6 elements, numbered 0 to 5
Each can be accessed individually to read or to change its data by
specifying its subscript.
Print Names (2) ‘displays Sally
Names (4) = Katy ‘ replaces Karen with Katy

A two – dimension array may be thought of as a table, with


numbered rows and columns.
0x0 0
0 1 2

0 x

1
This could be the board for noughts
and crosses. 2 0
It would be declared with the
line:
Dim 0 x 0 (2, 2) As string
In the illustration, 0 x 0, (0,0) hold the weekly wages of 20 workers,
and will require a little over 52*20*8 = 8320 bytes, just over 8kb.
Dim Marks (10, 30,25) As Double
This will hold the marks of 10 classes of students, with up to 30 in a
class and 25 assignments per student.
It will need 10*30*25*8 = 60,000 bytes of storage.

46

You might also like