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

Visual Basic Notes Summarised

Vb

Uploaded by

sheilamambon
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)
72 views

Visual Basic Notes Summarised

Vb

Uploaded by

sheilamambon
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/ 102

Student Notes

Visual Programming

Using Visual Basic 6.0

By Robert Keter
Programming in Visual Basic Page 1 of 102 By R. Keter
TABLE OF CONTENTS
TABLE OF CONTENTS ............................................................................................................................ 1
COURSE OUTLINE .................................................................................................................................. 3
What is Visual Programming Language ..................................................................................................... 6
Visual Programming ................................................................................................................................... 6
Visual programming Terminologies ........................................................................................................... 8
Visual Basic Environment ........................................................................................................................ 10
Integrated Development Environment Elements ...................................................................................... 13
Creating visual Environment with objects ................................................................................................ 19
Program Writing ....................................................................................................................................... 20
Operators in Visual Basic ......................................................................................................................... 23
Program Writing ....................................................................................................................................... 26
Error handling in visual basic ................................................................................................................... 31
CLASSES OF DATA TYPES .................................................................................................................. 42
Creating user defined data types ............................................................................................................... 43
THE VISUAL BASIC CONTROL STRUCTURES ................................................................................ 43
Iterative control structure .......................................................................................................................... 53
Visual basic sub-programs ........................................................................................................................ 60
Built–in functions...................................................................................................................................... 61
User defined functions .............................................................................................................................. 63
Procedures ................................................................................................................................................. 68
Types of procedures in visual basic .......................................................................................................... 68
Function and procedure calling ................................................................................................................. 69
Data structures .......................................................................................................................................... 74
Searching arrays ........................................................................................................................................ 83
Files ........................................................................................................................................................... 89
LINKING VISUAL BASIC TO DATABASES....................................................................................... 98

Programming in Visual Basic Page 2 of 102 By R. Keter


COURSE OUTLINE
1. INTRODUCTION TO VISUAL BASIC PROGRAMMING LANGUAGES
Description of V.B
Example of V.P.L
• Visual basic
• Visual c++
• Delphi
Hardware and software constructions for V.P
2. VISUAL ENVIRONMENT
Description of visual environment
Integrated development environment (IDE)
• Visual objects
• Form window
• Properties window
• Immediate window
• Code window
• Others
3. PROGRAM STRUCTURE
Format of Visual Program
Data types
Operators
Variables
4. PROGRAM WRITING Creating an application Compilation
Debugging Testing Execution
5. CONTROL STRUCTURES Types of control structures
Definition
Types:
• Sequence
• Selection
• Iteration / repetition
Implementation of data structures
6. ERROR HANDLING Types of errors

Programming in Visual Basic Page 3 of 102 By R. Keter


- Syntax
- Run time
- Semantics
- Logical
Error handling techniques .
• Writing error handlers
• On error resume
• On error to go
• Error object
• Debugging tools
7. SUB-PROGRAM Meaning of sub-program Types of sub-programs
• Private sub program
• Public sub-program Scope of variables
Local variables Global variables
8. Data structures
• Types of data structures
- Arrays
- Records
- Pointer
- Stacks and queues
- Sets
- Files
• Sort Techniques
- Bubble shell
- Selection
• Search Techniques
- Binary search
- Linear search
9. Linking to databases
- Database controls
- Data control
- Ms data bound controls
- Active data object (ADO)
Programming in Visual Basic Page 4 of 102 By R. Keter
• Reports
• Data reports
10. Emerging Trends In Visual Basic.
• Emerging trends in visual programming
• Challenges of emerging trends in Visual Basic
• Coping with challenges of emerging trends in visual programming.

Programming in Visual Basic Page 5 of 102 By R. Keter


What is Visual Programming Language
Visual programming language is a programming language that uses graphical elements and

figures to develop a program. Visual Programming Language employs techniques to design a

software program in two or more dimensions, and includes graphical elements, text, symbols and

icons within its programming context. Visual programming language is also known as

executable graphics language. Visual programming language enables the development of

software programs by eliminating textual software code with a series of visual graphics elements.

VPL incorporates these graphical elements as the primary context of the language arranged in a

systematic order. The graphics or icons included within a visual program serve as input,

activities, connections and/or output of the program. Visual language has a few types, such as

icon-based languages, diagramming languages and form-based language. Visual languages

should not be confused with GUI-based programming language as they only provide graphical

program authoring services. However, their code/context is completely textual.

Visual Programming
Visual programming is the creation of a computer program by utilizing pictorial elements. Traditionally, a

program is a sequence of text statements used to achieve a certain result or solve some problem.

Programming languages often have particular ways of representing the work to be done thus leading to

complexity. Visual programming attempts to make the creation of programs simpler.

Advantages of visual programming


i. The structure of the visual programming is very simple, particularly as to the executable code.

ii. Visual programming is not only a language but primarily an integrated, interactive

development environment

Programming in Visual Basic Page 6 of 102 By R. Keter


iii. The Visual programming IDE supports rapid application development. It is particularly

easy to develop graphical user interfaces and to connect them to handler functions

provided by the application.

iv. The graphical user interface of the Visual programming IDE provides a naturally

appealing views for the management of the program structure in the large and the

various types of entities.

v. Visual programming provides a comprehensive interactive

Disadvantages of visual programming


i. Programs written in Visual basic cannot, easily, be transferred to other operating systems.

ii. It is impossible to initialize an array of structures in Visual programming.

Features of visual programming


• Allows you to quickly and easily develop a bank of visual controls with sliders, switches and

meters or a complex form for a user to fill out.

• Flexible

• Easily and quickly learned

• Visual programming is a Graphical User Interface (GUI) language. This means that a Visual

programming program will always show something on the screen that the user can interact with.

• Modularization
Instead of thinking of a computer program as a single large collection of code, the good

programmer writes code so that you never need to look at more code than fits on the screen (or

page) at one time.

Examples of visual programming languages


• Visual basic
• Visual C++
• Delphi ( Visual Pascal)
• Visual Foxpro.

Programming in Visual Basic Page 7 of 102 By R. Keter


Visual programming Terminologies
Forms
Are windows that you create for user interface. A form generally has many different controls
placed upon it.
Controls
Are graphical features drawn on forms to allow user interaction, examples are textboxes labels,
scrollbars command buttons e.t.c. Forms and controls are sometimes collectively known as objects.
Properties
Every characteristic of a form or control is specified by a property, examples of properties include
name, caption ,size, colour ,position and content.
Methods
Is a built-in procedure that can be invoked to impart some action to a particular object
e.g print method. Example: Me.print sum ‘displays value held by the variable sum in
the current form.
Event Procedure
Is a code related to some object. This is the code that is executed when a certain event occurs.
General Procedure
Is code not related to objects. This code must be invoked by the application.
Module
It is a collection of general procedures, variable declaration and constant definitions used by the
application.
Application
Is a collection of objects that work together to accomplish something useful? In Vb the application is
called a project. A project could be the management of a video store, calculation of mortgages e.t.c
Object
Objects are the basic run-time units of a class. Once a class is defined, we can create any number of
objects related to the class to access the defined properties and methods.. Each object in Visual Basic is
defined by a class
Class
A class describes the variables, properties, procedures, and events of an object.
For example, the Car is the Class name, and the speed, mileage, and wheels are attributes of the Class
that can be accessed by the Object.

Programming in Visual Basic Page 8 of 102 By R. Keter


Software considerations for visual programming
Ease of Learning
Clearly, the easier that the programming language is to learn, the quicker that programmers become

productive. Java is a lot easier to learn than C++; C is probably even easier. But you learn once and

program for a long time, so that ease of learning is of only limited value.

Ease of Understanding
Most code is written once and read many times usually, to focus on a particular point. Thus, it is important

that the reader quickly grasp the essence of what’s happening.

Speed of Development
If you look at speed of development in the round, you must consider not only how long it takes you to

write code, but also how long it takes you to find a solution to the problem at hand and find the bugs.

Help with Enforcement of Correct Code


The ideal programming language should turn logic errors into syntax errors. A powerful means to this end

is type checking. Most standard languages, such as Java and COBOL, have good type checking. But some

languages have an escape clause.

Supported Platform Environments


By platform environment, I mean not only the operating-system facilities, but also the middleware

facilities, database facilities, and system-management facilities.

Hardware considerations for visual programming


• User friendly
• Compatibility
• Portability

Programming in Visual Basic Page 9 of 102 By R. Keter


Visual Basic Environment
Visual Basic is a programming language and development environment created by Microsoft Corporation.

It is an extension of the BASIC programming language that combines BASIC functions and commands

with visual controls. Visual Basic provides a graphical user interface (GUI) that allows the developer to

drag and drop objects into the program as well as manually write program code.

Visual Basic is an event driven programming language. This simply means that the applications

that are developed using Visual Basic, much like any other windows applications, will act upon

the users actions (event procedures) such as Click, DoubleClick, DragDrop, MouseDown.

Whenever you want the control in your application to respond to an event, you put the instructions in

the appropriate event procedure. Of course the user does not initiate all the events. Sometimes events

are consequence of other events. For example as you start an application the main Form is loaded in

the memory and shows up on the screen. This is a Form_Load event, which simply means that the

Load event procedure is activated on the Form control.

Before you can write programs in VB 6, you need to install Visual Basic 6 compiler on your computer.
You can purchase a copy of Microsoft Visual Basic 6.0 Learning Edition or Microsoft Visual Basic
Professional Edition from Amazon.com, both are vb6 compilers. Besides, you can also buy it from eBay
at Microsoft Visual Basic 6.0 6 Professional PRO MSDN Library Manual Service Pack. If you have
already installed Microsoft Office in your PC or laptop, you can also use the built-in Visual Basic
Application in Excel to start creating Visual Basic programs without having to spend extra cash to buy
the VB6 compiler.
You can also install VB6 on Windows 10 but you need to follow certain steps otherwise the installation
will fail. First, you need to run setup as administrator. Next, you need to use custom installation. Clear
the checkbox for Data Access. If you don't, set up will hang at the end of the installation. Finally, click
next and wait for the installation to complete. For complete instructions, please follow this link Install
VB6 on Windows 10
After installing the vb6 compiler, the icon will appear on your desktop or in your programs

menu.

Programming in Visual Basic Page 10 of 102 By R. Keter


Click on the icon to launch the VB6 compiler. On start up, Visual Basic 6.0 will display the

following dialog box as shown below

You can choose to either start a new project, open an existing project or select a list of recently opened

programs. A project is a collection of files that make up your application. There are various types of

applications that we could create, however, we shall concentrate on creating Standard EXE programs (EXE

means executable). Before you begin, you must think of an application that preferably have commercial,

educational or recreational value. Next, click on the Standard EXE icon to go into the actual Visual Basic 6

programming environment.

When you start a new Visual Basic 6 Standard EXE project, you will be presented with the Visual

Basic 6 Integrated Development Environment (IDE). The Visual Basic 6 Integrated Programming

Environment is shown below. It consists of the toolbox, the form, the project explorer and the

properties window

Programming in Visual Basic Page 11 of 102 By R. Keter


The Integrated Development Environment
IDE is a term commonly used in the programming world to describe the interface and environment that

we use to create our applications. It is called integrated because we can access virtually all of the

development tools that we need from one screen called an interface. The IDE is also commonly referred

to as the design environment, or the program. Programs written in visual basic are done in an Integrated

Development Environment (IDE). The IDE allows a programmer to:

• Create/design a user interface.

• Code the program.

• Set the properties for the controls.

• Run/compile the program.

• Debug the program.

Programming in Visual Basic Page 12 of 102 By R. Keter


Integrated Development Environment Elements
The Visual Basic integrated development environment (IDE) consists of the following elements.

1. Menu Bar
Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View,

Window, and Help menus, menus are provided to access functions specific to programming such as

Project, Format, or Debug.

Context Menus
Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button

on the object you're using. The specific list of shortcuts available from context menus depends on the part

of the environment where you click the right mouse button.

2. Toolbars
Provide quick access to commonly used commands in the programming environment. You

click a button on the toolbar once to carry out the action represented by that button.

3. Toolbox
Provides a set of tools that you use at design time to place controls on a form.

Programming in Visual Basic Page 13 of 102 By R. Keter


Controls in toolbox

Programming in Visual Basic Page 14 of 102 By R. Keter


4. Project Explorer Window
Lists the forms and modules in your current project. A project is the collection of files you use to build an

application.

5. Properties Window
Lists the property settings for the selected form or control. A property is a characteristic of an object,

such as size, caption, or color.

6. Form Layout Window


The Form Layout window allows you to position the forms in your application using a small graphical

representation of the screen.

Programming in Visual Basic Page 15 of 102 By R. Keter


7. Object Browser
Lists objects available for use in your project and gives you a quick way to navigate through your code.

You can use the Object Browser to explore objects in Visual Basic and other applications, see what

methods and properties are available for those objects, and paste code procedures into your application.

8. Form Designer
Serves as a window that you customize to design the interface of your application. You add controls, graphics,

and pictures to a form to create the look you want. Each form in your application has its own form designer.

Programming in Visual Basic Page 16 of 102 By R. Keter


9. Code Editor Window
Serves as an editor for entering application code. A separate code editor window is created for each form

or code module in your application.

Other IDE Elements


Immediate window
The Immediate window is a special window in which you can directly type Visual Basic commands and view

and change variables and control values during a program's execution.

Locals window
The Locals window displays the values and types of all variables that are within the scope of the

currently executing procedure. This window allows you to learn about the lifetime of a variable

as you step through your application because you can see when it is initialized, when it changes,

and when it is destroyed. When a variable comes into scope it will be shown in the window.

Programming in Visual Basic Page 17 of 102 By R. Keter


Watch Window
The Watch Window is similar to the Locals Window, but you specify the variables you want to track. You

can track variables across modules and procedures and keep them in your Watch Window to see their

value no matter where the current line is.

Debug window
The debug window in visual basic is a utility that helps in debugging code. Whenever error

occurs in a project, visual basic compiler displays an error message, pauses the project execution

and highlights the statement which caused the error.

Edit window

Form editor

Programming in Visual Basic Page 18 of 102 By R. Keter


Toolbox Controls with prefix

• Textbox – txt : A control for accepting user input.

• Label – lbl: A control that displays unedited text to the user.

• Command button – cmd : A control which represents a button. The user clicks on it initiate an
action.

• Picturebox – pic : A control that displays images.

• Frame – fra : A control that is used to group objects.

• Checkbox – chk: A control that provides user with a toggle choice.

• Listbox – lst: A control that provides a list of items

• Combobox – cbo : A control that provides a short list of items.

• Data – dat: A control for connecting to a database.

• OLE – ole: A control for interacting other windows applications.

• Shape – shp: A control that is used to draw circles, rectangles.

Creating visual Environment with objects

Visual basic is a Microsoft windows programming language. Programs written in visual basic are

done in an Integrated Development Environment (IDE). The IDE allows a programmer to:

• Create/design a user interface.

• Code the program.

• Set the properties for the controls.

• Run/compile the program.

• Debug the program.

Programming in Visual Basic Page 19 of 102 By R. Keter


Program Writing

Format of a visual program

Option explicit or implicit

Global variables

Procedure or function name with events and optional arguments

Local variables declaration

Statement(s)

End procedure or function

Where:

Option Explicit statement at the top of a code module forces the programmer to declare all

variables that you have used in that module, using Dim or similar.

Option implicit statement at the top of a code module does not force the programmer to declare

all variables that you have used in that module, using Dim or similar.

Global variables are variables that are accessible through the program when it executes.

Procedure or function name with events and optional arguments

Local variables are variables that are accessible within the function or procedures in which they

are declared.

Statements are instructions to be executed

End procedure or function stops execution

Variables

Variables are memory locations that hold values to be used by the program at execution time. It

is a valid identifier.

Programming in Visual Basic Page 20 of 102 By R. Keter


Variable naming conventions (nomenclature)

• Variables cannot be keywords in visual basic.

• Variables must begin with letters.

• The maximum length of variable names is 255 characters.

• Variable names can contain letters, numbers and underscores.

Variables categories

• Static variables

They are those variables that don’t change when the program executes.

• Dynamic variables

They are those variables that change when the program executes.

Types of variables

• Global variables

These are variables that are accessible through the program when it executes.

• Local variables

They are variables that are accessible within the function or procedures in which they are

declared.

The keyword Dim is used to declare dynamic variables in visual basic. The keyword const is

used to declare static variables in visual basic.

Programming in Visual Basic Page 21 of 102 By R. Keter


Integer 2 -32768 to 32768

Byte 1 0 to 255

Currency 8 -922337203685477 to 922337203685477

Date/Time 8 1 January 100 to 31 December 9999


Data Types
Double 8 -1.79769313486232E308 to 1.79769313486232E308
A data type shows the kind information or data a certain variable store.
Long 4 -2147483648 to 2147483648
• Integer: Stores whole numbers ie non-floating numbers.
• Boolean:2 Represents
Boolean trueororFalse
True false values.
• Byte: Stores a byte of information.
• Double: 4Represents Any
Object object
a double type. floating point number.
precision
• Single: Represents a single precision floating point number.
• Strings: Stores
Single 4 -3.40823E38
a series to 1.44012998E-45
of characters.
• Variant: Store’s data types of any type.
• Date and10+
String 0 todate
time.: Store’s 20,000,000,000
and time formats.
• Long: Stores whole numbers with greater magnitudes.
Variant
• Currency: 16Stores monetary
Any value within the range listed above.
values.

Data type Bytes Range

Integer 2 -32768 to 32768

Byte 1 0 to 255

Currency 8 -922337203685477 to 922337203685477

Date/Time 8 1 January 100 to 31 December 9999

Double 8 -1.79769313486232E308 to 1.79769313486232E308

Long 4 -2147483648 to 2147483648

Boolean 2 True or False

Object 4 Any object type.

Single 4 -3.40823E38 to 1.44012998E-45

String 10+ 0 to 20,000,000,000

Variant 16 Any value within the range listed above.

Programming in Visual Basic Page 22 of 102 By R. Keter


Operators in Visual Basic
In visual basic an operator is an object that is capable of manipulating a value or operator. for

example, in "1 + 2", the "1" and "2" are the operands and the plus symbol is the operator.

1. Arithmetical Operators
Operators Description Example Result

+ Add 5+5 10

- Substract 10-5 5

/ Divide 25/5 5

\ Integer Division 20\3 6

* Multiply 5*4 20

^ Exponent (power of) 3^3 27

Mod Remainder of division 20 Mod 6 2

"Rift"&"Valley”
& String concatenation Rift Valley

Programming in Visual Basic Page 23 of 102 By R. Keter


2. Relational Operators

Operators Description Example Result

> Greater than 10>8 True

< Less than 10<8 False

>= Greater than or equal to 20>=10 True

<= Less than or equal to 10<=20 True

<> Not Equal to 5<>4 True

= Equal to 5=7 False

3. Logical Operators

Operators Description

OR Operation will be true if either of the operands is true

AND Operation will be true only if both the operands are true

Visual basic allows programmers to do mathematical operations using various arithmetic


operators.

Vb operator Arithmetic operator Algebraic expression Vb expression


Addition + X+y X+y
Subtraction - a-b x-8
Multiplication * Yb Y*b
Division / u/v u/v
Division(integer) \ None u\v
Exponentiation ^ qp Q^p
Negation - -e -e
Modulus Mod Qmodr qmodr
Programming in Visual Basic Page 24 of 102 By R. Keter
Keywords

Keywords are the reserved words used in programming. Each keyword has fixed meaning

and that cannot be changed by user.

Visual basic expressions


An expression is a series of value elements combined with operators, which yields a new value.

The operators act on the value elements by performing calculations, comparisons, or other

operations.
Order of precedence
These are visual basic arithmetic rules that determine the sequence of evaluating values in a

visual basic expression.

Rules

Use the operators in order of precedence. For operators on the same precedence, evaluate from

left to right in an expression.

Order of precedence Symbol Operator


1 () The value between the brackets
2 ^ The exponentiation
3 - Negative (negative values)
4 */ Multiplication and division
5 \ Integer division
6 Mod Remainder division
7 +- Addition and subtraction
Lastly & String concatenation

Programming in Visual Basic Page 25 of 102 By R. Keter


Program Writing Terminologies
Program
A set of coded instructions that a computer can understand to solve a problem or produce a desired

result. Programs are written either in one of high-level programming languages (such as visual basic,

C, Java) which are easier but execute relatively slowly, or in one of low-level languages (assembly

language or machine language) which are very complex but execute very fast.

Properties
A property procedure is a series of Visual Basic statements that manipulate a custom property on

a module, class, or structure. Property procedures are also known as property accessors.

Objects:

An object is a combination of code and data that can be treated as a unit. An object can be a

piece of an application, like a control or a form. An entire application can also be an object.

Method

In visual basic is a procedure that is executed when an object receives a message. A method is

really the same as a procedure, function, or routine in procedural programming languages.

Events

In computing, an event is an action or occurrence detected by the program that may be handled

by the program. Typically, events are handled synchronously with the program flow, that is,

the program has one or more dedicated places where events are handled, frequently an event

loop.

Program coding

Computer instructions written in a programming language

Programming in Visual Basic Page 26 of 102 By R. Keter


Program compiling

In computer science compiling a program means to decode instructions written in a higher order

language and produces an assembly language program

Program debugging

Program debugging is the routine process of locating and removing computer program bugs,

errors or abnormalities, which is methodically handled by software programmers via debugging

tools. Debugging checks, detects and corrects errors or bugs to allow proper program operation

according to set specifications

Program testing
Program testing is an investigation conducted to provide stakeholders with information about

the quality of the product or service under test. Software testing can also provide an objective,

independent view of the software to allow the business to appreciate and understand the risks of

software implementation. Test techniques include, but are not limited to the process of executing

a program or application with the intent of finding software bugs.

Program execution
Program execution in computer science and software engineering is the process by which a

computer performs the instructions of a computer program. The instructions in the program

trigger sequences of simple actions on the executing machine. Those actions produce effects

according to the semantics of the instructions in the program. Programs for a computer may

execute in a batch process without human interaction, or a user may type commands in an

interactive session of an interpreter.

Programming in Visual Basic Page 27 of 102 By R. Keter


Program deployment

Software deployment is all of the activities that make a software system available for use. The

general deployment process consists of several interrelated activities with possible transitions

between them. These activities can occur at the producer side or at the consumer side or both.

Because every software system is unique, the precise processes or procedures within each

activity can hardly be defined. Therefore, deployment should be interpreted as a general

process that has to be customized according to specific requirements or characteristics.

Testing programs in visual programming


This is a process of running (executing) programs to find errors (bugs). The process of finding

bugs is called debugging as mentioned above. Program testing is part of the procedure which

ensures that the program corresponds with original program specification and that it works in the

intended environment.

Test Plan
These are the stages involved in testing the programs. They include the following.
1. Desk checking
After writing the program the programmer goes through the program on a paper to eliminate any

error that might cause extra work later.

2. Translator system checking


After coding the program is checked using the compiler or translator to detect any syntax error.

The programmer corrects these errors and then resubmits the program to the compiler until the

errors are over.

3. Program run with test data


These are trial runs done with test data that includes all variations and extremes data including

data with errors to ensure that program does not grind to an halt if incorrect data is used.
Programming in Visual Basic Page 28 of 102 By R. Keter
Diagnostic procedures
For complex programs diagnostic procedures are used to find logical errors. A trace routine print

the results at each stage to enable errors detected quickly. If the trace routine is not available, the

programmer can insert instructions in the program to print out intermediate results at key points.

System test with actual data (full-scale) system


Usually new systems are run parallel with existing system for a short period so that the results

are compared and adjustments made.

Test Data
This is the information that is used to test the new system or program. The program tried and

executed at least once every routine through the program and the accuracy of the program is

verified to meet the original design specification.

Categories of test data


Dummy data
This is the data input into a system for trial purposes. Used to test the system for correctness.
Real data (normal data)
This includes the general data for which the system was designed.
Exceptional data
Programs are designed to accept certain range of data. If illegal data is input it should be able to

detect and reject it rather than try to process it to avoid getting wrong results.

Example 1

Write a program that calculates the sum of two integers

Algorithms

• Start
• Enter the integer values.
• Compute the sum the two numbers.
• Produce results
• Stop

Programming in Visual Basic Page 29 of 102 By R. Keter


Flowchart

Start

Enter 2 numbers

Interface

Code
Private Sub cmdcompute_Click()
Dim num1 As Integer
Dim num2 As Integer
Dim sum As Integer
num1 = Val(txtnum1.Text)
num2 = Val(txtnum2.Text)
txtsum.Text = Val(txtnum1.Text) + Val(txtnum2.Text)

End Sub

Programming in Visual Basic Page 30 of 102 By R. Keter


Error handling in visual basic
Error Handling enables programmers to write clearer, more robust, more fault-tolerant programs.

Error handling enables the programmer to attempt to recover (i.e., continue executing) from

infrequent fatal errors rather than letting them occur and suffering the consequences (such as loss

of application data).

Error handling is designed for dealing with synchronous errors such as an attempt to divide by 0

(that occurs as the program executes the divide instruction). Other common examples of

synchronous errors are memory exhaustion, an out-of-bound array index, and arithmetic

overflow. Error handling provides the programmer with a disciplined set of capabilities for

dealing with these types of errors.

Error-handling code is interspersed throughout a program's code. Errors are dealt with the places

in the code where errors are likely to occur. The advantage of this approach is that a programmer

reading the code can see the error handling in the immediate vicinity of the code and determine if

the proper error handling has been implemented.

Debugging - Error Types in Visual Basic 6

• No matter how hard we try, errors do creep into our programs. These errors can be grouped into

three categories:

1. Syntax errors
2. Run-time errors
3. Logic errors

• Syntax errors occur when you mistype a command or leave out an expected phrase or

argument. Visual Basic detects these errors as they occur and even provides help in correcting

them. You cannot run a Visual Basic program until all syntax errors have been corrected.

Programming in Visual Basic Page 31 of 102 By R. Keter


• Run-time errors are usually beyond your program's control. Examples include: when a variable

takes on an unexpected value (divide by zero), when a drive door is left open, or when a file is

not found. Visual Basic allows you to trap such errors and make attempts to correct them.

• Logic errors are the most difficult to find. With logic errors, the program will usually run, but

will produce incorrect or unexpected results. The Visual Basic debugger is an aid in detecting

logic errors.

• Logical errors: This is a human error. A programming mistake that makes a program

code to output results.

• Syntax error: These are errors that violate rules and regulations or the syntax of a language.
• Runtime error: These are the undiscovered error in a program.

Ways to minimize errors

• Design your application carefully. More design time means less debugging time.

• Use comments where applicable to help you remember what you were trying to do.

• Use consistent and meaningful naming conventions for your variables, objects, and procedures.

Run-Time Error Trapping and Handling


Run-time errors are trappable. That is, Visual Basic recognizes an error has occurred and enables

you to trap it and take corrective action. If an error occurs and is not trapped, your program will

usually end in a rather unceremonious manner. Error trapping is enabled with the On Error

statement:

On Error GoTo errlabel

This uses the GoTo statement. Any time a run-time error occurs following this line, program

control is transferred to the line labeled errlabel. Recall a labeled line is simply a line with the

label followed by a colon (:).


Programming in Visual Basic Page 32 of 102 By R. Keter
The best way to explain how to use error trapping is to look at an outline of an example

procedure with error trapping.

Private Sub Example ()


Declare variables……………………..
On Error GoTo HandleErrors
Procedure code
Exit Sub
HandleErrors
Error handling code
End Sub

Once you have set up the variable declarations, constant definitions, and any other procedure

preliminaries, the On Error statement is executed to enable error trapping. Your normal

procedure code follows this statement. The error handling code goes at the end of the procedure,

following the HandleErrors statement label. This is the code that is executed if an error is

encountered anywhere in the Sub procedure. Note you must exit (with Exit Sub) from the code

before reaching the HandleErrors line to avoid execution of the error handling code.

Since the error handling code is in the same procedure where an error occurs, all variables in that

procedure are available for possible corrective action. If at some time in your procedure, you

want to turn off error trapping that is done with the following statement:

On Error GoTo 0
Once a run-time error occurs, we would like to know what the error is and attempt to fix it. This

is done in the error handling code.

Visual Basic offers help in identifying run-time errors. The Err object returns, in its Number

property (Err.Number), the number associated with the current error condition. (The Err function

Programming in Visual Basic Page 33 of 102 By R. Keter


has other useful properties that we won’t cover here - consult on-line help for further

information.) The Error() function takes this error number as its argument and returns a string

description of the error. Consult on-line help for Visual Basic run-time error numbers and their

descriptions.

Once an error has been trapped and some action taken, control must be returned to your

application. That control is returned via the Resume statement. There are three options:

Resume lets you retry the operation that caused the error. That is, control is returned to the line

where the error occurred. This could be dangerous in that, if the error has not been corrected (via

code or by the user), an infinite loop between the error handler and the procedure code may

result.

Resume Next Program control is returned to the line immediately following the line where the

error occurred. Resume label Program control is returned to the line labeled label.

When executing the error handling portion of the code and the end of the procedure is

encountered before a Resume, an error occurs. Likewise, if a Resume is encountered outside of

the error handling portion of the code, an error occurs.

Debugging Visual Basic Programs

These are errors that don’t prevent an application from running, but cause incorrect or

unexpected results. Visual Basic provides an excellent set of debugging tools to aid in this

search. There are no prescribed processes that you can follow to eliminate all logic errors in your

program. The usual approach is to eliminate them as they are discovered.

• The Immediate Window.


• The Locals Window.
• The Watch Window.

Programming in Visual Basic Page 34 of 102 By R. Keter


These windows can be accessed from the View menu (the Immediate Window can be accessed

by pressing Ctrl+G). Or, they can be selected from the Debug Toolbar (accessed using the

Toolbars option under the View menu):

All debugging using the debug windows is done when your application is in break mode. You

can enter break mode by setting breakpoints, pressing Ctrl+Break, or the program will go into

break mode if it encounters an untrapped error or a Stop statement.

Once in break mode, the debug windows and other tools can be used to:
• Determine values of variables
• Set breakpoints
• Set watch variables and expressions
• Manually control the application
• have been called
• Change the values of variables and properties

Debugging
• Unlike other examples, we’ll do this one as a group. It will be used to demonstrate use of

the debugging tools.

• The example simply has a form with a single command button. The button is used to

execute some code. We won’t be real careful about proper naming conventions and such

in this example.

• The code attached to this button’s Click event is a simple loop that evaluates a function at
several values.

Programming in Visual Basic Page 35 of 102 By R. Keter


Private Sub Command1_Click()
Dim X As Integer, Y As Integer
X=0
Do

Y = Fcn(X)

X=X+1

Loop While X <= 20

End Sub
This code begins with an X value of 0 and computes the Y value using the general integer

function Fcn. It then increments X by 1 and repeats the Loop. It continues looping While X is

less than or equal to 20. The function Fcn is computed using:

Function Fcn(X As Integer) As Integer


Fcn = CInt(0.1 * X ^ 2)
End Function
This code doesn’t do much, especially without any output, but it makes a good example for

looking at debugger use. Set up the application and get ready to try debugging.

Using the Debugging Tools

• There are several debugging tools available for use in Visual Basic. Access to these tools is

provided with both menu options and buttons on the Debug toolbar. These tools include

breakpoints, watch points, calls, step into, step over, and step out.

The simplest tool is the use of direct prints to the immediate window.

Programming in Visual Basic Page 36 of 102 By R. Keter


Printing to the Immediate Window:

You can print directly to the immediate window while an application is running. Sometimes, this

is all the debugging you may need. A few carefully placed print statements can sometimes clear

up all logic errors, especially in small applications.

To print to the immediate window, use the Print method:

• Debug.Print [List of variables separated by commas or semi-colons]

• Debug.Print Example:

• Place the following statement in the Command1_Click procedure after the line calling the

general procedure Fcn:

• Debug.Print X; Y and run the application.

• Examine the immediate window. Note how, at each iteration of the loop, the program

prints the value of X and Y. You could use this information to make sure X is

incrementing correctly and that Y values look acceptable.

• Remove the Debug.Print statement.


Breakpoints:

In the above examples, the program ran to completion before we could look at the debug

window. In many applications, we want to stop the application while it is running, examine

variables and then continue running. This can be done with breakpoints.

A breakpoint is a line in the code where you want to stop (temporarily) the execution of the

program that is force the program into break mode. To set a breakpoint, put the cursor in the line

Programming in Visual Basic Page 37 of 102 By R. Keter


of code you want to break on. Then, press <F9> or click the Breakpoint button on the toolbar or

select Toggle Breakpoint from the Debug menu. The line will be highlighted.

When you run your program, Visual Basic will stop when it reaches lines with breakpoints and

allow you to use the immediate window to check variables and expressions. To continue

program operation after a breakpoint, press <F5>, click the Run button on the toolbar, or choose

Start from the Run menu.

You can also change variable values using the immediate window. Simply type a valid Basic

expression. This can sometimes be dangerous, though, as it may change program operation

completely.

Breakpoint Example:

• Set a breakpoint on the X = X + 1 line in the sample program. Run the program.

• When the program stops, display the immediate window and type the following line:

• Print X;Y

• The values of these two variables will appear in the debug window. You can use a

question mark (?) as shorthand for the command Print, if you’d like. Restart the

application. Print the new variable values.

• Try other breakpoints if you have time. Once done, all breakpoints can be cleared by

Ctrl+Shift+<F9> or by choosing Clear All Breakpoints from the Debug menu. Individual

breakpoints can be toggled using <F9> or the Breakpoint button on the toolbar.

Viewing Variables in the Locals Window:

Programming in Visual Basic Page 38 of 102 By R. Keter


The locals window shows the value of any variables within the scope of the current procedure.

As execution switches from procedure to procedure, the contents of this window changes to

reflect only the variables applicable to the current procedure. Repeat the above example and

notice the values of X and Y also appear in the locals window.

Watch Expressions:

The Add Watch option on the Debug menu allows you to establish watch expressions for your

application. Watch expressions can be variable values or logical expressions you want to view or

test. Values of watch expressions are displayed in the watch window.

In break mode, you can use the Quick Watch button on the toolbar to add watch expressions you

need. Simply put the cursor on the variable or expression you want to add to the watch list and

click the Quick Watch button.

Watch expressions can be edited using the Edit Watch option on the Debug menu.

Watch Expression Example:


• Set a breakpoint at the X = X + 1 line in the example.

• Set a watch expression for the variable X. Run the application. Notice X appears in the

watch window. Every time you re-start the application, the value of X changes.

• At some point in the debug procedure, add a quick watch on Y. Notice it is now in the

watch window.

• Clear the breakpoint. Add a watch on the expression: X = Y. Set Watch Type to ‘Break

When Value Is True.’ Run the application. Notice it goes into break mode and displays

the watch window whenever X = Y. Delete this last watch expression.

Programming in Visual Basic Page 39 of 102 By R. Keter


Call Stack:

Selecting the Call Stack button from the toolbar (or pressing Ctrl+L or selecting Call Stack from

the View menu) will display all active procedures, that is those that have not been exited.

Call Stack helps you unravel situations with nested procedure calls to give you some idea of

where you are in the application.

Call Stack Example:


• Set a breakpoint on the Fcn = Cint() line in the general function procedure. Run the

application. It will break at this line.

• Press the Call Stack button. It will indicate you are currently in the Fcn procedure which

was called from the Command1_Click procedure. Clear the breakpoint.

Single Stepping (Step Into):

While at a breakpoint, you may execute your program one line at a time by pressing <F8>,

choosing the Step Into option in the Debug menu, or by clicking the Step Into button on the

toolbar.

This process is single stepping. It allows you to watch how variables change (in the locals

window) or how your form changes, one step at a time.

You may step through several lines at a time by using Run To Cursor option. With this option,

click on a line below your current point of execution. Then press Ctrl+<F8> (or choose Run To

Cursor in the Debug menu). the program will run through every line up to the cursor location,

then stop.
Programming in Visual Basic Page 40 of 102 By R. Keter
Step into Example:

• Set a breakpoint on the Do line in the example. Run the application.

• When the program breaks, use the Step Into button to single step through the program.

• At some point, put the cursor on the Loop While line. Try the Run To Cursor option

(press Ctrl+<F8>).

Procedure Stepping (Step Over):

While single stepping your program, if you come to a procedure call you know functions

properly, you can perform procedure stepping. This simply executes the entire procedure at once,

rather than one step at a time.

To move through a procedure in this manner, press Shift+<F8>, choose Step Over from the

Debug menu, or press the Step Over button on the toolbar.

Step over Example:

• Run the previous example. Single step through it a couple of times.

• One time through, when you are at the line calling the Fcn function, press the Step over

button. Notice how the program did not single step through the function as it did

previously.

Function Exit (Step Out):

While stepping through your program, if you wish to complete the execution of a function you

are in, without stepping through it line-by-line, choose the Step Out option. The function will be

completed and you will be returned to the procedure accessing that function.

Programming in Visual Basic Page 41 of 102 By R. Keter


To perform this step out, press Ctrl+Shift+<F8>, choose Step Out from the Debug menu, or

press the Step Out button on the toolbar. Try this on the previous example.

CLASSES OF DATA TYPES

1. Numeric data types


These are those data types that will store numbers or numeric values. They are computed

mathematically.

• Integers – store numbers.


• Byte – true or false values between 0 and 255.
• Real (double) – store 8 bytes of numeric data.
• Currency – stores monetary values.
• Date and time – store and time format.
• Single – store 4 bytes of numeric data.
• Long – stores 4 bytes of numeric data.
• Decimal – stores 12 bytes of numeric data.

2. Character data types


They are data types that stores characters or strings of characters.

• String – fixed length. Stores 1 to 65,400 characters.


• String – variable length. Stores 0 to 2 billion characters.
• Date – January 1,100 to December 9999
• Boolean – stores true or false values.
• Object – stores any embedded object.
• Variant – numeric. Any value as large as double.
• Variant – text. Same as variable length.

3. Boolean data types


Stores Boolean data types. Boolean is represented by either the keyword true or false or non-zero

or zero value. Boolean are stored in two bytes and have no type declaration character.

4. User defined data types


Visual basic lets the user create his own data type. This is done when you work with mixed data

types.

Programming in Visual Basic Page 42 of 102 By R. Keter


Creating user defined data types
When creating user defined data types use the key word “Type” statement in declaration section

of the form. Declare variables associated with the new data types.

Example 1
Private type employee
Name as string

Dateofbirth as date
Hiredate as date
Salary as currency
Gender as string
End type

THE VISUAL BASIC CONTROL STRUCTURES


A control structure regulates the flow of a visual basic program, given a condition. Determine the

output depending on the conditions used in the program. It performs an indicated action only

when the condition is false or true.

In its simplest sense, it is a block of code. More specifically, control structures are blocks of

code that dictate the flow of control. In other words, a control structure is a container for a series

of function calls, instructions and statements. One or more set of instructions, statements or

groups of statements in a programming language which determines the sequence of execution of

other instructions or statements.

Importance of control structures


i. Are very useful in writing code that gives flexibility to the programmer.

ii. Can be used to manipulate data by using logic to specify what should be done when

a user tries to change or modify the data.

iii. Gives power to the programmer because the programmer can specify when a

situation occurs, the function should do this or that.

Programming in Visual Basic Page 43 of 102 By R. Keter


Types of control structures

Selection

The selection control structure allows one set of statements to be executed if a condition is true

and another set of actions to be executed if a condition is false.

Iteration
These are control structures that repeat statements until a given condition turns true of false for

example while/wend, do/until, do/loop while, for/next, do/loop until.

Sequence
A control structure that executes statements in a program procedurally; one after another.

If/then selection control structure

This is a control structure that is used to choose among alternative action to take.

Example 1
Determining the age of students in a class
Interface

Enter the age

Message

Display the age

Pseudo code/Algorithms

Declare the variables i.e. age and message

Initialize variable age

If age is greater than or equal to 18 then


Display “you are a grown up. Learn to be responsible.”
End if
Programming in Visual Basic Page 44 of 102 By R. Keter
Code

Private sub cmddisplay_click()

Dim age as integer

Dim message as string

Age=value(txtage.text)

If txtage.text>=18 then

Txtmessage.text=”You are a grown up. Learn to be responsible”

End if

End sub

Flowchart
Start

Display the message


If age>=18

Stop

The above flowchart represents if/then selection control structure. It illustrates a single selection

control structure. It performs the indicated action only if the condition is true otherwise it is

aborted.

If/then/else selection control structure

The if/then/else control structure allows a programmer to specify that a different action can be

performed when the condition is true. It tsts for true statements in a program.

Programming in Visual Basic Page 45 of 102 By R. Keter


Example 1

A student sat for a DIT II exam an d score the below marks;

• SAD= 70

• PI= 60

• PII= 80

• Maths= 40

Required:

Create a visual basic program that calculates the average mark. Use the average mark and assign

the student the grade according to the grading system below

Key to grading system:

A = 80 to 100

B =70 to 79

C =60 to 69

D =50 to 59

E =40 to 49

F =0 to 39

Interface

Sad

PI

PII

Maths

Average

Grade

Calculate

Programming in Visual Basic Page 46 of 102 By R. Keter


Pseudo code/algorithms

Declare variables

Initialize the variable that we input

Calculate the average

If average is greater than or equal to 80 then

Display “A”

Else if average is greater than or equal to 70 then

Display “B”

Else if average is greater than or equal to 60 then

Display “C”

Else if average is greater than or equal to 50 then

Display “D”

Else if average is greater than or equal to 40 then

Display “E”

Else if average is less than 40 then

Display “F”

Code

Private sub cmdcalculate_click ()

Dim SAD, PI, PII, maths as integer

Dim average as single

Dim grade as string

SAD=val(txtsad.text)

PI=val(txtpi.text)

PII=val(txtpii.text)

Programming in Visual Basic Page 47 of 102 By R. Keter


maths=val(txtmaths.text)

txtaverage.text= val(txtsad.text)+ val(txtpi.text)+ val(txtpii.text)+ val(txtmaths.text)/4

if txtaverage.text>=80 then

txtgrade.text=”A”

Else if txtaverage.text>=70 then

Txtgrade.text=”B”

Else if txtaverage.text>=60 then

Txtgrade.text=”C”

Else if txtaverage.text>=50 then

Txtgrade.text=”D”

Else if txtaverage.text>=40 then

Txtgrade.text=”E”

Else if txtaverage.text<40 then

Txtgrade.text=”F”

End if

End sub

Select case selection control structure

This is a control structure that allows programmers to enter multiple information in a program.

It can be used with multiple conditional statements. Format

Select case (expression)

Case value 1

Block of statements

Case value 2

Programming in Visual Basic Page 48 of 102 By R. Keter


Block of statements

Case else

Block of statements

End select
Example 1

Determining the grade of an exam in a class.

Marks
Marks

Grade

Display

Algorithms

Declare the variable marks and grade

Initialize the variables marks and grade

Select case marks

Case is 80 to 100

Display “Distinction”

Case is 70 to 79

Display “Credit”

Case is 60 to 69

Display “Pass”

Case is 50 to 59
Programming in Visual Basic Page 49 of 102 By R. Keter
Display “Referred”

Case is 40 to 49

Display “Fail”

Case else

Display “Repeat the course”

End select

Visual basic code

Private sub cmddisplay_click()

Dim marks as integer

Dim grade as string

Marks=val(txtgrade.text)

Select case txtmarks.text

Case is 80 to 100

Txtgrade.text=”Distinction”

Case is 70 to 79

Txtgrade.text=”Credit”

Case is 60 to 69

Txtgrade.text=”Pass”

Case is 50 to 59

Txtgrade.text=”Referred”

Case is 40 to 49

Txtgrade.text=”Fail”

Case is 8 to 39

Txtgrade.text=”Repeat”

Programming in Visual Basic Page 50 of 102 By R. Keter


End select

End sub

Note: the data type specified in the expression must match that of case values

Switch selection control structure

This is a control structure that is related to if/then/else control structure. Each argument passed

to switch control structure is either a condition or a value. If a condition is true the value

associated with the condition is returned.

Example 1

A student sat for a DIT II exam an d score the below marks;

• SAD= 70

• PI= 60

• PII= 80

• Maths= 40

Required:

Create a visual basic program that calculates the average mark. Use the average mark and assign

the student the grade according to the grading system below

Key to grading system:

A = 80 to 100

B =70 to 79

C =60 to 69

D =50 to 59

E =40 to 49

F =0 to 39

Programming in Visual Basic Page 51 of 102 By R. Keter


Interface

Sad

PI

PII

Maths

Average

Grade

Calculate

Code

Private sub cmdcalculate_click ()

Dim SAD, PI, PII, maths as integer

Dim average as single

Dim grade as string

SAD=val(txtsad.text)

PI=val(txtpi.text)

PII=val(txtpii.text)

maths=val(txtmaths.text)

txtaverage.text= val(txtsad.text)+ val(txtpi.text)+ val(txtpii.text)+

val(txtmaths.text)/4 txtgrade.text=switch(txtaverage.text>=80,”A”

txtaverage.text>=70,”B”

txtaverage.text>=60,”C”

txtaverage.text>=50,”D”

Programming in Visual Basic Page 52 of 102 By R. Keter


Iterative control structure

While/wend repetition control structure

This is a repetition control structure that allows programmer to specify that an action is to be

repeated based on a true or false condition. The condition given may be true or false. If the

condition is false the action stops being executed, but if the condition is true the statements will

be repeated until the condition turns false.

Example 1

Printing numbers from 1 to 1000

Display

Visual basic Code

Private sub cmddisplay_click()

Dim x as integer

X=2

While x<=1000

Print x

Programming in Visual Basic Page 53 of 102 By R. Keter


X=x*2

Wend

End sub

Do until/loop repetition control structure

The Do until loop repetition control structure repeats until a condition turns false. The statements in

the body of a loop are repeatedly executed as long as the loop continuation evaluates to false.

Example 1

Printing numbers between 1 and 10

Display

Visual basic Code

Private sub cmddisplay_click()

Dim x as integer

X=1

Do until x<=10

Print x

X=x+1

Loop

End sub

Programming in Visual Basic Page 54 of 102 By R. Keter


The For/next repetition control structure

It handles the details of counter controlled repetition. When a program starts executing counter

variable is initialized to a certain value. The condition is tested by visual basic.

The keywords to is used specify the range of values to be printed. The keyword step is also used

to specify the increment operator (value). That is how much will be added to variable counter

each time the for/next body executes.

If the keywords Step and to are omitted, the increment value defaults to 1. Always initialize the

control variable to certain value.

Example 1

Printing numbers between 1 and 10

Display

Visual basic Code

Private sub cmddisplay_click()

Dim x as integer

For x=1 to 100 step 2

Print x

Next x

End sub

Components of typical for/next loop

e.g.

Programming in Visual Basic Page 55 of 102 By R. Keter


For x= 2 to 10 step 2

• For= keyword in visual basic

• x= control variable name

• 2= initial value

• To=keyword to specify the range

• 10=final value for the control variable

• Step= keyword to specify the increment value

• 2=increment value in control variable

Examples using for/next loop

• Varying the variable control between 1 and 100

For a=1 to 100 step 1

• Varying the variable control from 100 and

1 For b=100 to 1 step -1

• Varying the variable control between 7 and 77

For c=7 to 77 step 7

• Varying the variable control in the following sequence 99,88,77,66,55,44,33,22,11and

0 For d= 99 to 0 step 11

Example 1

Calculating the sum of numbers between 1 and 10 using for/next loop

Display

Visual basic Code

Private sub cmddisplay_click ()

Programming in Visual Basic Page 56 of 102 By R. Keter


Dim x as integer

X=1

Sum=0

For x=1 to 1
Print x

Sum=sum+x

Next x

End sub

Do/loop while repetition control structure

This is similar to do while/loop control structure. The condition is tested at the beginning of the

loop before the body of the loop is performed.

Do/loop while control structure tests the condition after the loop body is performed. When the

loop terminates, execution continues with the statement after the loop while clause. Flow chart

Start

Action

x<=10 True

False
Stop

Programming in Visual Basic Page 57 of 102 By R. Keter


Example 1

Display

Code
Private sub cmdprint_click()
Dim x as integer
X=1
Do
Print x
X=x+1
Loop while x<=10
End sub

Do/loop until repetition control structure


This is similar to do until/loop control structure. In do until/loop continuation the condition is

tested at the beginning of the loop. In do/loop until the body of the loop is performed first before

the condition is tested.

Start

Action

x<=10 True

Programming in Visual Basic Page 58 of 102 By R. Keter


Code

Private sub cmdprint_click()

Dim x as integer

X=1

Do

Print x

X=x+1

Loop until x<=10

End sub
Exiting Do and For statements

The exit Do and For statements alter the flow of the control structure. The exit Do when used in

do/until loop, do/while loop, do loop/while and do until/loop loops causes an immediate exit

from the control structure.

Example 1

Display

Code

Private sub cmdprint_click()

Dim x as integer

X=1

Programming in Visual Basic Page 59 of 102 By R. Keter


Do

If x=50 then

Exit do

End if
Print x

X=x+1

Loop until x>=100

End sub

Visual basic sub-programs

Refers to any set of statements forming part of the program used to perform a specific action.

The are procedures, modules or parts within the program that are used to carry out a specific task

before passing control to the main program.

A properly constructed subprogram should be self-contained perform defined operation on a well

defined data and have an internal structure independent of the program in which it’s contained.

Types of sub-programs in visual basic


• Functions

• Procedures

A function is any normal procedure but it is used to accept certain inputs and pass them to main

program to finish execution. It is used to pass or return a value which will be used to do a certain

operation. There are two types of function in visual basic:

• Built-in functions

• User defined functions

Programming in Visual Basic Page 60 of 102 By R. Keter


Built–in functions

Msgbox() functions

The objective of the Msgbox function is to produce a pop-up message box and prompts the user to

enter or click on a command button before he/she can continue.

Format

Message=Msgbox (prompt, stylevalue, title)

• Prompt – will display the message in a message box.

• Style value – determine the type of command button will appear on the message box.

Example

Message=Msgbox (“click to proceed”1,”gretings”)


Style values in Msgbox function
-

Style Value NAMED CONSTANT BUTTON DISPLAYEED

0 VbOk Ok only

1 VbOkCancel Ok and Cancel

2 VbAbortRetryIgnore Abort, Retry and Ignore

3 VbYesNoCancel Yes, No, Cancel

4 VbYesNo Yes, No

5 Vbretycancel Retry, Cancel

Programming in Visual Basic Page 61 of 102 By R. Keter


Icons Displayed In Msgbox () Function

Style Value Text Displayed Icon

16 Stop sign

32 Question mark

48 Exclamation point

64 Information icon

Input box function

The input box function is used to display a message box whwre the user can enter a value

or message in form of text.

Format

Message=inputbox (prompt, title, default text, x-position, y-position)

Prompt – the message normally displayed as a question.

Title – the title of the inputbox function.

Default text – a text that appears in the inputbox field where the users can use it as his or her

intended input or information he wishes to key in.

X and y position – indicate the coordinates of inputbox.

Programming in Visual Basic Page 62 of 102 By R. Keter


Example 1

Total

Add

Private sub cmdadd_click()

Dim total as integer

Dim x, y as integer

X=inputbox (“enter the value of x”)

Y=inputbox (“enter the value of y”)

Txttotal.text=x+y

End sub

User defined functions

These are those functions that user/programmer creates to perform a certain operation.
Format

Public function functionname (arg as datatype………….) as datatype

Private function functionname (arg as datatype………..) as datatype

Public indicates that the function is applicable is to the whole program and private indicates that

the function applicable to certain modules, statement or procedures only. User defined function

Programming in Visual Basic Page 63 of 102 By R. Keter


can be created with add procedure dialog box. They can also be created in the code window by

typing directly into it

Example 1

Write a visual basic function using a function to calculate the grade of student based on average

mark.

Interface

Visual basic code

Public Function grade(marks As Variant) As Variant

Select Case txtmark.Text

Case 80 To 100

txtgrade.Text = "DISTINCTION"

Case 70 To 79

txtgrade.Text = "CREDIT"

Case 60 To 69

txtgrade.Text = "PASS"

Programming in Visual Basic Page 64 of 102 By R. Keter


Case 50 To 59

txtgrade.Text = "REFFERED"
Case 40 To 49

txtgrade.Text = "FAIL"

Case 0 To 39

txtgrade.Text = "REPEAT"

End Select

End Function

Private Sub cmddisplay_Click()

Dim remarks As Variant

Dim mark As Variant

mark = Val(txtmark.Text)

remarks = grade(marks)

End Sub

Example 2

Using a visual basic function calculate the area of a circle given:

Pi=3.142

Radius=14cm

Solution

Interface

Programming in Visual Basic Page 65 of 102 By R. Keter


Visual basic Code

Public Function area(r As Variant) As Variant

Const pi = 3.142

Area = pi * r * r

End Function

Private Sub cmdcompute_Click()

Dim radius As Variant

Radius = Val(txtradius.Text)

Dim areas As Variant

Areas = area(radius)

MsgBox ("The area is:" & areas)

End Sub
Example 3

Write a visual basic function that will calculate and display interest in textbox given:
Amount =Kshs.10, 000
Interest rate = 10%
Period = 2 years

Solution

Programming in Visual Basic Page 66 of 102 By R. Keter


Visual basic code

Public Function interest (p As Variant, r As Variant, y As Variant) As Variant

Interest = p * r * y / 100

End Function

Private Sub cmdcalculate_Click()

Dim amount As Variant

Dim principle As Variant

Dim rate As Variant

Dim years As Variant

Principle = Val(txtprinciple.Text)

Rate = Val(txtrate.Text)

Years = Val(txtyears.Text)

Amount = interest(principle, rate, years)

MsgBox ("The Future Value is: " & amount)

End Sub

Assignment to the students


• Using a function write a program that prints numbers from 10 to 0 but when it goes

below zero it exits from executing.

• Write a visual basic program that accepts any three integers and then determines the

highest number among them. Use a function.

• Write a visual basic program that accepts any three integers. Let the program divide

the integers by numbers of integers entered. If it attempts to divide by zero exit the

execution.

Programming in Visual Basic Page 67 of 102 By R. Keter


Procedures

A procedure is a predefined function used to solve a problem in a project.

Types of procedures in visual basic

1. Event procedures

These are procedures used to design programs that respond to events. For example
Private Sub cmdcompute_Click()

Block of statements

End Sub

2. General procedures

These are procedures that are used to access any statement in a program. For example
Const pi=3.142

Rate=10%

3. Sub procedures

These are sub-routines which are logically accessed by programs in projects. They are

local to the main program for example:

Private Sub cmdcompute_Click ()

Block of statements

End Sub

Private sub calculate

(arguments) Block of statements

End sub

Programming in Visual Basic Page 68 of 102 By R. Keter


4. Function procedures

A function returns a value to the calling function or statements for example:


Private Function area (length as integer, width as integer) as integer

Block of statements

End Function

Function and procedure calling

A function or procedure is called tom perform a certain operation. It then returns a value to the

calling (main program) function statement or procedure.

A function return value is specified in the body of the program by assigning a value to the

function procedure name. Control then returns to the calling statement.

Call-by-value and call-by-reference

With call-by-reference the caller gives the called procedure or function the ability to directly

access data and modify data if he called procedure of function so wishes.

When an argument is called by value a copy of the of arguments’ value is passed to the calling

procedure. Arguments passed by value use keyword Byval or by enclosing the arguments in

parenthesis (). The arguments passed by references use the keyword Byref. For example:

Function interest (Byval x as integer as integer) as integer

Function interest (Byref x as integer as integer) as integer

Parameter passing

Parameters are those variables that are used to hold data to be passed to the calling statement or

procedure. The process of transferring these parameters is called parameter passing. Arguments

are real or actual values passed to calling statement or procedure.

Programming in Visual Basic Page 69 of 102 By R. Keter


Types of parameters
• Formal parameters

These are labeled memory blank areas that are to be used to store values to be used

during execution. They are identifiers rather than reserved words.

• Actual parameters

These are variables that replace the formal parameters when the procedure or function is

called. They are given the actual parameter list of procedure call.

Classes of parameters

• Value parameters

Used to supply information to the procedure but they cannot be used to get information

out of a procedure. Value parameters are declared by including their names and the

corresponding datatype within a procedure header.

• Variable parameter

Used in applications where information must be transferred in both directions between

the procedure and procedure reference. When the procedure containing a variable

parameter is accessed the actual parameter in the procedure reference is substituted by the

formal parameter within the procedure itself.

Recursive Functions
A recursive function/procedure calls itself either directly or indirectly through another call.

Functions call other functions or procedures to return values. It is equally possible for a function

to call itself.

A recursive function or procedure is called to solve a certain problem. A recursive function or

procedure problem solving approaches have a number of elements in common. The procedure

Programming in Visual Basic Page 70 of 102 By R. Keter


only knows how to solve the simplest case(s) so called base case(s). If called with base case, the

procedure stops recursively calling itself and simply returns to its caller.

If called with a more complex problem, the procedure divides the problem into two conceptual

pieces; a piece that knows what to do and a piece that doesn’t know how to do it. The latter piece

must resemble the original problem, but with a slightly simpler or smaller version of original

problem. Because this new problem looks like the original the procedure launches a fresh copy (a

call) of itself to go to and work on smaller problem. THIS IS CALLED RECURSIVE CALL.

Example 1

Demonstrating factorial function


Factorials are written using the! Symbol, and are defined as follows:
0!=1(by definition)

1!=1

2!=2x1=2
3!=3x2x1=6

4!=4x3x2x1=24

5! = 5 x 4 x 3 x 2 x 1 = 120
To get factorial quickly we multiply the number by the previous factorial, i.e. 5! = 5 x 4!

Similarly, 9! = 9 x 8! And 103! = 103 x 102! This means that if you know a factorial you can

easily get the next one in the series.

Visual basic code

Programming in Visual Basic Page 71 of 102 By R. Keter


Public Function factorial(ByVal y As Double) As Double

If y <= 1 Then

factorial = 1 'Base case

Else

factorial = y * factorial(y - 1) 'Recursive call

End If

End Function

Programming in Visual Basic Page 72 of 102 By R. Keter


Private Sub cmdcalculate_Click()

Dim x, n As Integer

Call lstvalues.Clear

n = txtinput.Text

For x = 0 To n

lstvalues.AddItem Format$(x, "@@") & "!=" & -factorial((x))

Next x

End Sub

Recursion and iteration


Both recursion and iteration are based on control structure. Iteration uses repetition control

structure while recursion uses selection control structure.

Both recursion and iteration involve recursion. Iteration explicitly uses repletion control structure

while recursion achieves repetition through repeated procedure calls.

Iteration and recursion each involve termination test. Iteration terminates when the loop

continuation condition fails, while recursion terminates when the base case is recognized.

Iteration keeps modifying a counter until the counter assumes a value that makes loop

continuation condition fail, recursion keeps producing smaller or simpler version of the original

problem until the base case is reached.

Both iteration and recursion can occur infinitely. An infinite loop loop occurs with iteration if

loop continuation test becomes false, infinite recursion occurs if the recursion step (call) does not

reduce the problem each time in a manner that converges on a base case.

Scope of variables
The scope of variables refers to the coverage or extent of variable reference in a program. In

visual basic there are three scopes of variable:

Programming in Visual Basic Page 73 of 102 By R. Keter


• Local scope
These are variables declared in a procedure’s body. Local variables are only referenced

from where they are declared through end sub or end function.

• Module scope

These are variables declared in general declaration with dim keyword. By default,

module variables can only be referenced in module in which they are declared. They are

sometimes declared private scope.

• Public scope

Refers to variables that are declared public. They are accessible to all modules.

Data structures

These are variable that are used hold data that contain two or more elements together instead of

single element. A tool for handling logically related data items. They are user defined and

provide a method for packing together of different types and structure.

Classes/types of data items

There are two types of data structure:

• Static fixed-size data structure

They are data structures that don’t change during program execution.

• Dynamic data structure

They are data structure that changes when the program executes.
Data structures types

Arrays

This is a consecutive group memory of locations that all have the same name and datatype. This

is a list of variables all with the same name and data type. When we work with single item, we

only we only need to use one variable. However, if we have a list of item which are similar in
Programming in Visual Basic Page 74 of 102 By R. Keter
type we need to declare an array of variables instead of using a variable for each item. For

example:

Format

Dim|Public|Private ArrayName(Subscript) As DataType

• ArrayName is the name of the array.

• Subscript is the dimensions of the array.

• DataType is any valid data type.

Dim name as integer ‘single item

Dim names (10) as string ‘more than two item

Programming in Visual Basic Page 75 of 102 By R. Keter


To refer to a particular location or element in the array, we specify the array name and an array

element position number. For example:

Dim numbers (3) as integer

Fixed-size array
Dim array1 (6) As String

Private Sub Form_Load()

array1(0) = "Kisii"

array1(1) = "Kisumu"

array1(2) = 1234

array13) = 342

array1(4) = 234

array1(5) = 9804

End Sub

Dynamic array

Redim preserve array1 (0 to 7) As String

Private Sub

Form_Load() array1(0) =

"Kisii" array1(1) =

"Kisumu" array1(2) =

1234 array13) = 342

Programming in Visual Basic Page 76 of 102 By R. Keter


array1(4) = 234

array1(5) = 9804

Array1(6)=675

End Sub

Declaring arrays

Arrays can be declared as public in the code module, local. Module array are declared at general

declarations using dim or private keywords. Local arrays are declared I the procedure using

thew keywords dim or static. For example:

Dim names (10) as string

Public declared arrays declare arrays that are used throughout the program or application. The

dim declaration arrays declare arrays that are only used in the procedure. The name of the arrays

states the name to be used to be used to store arrays. The value or position number defines the

upper bound (highest value) of the numbers and the lower bound(lowest value is zero(0).

Vb 1 dimensional array (1D)

Name(1) Name(2)Name(3)Name(4)Name(5)Name(6)Name(7)Name(8)Name(9)Name(10)

This is an array that consists of rows only.

Programming in Visual Basic Page 77 of 102 By R. Keter


Example 1

Use an array and print ten names on a form.

Dim studentName(10) As String

Dim num As Integer

Private Sub cmdprint_Click()

For num = 1 To 10

studentName(num) = InputBox("Enter the student name", "Student names", "", 1500, 4500)

If studentName(num) <> "" Then

Form1.Print studentName(num)
Else

End

End If

Next

End Sub
Example 2

Use an array and print ten names on a list box.

Programming in Visual Basic Page 78 of 102 By R. Keter


Code

Dim studentName(10) As String

Dim num As Integer

Private Sub addName()

For num = 1 To 10

studentName(num) = InputBox("Enter the student name")

List1.AddItem studentName(num)

Next

End Sub

Private Sub cmdprint_Click()


addName
End Sub
Example 3
Use an array to print random numbers from 1 to 100 on a form.

Code
Dim numbers(10) As Integer

Private Sub cmdprint_Click()

Dim x As Integer

Randomize
Programming in Visual Basic Page 79 of 102 By R. Keter
For x = 1 To 10

numbers(x) = Int(20 * Rnd + 2)

Next x
For x = 1 To 10

Print numbers(x)
Next x

End Sub

Multidimensional arrays
These are those arrays that contain two or more indexes. Arrays that require two or more indexes

to identify. For example:

Dim a (2, 2) as integer

Dim x (2, 4) as integer

Like one dimensional array, multidimensional arrays can have public and local module scope.

Function Lbound and Ubound can also used with multidimensional arrays. When calling the

Ubound and Lbound the dimension is passed as an argument.

Example 1

Write a visual basic that produces the data shown below on a form.

Sales for May 2010

Week Sun Mon Tue Wed Thur Fri

1 300 200 400 90 240 700

2 345 120 504 100 300 500

3 500 530 560 300 565 600

4 440 452 432 323 300 500

Programming in Visual Basic Page 80 of 102 By R. Keter


Solution

Dim sales(5, 6) As String

Private Sub Form_Load()

sales(1, 0) = "WEEK"

sales(1, 1) = "SUN"

sales(1, 2) = "MON"

sales(1, 3) = "TUE"

sales(1, 4) = "WED"

sales(1, 5) = "THUR"

sales(1, 6) = "FRI"
sales(2, 0) = 1

sales(2, 1) = 300

sales(2, 2) = 200

sales(2, 3) = 400

sales(2, 4) = 90

sales(2, 5) = 240

sales(2, 6) = 700
Programming in Visual Basic Page 81 of 102 By R. Keter
sales(3, 0) = 2

sales(3, 1) = 345

sales(3, 2) = 120

sales(3, 3) = 504

sales(3, 4) = 100

sales(3, 5) = 300

sales(3, 6) = 500

sales(4, 0) = 3

sales(4, 1) = 500

sales(4, 2) = 530

sales(4, 3) = 560

sales(4, 4) = 300

sales(4, 5) = 565
sales(4, 6) = 600

sales(5, 0) = 4

sales(5, 1) = 440

sales(5, 2) = 452

sales(5, 3) = 432

sales(5, 4) = 323

sales(5, 5) = 300

sales(5, 6) = 500

End Sub

Programming in Visual Basic Page 82 of 102 By R. Keter


Private Sub cmddisplay_Click()

Print sales(1, 0), sales(1, 1), sales(1, 2), sales(1, 3), sales(1, 4), sales(1, 5), sales(1, 6)

Print sales(2, 0), sales(2, 1), sales(2, 2), sales(2, 3), sales(2, 4), sales(2, 5), sales(2, 6)

Print sales(3, 0), sales(3, 1), sales(3, 2), sales(3, 3), sales(3, 4), sales(3, 5), sales(3, 6)

Print sales(3, 0), sales(3, 1), sales(3, 2), sales(3, 3), sales(3, 4), sales(3, 5), sales(3, 6)

Print sales(4, 0), sales(4, 1), sales(4, 2), sales(4, 3), sales(4, 4), sales(4, 5), sales(4, 6)

Print sales(5, 0), sales(5, 1), sales(5, 2), sales(5, 3), sales(5, 4), sales(5, 5), sales(5, 6)

End Sub

Control array
Control arrays group together controls that provide same name and functionality. Each control

array element maintains its own properties but shares its event procedure code with other control

array element. Control arrays can be created in several ways, either by giving a control same

name as another or by copying the forms and pasting the copy on a form.

Function arrays

These are arrays that return a variant array at execution time. The values passed to arrays specify

element values in returned array. The returned array element Lbound I either 1 or 0 depending on

option base.

Searching arrays
There are two techniques to search for arrays:

• Linear search

The computer compares each element of an array with the search key. Search key I the

index specify the way to search for.

• Binary search

Programming in Visual Basic Page 83 of 102 By R. Keter


In binary search the algorithm removes from consideration on behalf of the element in the

array searched for after each comparison. The algorithm locates the middle element of the

array and compares it with search key. If they are equal the search key is found and the

array index of that element is returned.

Example 1
Demonstrating linear search

Vb code

Private Sub cmdsearch_Click()

Dim searchkey As Integer

Dim element As Integer

lblresult.Caption = ""

searchkey = txtkey.Text

element = linearsearch(array3(), searchkey)

If element <> -1 Then

lblresult.Caption = "Value was found"

Else

lblresult.Caption = "Value was not found"

End If

End Sub

Programming in Visual Basic Page 84 of 102 By R. Keter


Private Sub lstdata_click()

Dim x As Integer

Call Randomize

Call lstdata.Clear

lblresult.Caption = ""

For x = LBound(array3) To UBound(array3)

array3(x) = 1 + Int(100 * Rnd())

Call lstdata.AddItem(array3(x))

Next x

End Sub

Public Function linearsearch(y() As Integer, key As Integer) As Integer

Dim x As Integer

For x = LBound(y) To UBound(y)

If y(x) = key Then

linearsearch = x

Exit Function

End If

Next x

linearsearch = -1

End Function

Private Sub Form_Load()

Call lstdata_click

End Sub.

Programming in Visual Basic Page 85 of 102 By R. Keter


QUEUES

This a chain of of data items in the computer memory awaiting execution. Queues use FIFO, first

datum in is the first datum out.

Characteristics of queues

• Data is entered to the end but removed from the front.

• The term FIFO is used to describe queues because first datum in is the first datum out.

• Each data stays in the storage location until its turn comes thereby reducing time spent in

data movement.

Overflow and underflow

Underflow occurs when an attempt is made to remove data from an empty queue. Overflow

occurs when an attempt is made to add data to a queue when all available memory space are

occupied.

Linked lists

Lists are flexible ways of handling data items in order. For example:

Does Not Like Cakes


Alex

Each word in the sentence is a data item, which is linked to the next data item by a pointer.

Datum plus a pointer make a node or element of a list. The last item in the list is a

terminator. This may be stored in an array of records. Each row of an array is one element

in the list. A start pointer saying where the first datum is stored and a free storage pointer

saying where the next datum can go.

Programming in Visual Basic Page 86 of 102 By R. Keter


ROW NO DATUM POINT TO THE NEXT NO COMMENT

Start pointer 1 “ALEX” 2 NEXT DATUM

2 “DOES” 3 NEXT DATUM

3 “NOT” 4 NEXT DATUM

4 “LIKE” 5 NEXT DATUM

5 “CAKES” -1 LAST DATUM

6 EMPTY
Free storage
pointer 7 EMPTY

Types of linked lists

• Single linked lists

The element of the record has only one pointer.

Address 1 Address 2 Address 3


Head

• Double linked lists

The element of the record has two pointers, one pointer for giving the address of

the following record another for giving the address of the proceeding record.

Head

Programming in Visual Basic Page 87 of 102 By R. Keter


• Circular linked lists

The pointer of the last record gives the address first record thus this form a circular

or ring of records.

Address 1 Address 2 Address 3

Trees

Trees these are hierarchal data structure constructed using rule of precedence for data items using

alphabetical or numerical sequence. The elements of a tree are called nodes and each element

consists of a datum and at least two pointers.

56 42 89 65 48

Left pointer Datum Right pointer

56 is the first datum placed I the tree. Its node is therefore called parent node or root node. We

add 42 to the tree next using rule of precedence; lower number to the left and higher number to

the right.

Programming in Visual Basic Page 88 of 102 By R. Keter


STACKS

They are used to temporarily store information or data. Related to queues but data is removed

and added differently. Data is added at the top and removed from top using LIFO.

Next removal pointer

Location of address 101 102 103 104 105 106 107 108 109 110

Contents 20 4 19 12 16

Order of arrival 1 2 3 4 5

Order of removal 5 4 3 2 1

Files
Visual basic files input and output
A file is a collection of data on a given subject, stored in a storage memory. We have executable

files with .EXE extensions, library files with .DLL extensions, word files with .DOC extensions

etc.

Terms used in files

• Record
• Field
• I/O -Stands for input output. This is a means of writing and reading from a file.

Types of files in visual basic


Method of storing files

• Sequential files
This is a method where the files are written in order from beginning to the end.
• Random files / .
A file where all records are accessible individually. They are scattered in a storage media.
• Binary file
The data is stored in byte level and you can read and write individually to the file.

Programming in Visual Basic Page 89 of 102 By R. Keter


• Serial file

They are files stored in series of one another.

• Indexed files

These are files that are stored and accessed using indexes. The files are accessed using

keys.

Opening and closing files

The OPEN command is used to open files. Open command assigns the files to a numbered file

handle, also called channel or sometimes buffer.

Syntax/format

Open “file number” [accessmode][accessrestriction][locktype]as # filenumber


Example 1

• Open “Git.txt” for random read lock read as #1

• “Git.txt” is the name of the file i9n the directory.

• For random means access to the record can be random.

• Read restricts access of the file to read only.

• Lock read means that only persons reading the records can have access to it at any time.

• As # 1 means that the file is assigned to handle # 1.

Access modes

• Input

It is open for sequential files input; the file will be read sequentially starting with the

beginning.

• Output

Programming in Visual Basic Page 90 of 102 By R. Keter


It is open for sequential files output; the file will be read sequentially starting with the

beginning.

• Random

Open to read and write; any specific record can be accessed.

• Append

Sequential output to the end of existing files; does not overwrite the file.

Closing files

The CLOSE command is used to close all the open files.

Syntax/format
Close #fileformat1 [, #filenumber2]……………………….

Creating a sequential file in visual basic


There are two commands that allow reading and writing to a file sequentially.

• Print – reading

• Write – writing

They work almost the same only that print does not separate the fields in the file which makes

data harder to read later.

Format

Write #filenumber, outputlist.

• File number is the number the file was opened with.

• Output list is one or more variables you want write to the file.
Example 1

Create a simple address book file to store the student’s records (contacts).
File design

• Determine the fields to have on the address book for example seven textboxes.

Programming in Visual Basic Page 91 of 102 By R. Keter


• Determine the name of the address book for example “addressbook.txt”
• Determine where to store the file for example “C:\”. We must know the location for the

purpose of the open statement.

• Determine the mod of access for the file when we output it for example input, output,

random, append etc.

• Set the tab order; use the tab index property at properties window for each control on the

form. It enables the user to tab as he enters data.

• For controls that don’t have focus such as labels set their tabstop property to false.

In setting properties for textboxes we will use control arrays technique. This is where we

name one textbox and copy the same name to other six textboxes; txtfield (0) to txtfield (6).

This creates an array of textboxes for output form (file).

Programming in Visual Basic Page 92 of 102 By R. Keter


Vb code

Private Sub cmdcancel_Click()

Dim x As Integer
For x = 0 To 6

txfield(x).Text = ""

Next x

txtfield(0).SetFocus

End Sub

Private Sub cmdexit_Click()

Unload Form1

End Sub
Private Sub cmdwrite_Click()

Dim x As Integer

Dim y As Integer

For x = 0 To 6

Write #1, txtfield(x).Text

Next x

For y = 0 To 6

txtfield(y).Text = ""

Next y

End Sub
Private Sub Form_Load()
Dim x as Integer

For x = 0 To 6

txtfield(x).Text = ""
Programming in Visual Basic Page 93 of 102 By R. Keter
Next x
Open "c:\addressbook.txt" For Append As #1

End Sub

Creating a random file in visual basic

Since the file format for random file is different from the sequential file we will create a new

output file called “phonebook.txt”. We will add a field for Personid at the beginning of each

record. This allows the retrieval of records using a record number.

User defined data types

We will user defined data types to simplify input-output operations since the Get and Put

commands only insert one field at a time. We will create a new variable that contains a whole

record. The user defined data types must be declared in the module. Any information declared

in the module is available to all forms in the application.

Private type phonerecord

Personalid as integer

Fname as string * 15

Lname as string * 15
Address as string * 15

Province as string * 10

Town as string * 10

Code as string * 10

Phone as string *10

End type

Programming in Visual Basic Page 94 of 102 By R. Keter


The type statement creates a new data called phonerecord. The remaining type can be like any

other string or integer. The individual fields in the structured variable can be accessed using dot

notation.

Txttown.text=inrecord.town

In random files it is important to determine the length of the string.

Fname as string *15

Writing and reading records

The command used to write records to random files is Put.

Format
Put #filenumber, [recordnumber], variable.
The recordnumber is optional

Variables are written in the next record position after the last put or get statement if omitted.
The command to read records from the random file is Get.
Format
Get #filenumber, [filenumber, [recordnumber], variable
If record number is omitted the next record is read from the file.

Creating random file

We will write a code using the user defined data types called “phonebook” that will obtain the

next record number from file, accepts input from user and write the record out of the file.

Programming in Visual Basic Page 95 of 102 By R. Keter


Dim outrecord As phonerecord

Dim inrecord As Integer

Dim position As Integer

Dim lastrecord As Integer

Private Type phonerecord

PersonalId As Integer

Fname As String * 15

Lname As String * 15

Address As String * 20
Province As String * 15

Town As String * 10

Code As String * 8

Phone As String * 15

End Type
Private Sub cmdwrite_Click()

Dim x As Integer

poistion = position + 1

Programming in Visual Basic Page 96 of 102 By R. Keter


txtfield(0).Text = position

outrecord.PersonalId = position

outrecord.Fname = txtfield(1).Text

outrecord.Lname = txtfield(2).Text

outrecord.Address = txtfield(3).Text

outrecord.Town = txtfield(4).Text

outrecord.Province = txtfield(5).Text

outrecord.Code = txtfield(6).Text

outrecord.Phone = txtfield(7).Text

Put #1, position, outrecord

For x = 0 To 7

txtfield(x).Text = ""

Next x

End Sub

Private Sub Form_Load()

Dim x As Integer

For x = 0 To 7

txtfield(x).Text = ""

Next x

Open "c:\contacts.txt" For Random As #1

Do While Not EOF(1)

Get #1, , outrecord

Loop

position = lastrecord

lastrecord = Seek(1) - 1

End Sub
Programming in Visual Basic Page 97 of 102 By R. Keter
LINKING VISUAL BASIC TO DATABASES
SAMPLE PROJECT EXAMPLE AND CODE
a).USER INTERFACE

txtR

txtN
Cbogender
cmdsave
adostudent

cmdclear

cmdaddnew

cmddelete

b).CODE cmdP cmdL


cmdN
Private Sub Form_Load()
cbogender.AddItem "MALE"

Programming in Visual Basic Page 98 of 102 By R. Keter


cbogender.AddItem
"FEMALE" End Sub
Private Sub
cmdclear_Click()
txtR.Text = ""
txtN.Text = ""
cbogender.Text
= "" End Sub
Private Sub cmdaddnew_Click()
Adostudent.Recordset.Add
New End Sub

Private Sub cmdsave_Click()


Adostudent.Recordset.Fields("Regno") =
Val(txtR.Text) Adostudent.Recordset.Fields("Name")
= txtN.Text Adostudent.Recordset.Fields("Gender") =
cbogender.Text Adostudent.Recordset.Update
MsgBox "Record
saved" End Sub

Private Sub
cmddelete_Click()
Adostudent.Recordset.Del
ete End Sub

Private Sub cmdF_Click()


Adostudent.Recordset.Move
First End Sub

Private Sub cmdL_Click()


Adostudent.Recordset.Move
Last End Sub

Programming in Visual Basic Page 99 of 102 By R. Keter


Private Sub cmdN_Click()
Adostudent.Recordset.MoveNe
xt If
Adostudent.Recordset.BOF
Then
Adostudent.Recordset.MoveFir
st End If
End Sub

Private Sub cmdP_Click()


Adostudent.Recordset.MovePrev
ious If
Adostudent.Recordset.BOF Then
Adostudent.Recordset.MoveLast
End If
End Sub
Code to select and display details of a record from a database on a list box and
or/ using a Combo
box

Programming in Visual Basic Page 100 of 102 By R. Keter


List1

cboreg

txtn

txtg

Adogetstu txtp
d
txtb

‘Code to display intended information on combo box and list


box Private Sub Form_Load()
List1.AddItem ("NAME" & " " &
"GENDER") List1.AddItem ("-----------" & " " & " ")
While Not Adogetstud.Recordset.EOF
cboreg.AddItem
(Adogetstud.Recordset!regno)
List1.AddItem (Adogetstud.Recordset!Name & " "&
Adogetstud.Recordset!Gender) Adogetstud.Recordset.MoveNext
Wend
Adogetstud.Recordset.Move
First End Sub
‘Code to select and display information using combo
box Private Sub cboreg_Click()

Programming in Visual Basic Page 101 of 102 By R. Keter


While Not Adogetstud.Recordset.EOF
If cboreg.Text = Adogetstud.Recordset!regno
Then txtn.Text = Adogetstud.Recordset!Name
txtg.Text =
Adogetstud.Recordset!Gender
Adogetstud.Recordset.MoveFirst
Exit
Sub
End
If

Adogetstud.Recordset.Move
Next Wend
End Sub

Private Sub txtp_KeyUp(KeyCode As Integer, Shift As Integer)


Const feeRequired As Integer =
20000 txtb.Text = feeRequired -
Val(txtp.Text) End Sub

Programming in Visual Basic Page 102 of 102 By R. Keter

You might also like