0% found this document useful (0 votes)
4 views69 pages

Visual Basic Programming SCO127

The document is a comprehensive students' manual for programming with Visual Basic, covering topics such as the development environment, program elements, control structures, and error handling. It provides detailed explanations of Visual Basic's features, including its object-oriented nature, data types, and the stages of application development. Additionally, it outlines the various file types associated with Visual Basic projects and includes practical guidance on creating user interfaces and managing events.

Uploaded by

dominic omosa
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)
4 views69 pages

Visual Basic Programming SCO127

The document is a comprehensive students' manual for programming with Visual Basic, covering topics such as the development environment, program elements, control structures, and error handling. It provides detailed explanations of Visual Basic's features, including its object-oriented nature, data types, and the stages of application development. Additionally, it outlines the various file types associated with Visual Basic projects and includes practical guidance on creating user interfaces and managing events.

Uploaded by

dominic omosa
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

Programming with visual

basic
STUDENTS’ MANUAL

[2022]
TABLE OF CONTENTS

Table of Contents
1.0 Introduction to Visual Basic .........................................................................................3
1.1 Introduction....................................................................................................................3
1.2 VISUAL BASIC DEVELOPMENT ENVIRONMENT ...............................................3
1.2 VISUAL BASIC IDE ELEMENTS ..............................................................................4
1.4 STAGES IN APPLICATION DEVELOPMENT .........................................................5
1.5 VISUAL BASIC TERMINOLOGIES ..........................................................................6
1.6 VISUAL BASIC FILE TYPES .....................................................................................6
2.0 PROGRAM ELEMENTS ..................................................................................................7
2.1 DATA TYPES (VARIABLE TYPES) ..........................................................................7
2.2 CONVERTING BETWEEN DATA TYPES. ...............................................................8
2.3 SETTING VARIABLE SCOPE ....................................................................................8
2.4 VARIABLE AND CONSTANT DECLARATION .....................................................9
2.5 LOGICAL TESTING ..................................................................................................11
2.6 INPUT AND OUTPUT ...............................................................................................12
3.0 CONTROL STRCUTURES ............................................................................................14
3.1 SELECTION................................................................................................................14
3.2 REPETITIONS (LOOPING) .......................................................................................16
4.0 ARRAYS .........................................................................................................................18
5.0 USER DEFINED DATA TYPE ......................................................................................19
6.0 SUB PROGRAMMING IN VB ......................................................................................20
6.1 Introduction..................................................................................................................20
6.2 PROCEDURES / ROUTINE .......................................................................................20
6.3 FUNCTIONS ...............................................................................................................22
7.0 Working with controls .....................................................................................................23
7.1 Creating and Using Controls .......................................................................................23
7.2 Classification of Controls ............................................................................................23
7.3 TabIndex property of Controls ....................................................................................24
7.4 COMMON CONTROLS .............................................................................................25
7.5 MANAGING FORMS.................................................................................................28
7.6 VALIDITION ..............................................................................................................32
8.0 ERROR HANDLING ......................................................................................................34
9.0 DEBUGGING IN VISUAL BASIC ................................................................................37
10.0 FILES .............................................................................................................................43
10.1 SEQUENTIAL ACCESS ..........................................................................................43
10.2 Random Access Files .................................................................................................43
10.3 CREATING A FILE ..................................................................................................44
10.4 Opening A File ..........................................................................................................46
10.5 Writing To A File ......................................................................................................47
10.7 Reading From A Files ................................................................................................50
10.7 Accessing Any Record In A Random Access File ....................................................55
PROGRAMMING IN VISUAL BASIC ...............................................................................57

2
Programming in visual basic

1.0 Introduction to Visual Basic

1.1 Introduction
It is a window-based programming language that evolved from DOS based BASIC
programming language. Visual refers to the method used to create the graphical user
interface (GUI). BASIC is the abbreviation for Beginners All-purpose Symbolic Instruction
Code. Visual basic has evolved from the original BASIC language and now contains several
hundred statements, functions and keywords many of which relate directly to the windows
(GUI). VB provides an integrated development environment (IDE) in which you can
develop, run, test and debug your applications. It also integrates many different functions
such as design, editing, compiling and debugging within a common environment. Visual
basic is also an object-oriented programming language i.e. it revolves around readymade
objects and it’s also an event driven i.e. all the activities in a program are triggered by one
event or another. Each object has its own properties determining its position, size, color,
appearance and nature of its text and much more. Each object has also its own event
handling procedures. The programmers’ job is to determine where, how and when an object
appears in the screen, what its caption reads and what happens when an event occurs. Visual
basic supports application programming interface (API). API is the library of shared code
that all windows application use for tasks like creating and displaying, windows, drawing
text and graphics on the screen, tracking mouse clicks and other tasks. In most case, the user
has no need to worry about API functions. You just have to click and drag controls and
write basic codes. Visual basic does the work of translating these elements into API
functions behind the scenes.

1.2 VISUAL BASIC DEVELOPMENT ENVIRONMENT


Using VB one can easily design the visual elements of a new programming project. The
following types of applications can be created using visual basic:
I. Standard exe
Standard exe project I a typical application which contains a form by default. Use this
project template to develop a stand-alone application.
II. Data project
This project contains a data environment and a data by default use this project
template to develop an application that reads or manipulates data from a data source.
III. Active X EXE /Active X DLL
These projects are available with the professional edition of vb. These project
templates are used to develop components that expose functionality to other
applications. use an active x exe projects if your components will both explore
functionality programmatically and run as standalone application and use an an active
x DLL project templates if your component will only be used programmatically by
another application
IV. ACTIVE X CONTROL
This project type is also packaged with the professional edition of [Link] template is
used to create active x controls use this project template to create a component design to
use interface element in a form or dialogue box
V. ACTIVE X DOCUMENT EXE /ACTIVE X DOCUMENT DLL
Active X documents are visual basic applications that can run in the environment of a
container that support hyper linking. Use these project templates to create components
designer for use in a document object container such a internet explorer.
3
VI. DHTML APPLICATION
These applications are a combination of compiled visual basic and dynamic Html. Use
this project template to create a component that can be used on the client side of a web
application.
VII. IIS APPLICATION
This is a server-based project that derives html and other internet contents to client
browsers. use this project template to create a component that can be used on a server
side of a web application

1.2 VISUAL BASIC IDE ELEMENTS


1. The menu bar
It presents visual basic menu which contains commands which you use to work
with. These include:
a) File – file handling and printing also used to make EXE files
b) Edit – standard editing functions
c) View –displays or hides windows and toolbars
d) Project – sets projects properties, adds or removes forms and modules
and adds or removes reference and components
e) Format – aligns or sizes controls
f) Debug- starts or stop debugging and stepping through programs
g) Run- starts a program or compiles and starts it
h) Tools- adds procedures, starts the menu editor and sets IDE options
i) Add-ins – adds in manager, lists, add-ins like application wizards and
API viewer window
j) Window – arranges or select open windows
k) Help –it handles help and the about box
2. Tool bar
It contains buttons matching popular menu items. it provides quick access to
commonly used commands in the programming environment.
3. The project explorer
It’s the window that allows you to co-ordinate the parts of your program into
folders for easy manipulation. It lists the forms and modules in your current project.
A project is a collection of files you are to build an application. To pick out the part
of the project you want to work on you only have to find it in the project explorer
and double click it. You can also add or remove items by right clicking them with
the mouse in the project explorer. The buttons at the top of the project explorer
allows you to switch between views.
4. The properties window.
It’s a window used to set properties of various objects. When you select an
object like a control in the VB using the mouse, that object properties appear in the
properties window. To change or examine a property setting in the properties
window you just find that property’s item in the window.
5. Object browser
It provides you with an overview of all the objects in a project, including their
properties and methods and what parameters to pass. You can see the object browser
to explore objects in VB and other applications
6. The tool bar
It provides asset of tools that you can use at design time to place controls on a
form. You do this by just clicking a tool and draw the new button in a form

7. The form layout window

4
It’s used to position forms as you want them to appear in the screen when
they are first displayed. This is done by dragging that form in the form layout
window to that new location.
8. Form designers’ windows.
The form designer displays the current form under design. It 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.

9. Code editor window


It serves as an editor for entering application code. A separate code editor window
is created for each module in your application. To open an objects code in the code window,
just double click that object or right click then close code editor. There are two drop-down
list boxes at the top of the code window ;the left lists lets you select the object to add code
to, and the right lists lets you select the p[procedure to add{all the methods the object
supports appear in this list}
10. Context menus
It contains short cuts to frequently performed actions. To open a context menu,
click the right mouse button on the object you are using.

1.4 STAGES IN APPLICATION DEVELOPMENT


Program statements in an event driven application execute only when a specific event calls
a section of a code assigned to that event. Creating event driven programs in VB requires an
approach different from that used in procedural languages. Creating an application involves
each of the following steps
i. Create a design plan
The design plan should be the road map you use when creating an application. This
planning will help you to understand user’s needs and be more efficient in your
development efforts.
ii. Create the user interface
To create the interface for your application, first place controls and objects on a form
by drawing or painting in the form designer then position the controls and objects according
to your need
iii. Set the properties of the interface
Once you have added objects to a form, you can set their properties at design time or you
use code statements to set properties at run time
iv. Write code for events
After you have set the initial properties for the form and its objects, you can add code that
runs in response to events. Events occur when different actions are performed on a control
or object
v. Save the project
Save the project giving it a unique and description name. You should save the project
frequently as you add code to it
vi. Test and debug the application
As you add code to the project, you can run the application and view its behaviour .VB also
offers numerous tools for debugging your application.
vii. Make an executable file
Upon the completion of the project you will create an executable file. This combines the
various files making up the program into a stand-alone executable file.
viii. Create a set up application
In order to run your application, the user usually needs other files such as DLL files or
custom controls OCX files you used to create your application. VB provides the package

5
and deployment wizard which automates the creation of the set up program and ensures the
user has all necessary files.

1.5 VISUAL BASIC TERMINOLOGIES


Some of the common terms used in development environment are;
➢ Forms
It’s a window that can be customized to serve as the interface for an application or a
dialogue box used to gather information to the application.
➢ Controls
Its graphic representation of objects such as buttons, list boxes used to manipulate to
provide information to the application
➢ Properties
It’s data that describes an object. They are characteristics of an object such as color, caption
or size.
➢ Objects
It’s a general term used to describe all forms or controls that make up a [Link] objects
have properties, methods and events.
➢ Methods.
It’s the actions that an object can perform or that can be performed on the object i.e. the
things you can tell the object to do
➢ Events
Its actions recognized by a form or control. Events occur as the use of the operating system
or application interacts with the objects of a program i.e. events are the things the object
does
➢ Design time
This describes any time an application is being developed in the VB environment. At this
time controls are added to the form and the code for the different events the control will
respond to
➢ Run time
Its anytime the application is running

1.6 VISUAL BASIC FILE TYPES


A VB project is made up of the forms, modules, active X controls and environment settings
that an application requires .VB maintains a project file with extension vbp .In addition to
project file, a project can include the following files;
1) Form files
These files contain the form, the objects on the form and code that runs when an event
occurs on that form. The file extension FRM or FRX
2) VB standard module extension (BAS)
These modules contains sub and function procedures that can be called by any form or
object on a form. Standard modules are optional
3) Active X controls file extension( OCX)
Active x controls are available from Microsoft and third party vendors. They are added
using the components command on the project menu
4) VB class modules extensions (CLS)
The modules contains the class definition methods and properties class modules are optional
5) Resource files extensions (RES)
This file contains binary information used by the application. Resource files are typically
used when creating programs for multiple languages.
6) User control extensions( CFL and CFX)

6
These files contain source code and binary information for use in controls. These files are
compiled into Active X Controls (.OCX files)
7) Upper document extension (DOBand DOX)
These files contain base form and binary information for creating Active X Documents
8) Active designers extensions
These files contain information about designers that are used in the project.e.g you
can create a data environment for run-time data access

2.0 PROGRAM ELEMENTS

2.1 DATA TYPES (VARIABLE TYPES)


Variables in VB are declared using Dim statements. Though you don’t have to
declare variable before you first use them, its good practice to declare variables as
this helps to prevent errors and allow your computer to work more efficiently. The
rules for variable names are;
a) They must begin with a letter,
b) They may contain any mixture of letters and numbers,
c) They may not include punctuation or symbols, with the exception of
under score,
d) They may not have more than forty characters.

VB supports a wider range of data types (variable types) than is found on other Basics.
These include;
➢ Integer
This is a whole number in the range of -32,768 to +32767
➢ Long
This is a whole number in the range of -2,147,483,648 to 2,147,483,647
➢ Single
These are floating data type which holds positive or negative numbers up to around 3.4E38
➢ Double
It’s a floating data type which holds positive and negative numbers to around 1.8E308
➢ Currency
This data type is called scaled integer because it deals with a fixed point numbers that have
5 digits to the left of the decimal and 4 digits to the right. This is more accurate than floating
point numbers for currency values.
➢ Date
It holds dates for january1, 100 to december31, [Link] information is also stored.
➢ Byte
This data type holds positive numbers from 0 to 255
➢ Boolean
This is a simple data type that holds two values either True or False
➢ String
This is a sequence of up to two billion characters
➢ Variant
It’s a highly flexible form of storage that takes string or number values. The nature of the
variable can change during the programs run.
➢ Object
The object data type stores VB objects. These can also be automation object from other
applications

7
2.2 CONVERTING BETWEEN DATA TYPES.
VB supports a number of ways of converting from one type of variable to another. The
following table illustrates conversion statements
To do this, Use this
➢ ANSI value to string chr
➢ String to lower case or upper case Format, Lcase, Ucase
➢ Date to serial number Dateserial, datevalue
➢ Decimal number to other bases Hex, Oct
➢ Number to string Format, str
➢ Date to day, month, weekday or year Day, month, weekday ,year
➢ Time to hour, minute, or second Hour, minute, second
➢ String to ASCII value ASC
➢ String to number Val
➢ Time to serial number Time serial, time value
➢ One data type to another CBOOL,BYTE, CCUR,
CDATE, CDBI, CDEC,
CINT, CLNG, CSNG,
CSTR, CVAR, CRERR, FIX,INT.

2.3 SETTING VARIABLE SCOPE

There are three levels of variable scope in VB as follows;


a) Variables declared in the procedures as private to the procedure
b) Variables declared at the form or module level in the form or modules (general)
section using Dim, ReDim,Private, Static or Type area form or module-level
variables. These variables are available through out the module.
c) Variables declared at the module level in the module’s(general)section using
public as global and are available through out the project in all forms and
modules .NB; you cannot use PUBLIC in procedures.

HANDLING STRINGS
There are two types of strings available in VB namely;
➢ Variable length strings,
➢ Fixed length strings

Variable length strings can contain up to approximately two billion characters and can grow
or shrink to match the data you place to it e.g.
Dim Named as String
Fixed length string as declared with an asterisk character (*) followed by the strings ‘length
eg.
Dim Address as String*20
The address will contain 20 characters.
The table below gives a list of string functions;

To do this Use this


➢ Compare two strings Str comp
➢ Convert to lower case or upper case Lcase, Ucase
➢ Find length of string Len
➢ Justify a string Lset, Rset
8
➢ Manipulate strings Instr, left, LTRIM, MID, right,
RTRIM, TRIM

2.4 VARIABLE AND CONSTANT DECLARATION


➢ Declaring constants
You declare constants in VB with the CONST statement;
{PUBLIC/PRIVATE} const constname
[AS TYPE]=EXPRESSION
The public keyword is used at the module level to make a constant global. This keyword is
not allowed in procedures. The private keyword is used at module or form level to declare
constants that are private which means only available within the module or form where the
declaration is made. Private is not allowed in procedures
The constant name identifier is the actual name of the constant.
Type identifier is the data type which might be Boolean, byte, integer long, currency, single,
double, date, string, or variant.
The expression identifier holds the value you want for this constant.
Example, Private Sub COMMAND-Click ( )
CONST PI=3.14159

➢ Declaring variables
Before using variables, you have to set a side memory space for item. Usually you use the
Dim statement to declare variables although you can use PRIVATE, PUBLIC, STATIC
(Declaring a variable that holds its value between procedure calls) REDIM (Redimension a
dynamic away) or TYPE (Declare a user defined type) key words to declare variables.

THE DIM STATEMENT


Dim {with events} varname{([subscripts] )] [AS[NEW]type]C. [WITH EVENTS]varname
[([Subscripts])] [AS[NEW]type] ]…….
The with events keyword is used only in class as modules. This keyword specifies that the
varname is an object variable used to respond to events triggered by an active X object
The varname identifier is the name of the variable you are declaring. Use subscript if you
are declaring an array
The new keyword enables creation of an object. Type argument specifies the data type of
the variable e.g. byte if you don’t specify any type then its variant. Examples
DIM emploid AS integer
DIM name AS string
NB :
1) Static keyword can be used instead of Dim in a procedure if you want the variable
to retain its value when the procedure ends.
2) Re Dim keyword can be used to set up arrays if you want to be able to change the
size of the array during execution of the program
Variable Declaration

• There are three ways for a variable to be typed (declared):

1. Default
2. Implicit
3. Explicit

• If variables are not implicitly or explicitly typed, they are assigned the variant
type by default. The variant data type is a special type used by Visual Basic
that can contain numeric, string, or date data.

9
• To implicitly type a variable, use the corresponding suffix shown above in the
data type table. For example,

TextValue$ = "This is a string"

creates a string variable, while

Amount% = 300

creates an integer variable.

• There are many advantages to explicitly typing variables. Primarily, we insure


all computations are properly done, mistyped variable names are easily spotted,
and Visual Basic will take care of insuring consistency in upper and lower case
letters used in variable names. Because of these advantages, and because it is
good programming practice, we will explicitly type all variables.

• To explicitly type a variable, you must first determine its scope. There are four
levels of scope:

 Procedure level
 Procedure level, static
 Form and module level
 Global level

• Within a procedure, variables are declared using the Dim statement:

Dim MyInt as Integer


Dim MyDouble as Double
Dim MyString, YourString as String

Procedure level variables declared in this manner do not retain their value once
a procedure terminates.

• To make a procedure level variable retain its value upon exiting the procedure,
replace the Dim keyword with Static:

Static MyInt as Integer


Static MyDouble as Double

10
• Form (module) level variables retain their value and are available to all
procedures within that form (module). Form (module) level variables are
declared in the declarations part of the general object in the form's (module's)
code window. The Dim keyword is used:

Dim MyInt as Integer


Dim MyDate as Date

• Global level variables retain their value and are available to all procedures
within an application. Module level variables are declared in the declarations
part of the general object of a module's code window. (It is advisable to keep
all global variables in one module.) Use the Global keyword:

Global MyInt as Integer


Global MyDate as Date

• What happens if you declare a variable with the same name in two or more
places? More local variables shadow (are accessed in preference to) less local
variables. For example, if a variable MyInt is defined as Global in a module and
declared local in a routine MyRoutine, while in MyRoutine, the local value of
MyInt is accessed. Outside MyRoutine, the global value of MyInt is accessed.

2.5 LOGICAL TESTING


Logical testing may be performed upon string or numeric expression or upon controls. The
expression string or numeric may contain variables, literal values, functions and
arithmetic’s or other operations as long as the expression produces values.
A test will result in true, false, or null value. Null occurs when one or more of the
expressions being tested has a null value.

COMPARISON OPERATORS
VB supports the usual set of relational or comparison operators, plus two unique to the
language.
1. = = equal to
2. < > not equal to
3. < less than
4. > greater than
5. Z = =less than or equal to
6. > = greater than or equal to
7. LIKE- fuzzy string comparisons
8. IS- compares control values

ARITHMETIC OPERATORS
The following is the list of arithmetic operators supported by VB in order of precedence
1. Exponentiation ^
2. Negation -
3. Multiplication and Division * /
4. Integer division /
5. Modules arithmetic MOD
6. Addition and Subtraction + -
7. String concatenation &

11
LOGICAL OPERATORS
There are six logical operators, which are mainly used to combine two or more
relational operations in a test .These include
1. NOT its used with a single expression to reverse it’s value so that true becomes false
and vise versa e.g.……NOT(X>1000)….
2. AND it links two expressions and is true if both expressions are true e.g …X.>1000
AND Y>1000……
3. OR it’s true if either or both expressions are true e.g. ….T.>100 OR K<9000….
4. XOR (EXCLUSIVE OR) it’s true if one or either but not both expressions is true e.g.
…X>1000 X OR Y> 1000
5. EQU(EQUIVALENT) its true if both expressions are true or both are false.e.g X>1000
EQU Y>1000
6. IMP (IMPLICATIONS) It’s true if both are same, as EQU,or if only the second is true .
It’s false only when the first expression is true and the second is false

2.6 INPUT AND OUTPUT


VB contains controls which can be used for input and output. These controls are available
on tool box and the rest can be included if need be (This will be dealt with later).VB
provides two functions which can be used to input or output data in a program. These
functions are;
➢ THE MSGBOX( )
➢ THE INPUTBOX ( )

1. The msgbox
This function is used to display a message to the user and get a return value corresponding
to one of the buttons in the message box syntax MSGBOX (PROMPT
[BUTTONS][TITLE][HELP FILE. CONTEXT])
➢ The prompt argument holds the strings displayed as the message in the dialogue box.
➢ The buttons argument specifies what to put in the message box a specified in the
table below. If the buttons are not specified, the default button is 0 or ok
➢ The title parameter holds the strings displayed in the title bar of the dialogue box
Msg box function can be used to out put a value from the memory e.g. MSGBOX (‘the
answer of the sum is’$ N) N is a memory variable e.g. MSGBOX(“prompt the user”,64,
“meaningful title”)
CONSTANT VALUE DESCRIPTION
1. VB ok only 0 Display ok button only
2. VB ok cancel 1 Displays ok and cancel buttons
3. VB Abort retry/ ignore 2 Displays abort, retry, and ignore buttons
4. VBYes NO 4 Displays yes and no
5. VB Yes No cancel 3 Displays yes, no and cancel
6. VB Retry cancel 5 Displays retry and cancel
7. VB Critical 16 Displays critical message icon
8. VB exclamation 48 Displays warning message icon
9. VB Question 32 Displays warning query icon
10. VBApplication modal 0 Application modal; The user must respond to
the message before continuing work in the
current application
11. VB System modal 4696 System modal; All applications are suspended
until the user responds to the message box.

The following values will be returned by the function showing which button was clicked if
more than one button is displayed in the dialogue box.

12
VALUE BUTTON
1 Ok
2 Cancel
3 Abort
4 Retry
5 Ignore
6 Yes
7 No
Example using button numbers;
Dim type code as integer
Dim reply as integer
Typecode =32 *4
Reply=msgbox (“reply quit?”, type code, “quit”)
If reply = 6, then END.

2. The input box ( ) function


Its used to get a string of text from the user. It takes the following syntax
Varname =INPUT (“PROMPT”.[TITLE][,DEFAULT][,X POS][Y POS])
➢ Varname is the name of the variable declared using dim
➢ Prompt is the string displayed as the message in the dialogue box
➢ Title argument is the string displayed in the title bar of the dialogue box
➢ The default argument is a string displayed in the text box a the default response if no
other input is provided
➢ Xpos argument is a number that specifies (in twips) the horizontal distance of the
left edge of the dialogue box from the left edge of the screen
➢ Ypos argument is a number that specifies (in twips) the vertical distance of the upper
edge of the dialogue box from the top of the screen
The input box will always display ok and cancel and cannot hold symbols. Clicking at
cancel will always cause problems. This can be corrected by use of default value and variant
data type.

13
3.0 CONTROL STRCUTURES

3.1 SELECTION
IF. .THEN. ELSE STATEMENTS
This is used as branching statement. It allows the user to branch one part of the statement
leaving the other part unexecuted.
Syntax
IF condition then
Statements
[Elseif condition then
[Elseifstatements] ]
[Else
[ Elsesestatements] ]
Endif
Example
DIM A AS LONG, B AS LONG
A = Input box (“Enter A”)
B = Input box (“Enter the value of B’)
A = Val (A)
B = Val (B)
IF A >B then
MSGBOX (“The greater number is “ & A)
Elseif B > A then
MSGBOX (“The greater number is “ & B)
ELSE
MSGBOX (“They are equal”)
ENDIF
NB;IF statement can be used in conjunction with logical operators to test for more than one
condition.
THE SELECT CASE STATEMENT
This statement is used like if statement. Select statement causes a particular group of
statement to be chosen from several available groups. The selection is based upon the
current value of an expression which is included within the select statement.
To avoid a lot of if statements use select, this will shorten the code general expression.
SELECT CASE test Expression
Case expression l
Statements 1
Case expression 2
Statements 2
…….
……..
Case expression n
Statements – n

CASE ELSE
[Else statements
END SELECT

Examples;
14
a. SELECT CASE SUMtYPE
CASE “+”
Z =X+Y
CASE “-“
Z =X-Y
CASE “*”
Z =X*Y
CASE “/’
Z =X/Y
END SELECT

b. SELECT CASE COLOR


CASE IS =”RED”
MSGBOX (“COLOUR IS RED”)
CASE IS =”BLUE”
MGBOX (“COLUR IS BLUE’)
CASE ELSE
MSGBOX (“COLOUR IS WHITE”)
END SELECT

c. SELECT CASE MARKS


CASE 0 TO 39
MSGBOX (“Fail”)
CASE 40 TO 59
MSGBOX (“Pass”)
CASE 60 TO 79
MSGBOX (“Credit”)
CASE ELSE
MSGBOX (“Distinction”)
END SELECT

15
3.2 REPETITIONS (LOOPING)
The programs that we have developed used either a sequential or a decision control
statement i.e. execution was carried out in a fixed order or depending upon the outcome of a
condition being tested(logical decision being taken). These programs were of limited nature
because when executed they always performed the same series of actions in the same way
and exactly once. Programming requires frequent performance of an action over and over,
often with variations in the details each time. The mechanism that meets this is the use
loops. The versatility of the computer lies in its ability to perform a set of instructions
repeatedly. This involves repeating some portion of the program either a specific number of
times or until a particular condition is satisfied. The repetitive operation is done by the use
of a loop control structure.

GO TO STATEMENT

This statement is used together with a label to branch another part of the program. It may be
used with if statement to jump outside the loop.
Example
DIM X as integer
X=0
Startloop: ‘This is a label
X =X+1
IF X = 10 then GO TO endloop ‘Another label
GO TO startloop
Endloop
MSGBOX “Done”
End

1. THE FOR . . NEXT STATEMENT


This is a repeating statement used to execute a statement(s) a specified number of times.
Syntax
For index = start to end [step step]
[Statements]
[Exit for]
[Statements]
Next index
Example adding ten numbers
DIM i, s, A AS integer
S=0
FOR i =1 to 10
A = Input box (‘enter a number”)
S = S+A
Next i
MSGBOX (“The total is “and S ‘)

1. THE DO LOOP STATEMENT


It’s a repeating statement used to execute a group of statements until or while a condition is
true. The condition can be evaluated at the beginning or at the end.
At the beginning;
DO [WHILE/UNTIL] Condition
[Statements]
[Exit do]
[Statements]
16
Loop
At the end

At the end
DO
[Statements]
[Exit Do]
[Statements]
Loop [WHILE/ UNTIL] Condition

Example
Private sub numbers ( )
DIM X, Y AS INTEGER
Y =1
S =0
DO
X = INPUT BOX (‘ENTER NUMBER’)
Y =Y+1
S =S+X
UNTIL Y=10
MSGBOX (‘Your total is’ & S)
End sub

2. THE WHILE LOOP


It’s a repetition statement used if you want to stop looping when a condition is no longer
true.
Syntax
While condition
[Statements]
Wend
Example
Dim intinput
Intinput =-1
While intinput <0
Intinput =input box (“enter a positive number”)
Wend

17
4.0 ARRAYS
VB supports arrays where one variable is used to hold a block of data. Arrays provide a
compact and efficient means of handling block of data. Arrays add power of programming
than any other feature. An array is a set of variables of any type all with the same name but
with different identifying numbers or subscripts.

➢ Declaring arrays
You can use dim statements for standard arrays, redim for dynamic arrays, static for arrays
that don’t change when between calls to the procedure they are in. private for arrays private
to the form or module they are declared in public or type for any array of user defined types
to dimension arrays.

➢ Standard arrays
Use dim statement to declare a standard array (note that in VB, arrays can have up to 60
dimensions)
DIM varname [subscripts] [AS [NEW] TYPE]
❖ Varname is an identifier or name associated with the array (the name of the array)
(variable name)
❖ Subscripts I used to declare the array
❖ New is keyword which enables creation of an object
❖ Type argument specifies the data type of the variable which may be byte, Boolean,
integer, long, currency, single, double, date, string
Examples
I. Dim results (50)as integer
This creates a one dimensional array of 51 integers numbered from 0 to 50. Note subscripts
numbering starts from 0 unless you specify otherwise.
II. Dim employees (1…200)as string
This will hold 200 text items. Note subscripts will start from 1
III. Dim two array (20, 40)as integer
This is a two dimensional array holding a table of 20 by 40
IV. Dim marks (10,30,25)as double
This is a multidimensional array holding data in three dimensions.
V. Dim data et (1to15,-20 to 20)as long
This creates a two dimensional array with elements running from data set (*1,-20)
through to data set (15, 20)

➢ Dynamic arrays
You can use the dim statement to declare an array with empty parentheses to declare a
dynamic array. Dynamic arrays can be dimensioned or redimensioned as you need them
with the redim statement.
REDIM [PRESERVE] VARNAME (SUBSCRIPTS) [AS TYPE]
❖ Preserve key word is used to preserve the data in an existing array when you change
the size of the lat dimension
❖ Varname argument hold the name of the array to (n) dimensions
❖ Subscripts term specifies the dimensions of the array
❖ Type argument specifies the type of the array.
Example
Dim dynastring ( ) as string
Redim dynastring (10)
Dynastring (1) =”this is first string”
Redim preserve dynastring (100)
Dynastring (50) =”the fiftieth string”
18
5.0 USER DEFINED DATA TYPE
They are a group of variables referred to as one. In VB user defined data type are simple to
declare as use.
PRIVATE/PUBLIC
Varname 1 AS type
Varname 2 AS type .
End type
❖ Use private if you want the user defined data type to be used within the form or
module.
❖ Use private if you want the user defined data type to be a variable in the whole
project.
❖ Type name is the variable name for the user defined data type.
❖ Varname, 2 are the individual variables within the user type.
❖ Type[e refers to the type of variable in use for each variable name. this can be byte,
long, integer, double, single, currency, string, or Boolean.
Example,
Private type customer
Name as string
Address as string
Adm no as long
End type
Individual elements can be referred to by specifying the type name followed by a dot, the
variable name of the element after declaring it with the dim statement just like any other
data type.
Example
Dim custrar as customer
Custrar .name =”Jones”
[Link] no = input box (“enter the admission number”)
You can use the with structure to avoid repetition of the data type name. e.g.
With custrar
▪ Name = “kamau”
▪ Adm no =14897
▪ Address =”p.o box 4284 nrb”
End with.
You can also declare user defined data type as an array. Example
Dim custrar (20) as customer
You can access each element by specifying the position of each record in the array.
Example
Custrar (1). Name =”Waweru kanja”
Custrar (1). Adm no =14928

19
6.0 SUB PROGRAMMING IN VB
6.1 Introduction
Modular programming refers to development of a program in modular basis i.e the program
is broken up in more manageable units. Each unit represents a major uniquely identifiable
component of a program called a subroutine can be written separately almost separate from
others but in a coordinated basis. This approach facilities the debugging (detecting errors)
and maintenance of a program. It also enables a large program to be developed in a shorter
time by a team of programmers thus making the work load lighter. The modules can be used
in house keeping input, processing and output functions. In good programming practical
program modules form a group of sources code which translates into subprograms such as
subroutines procedures or functions.
Modular programming has the following advantages.
A program can be developed into separate sub programs called modules
◼ It facilitates the development a programs by terms of programmers.
◼ System modules can be written and tested independently
◼ It makes debugging of programs a lot easier because errors are localized in modules.
◼ Programs can be developed in a shorter time

6.2 PROCEDURES / ROUTINE


When you double click a button on a form to open its click event in the code editor, you will
have noticed that the code begins and ends like this; private sub ……. End sub. Sub is short
for subroutines. You ca n also use your own subroutines from scratch. Subroutines can be
thought of as blocks of code that can organize your code into single sections to make
programming easier.
This is how you can declare a subroutine from scratch;

General structure

[Private | Public | Friend] [Static] Sub name [(arglist)]


...
[statements]
...
[Exit Sub]
...
[statements]
...
End Sub

The Public keyword makes a procedure accessible to all other procedures in all modules
and forms. The Private keyword makes a procedure accessible only to other procedures in
the module or form in which it is declared. The Friend keyword is used only in class
modules and specifies that the procedure is visible throughout the project, but not visible to
a controller of an instance of an object. The Static keyword specifies that the procedure’s
local variables should be preserved between calls. The name identifier is the name of the
procedure.
;
❖ [The arglist identifier is a list of variables representing arguments that are passed to
the procedure when it is called. You separate multiple variables with commas. The
statements identifier is the group of statements to be executed within the procedure.
❖ The arglist identifier has the following syntax:
20
❖ [Optional] [ByVal | ByRef] [ParamArray] varname [()] [As type] [= defaultvalue]

❖ In arglist, Optional means that an argument is not required;
❖ ByVal means that the argument is passed by value; ByRef means that the argument
is passed by reference (ByRef is the default in Visual Basic);
❖ ParamArray is used as the last argument in arglist to indicate that the final
argument is an array of Variant elements; varname is the name of the variable
passed as an argument; type is the data type of the argument; and defaultvalue is any
constant or constant expression, which is used as the argument’s default value if
you’ve used the Optional keyword.
The Exit Sub keywords cause an immediate exit from a Sub procedure. Finally, End Sub
ends the procedure definition

NB:
❖ When you use byval, you pass a copy of variable to a procedure.
❖ When you use byref, you pass a reference to the variable
❖ If you make changes to that reference, the original variable is changed

21
6.3 FUNCTIONS
A function is a procedure which returns a single value to its reference point. It can also be
referred to as block of code that you call and pass arguments to and using functions helps
break your code up into manageable parts. The function is declared using the following
syntax;
[Private | Public | Friend] [Static] Function name [(arglist)] [As type]
...
[statements]
...
[name = expression]
...
[Exit Function]
...
[statements]
...
End Function
◼ The Public keyword makes a procedure accessible to all other procedures in all
modules and forms.
◼ The Private keyword makes a procedure accessible only to other procedures in the
module or form in which it is declared.
◼ The Friend keyword is used only in class modules and specifies that the procedure
is visible throughout the project, but not visible to a controller of an instance of an
object.
◼ The Static keyword specifies that the procedure’s local variables should be
preserved between calls. The name identifier is the name of the procedure. The
arglist identifier is a list of variables representing arguments that are passed to the
procedure when it is called. You separate multiple variables with commas. The
statements identifier is the group of statements to be executed within the procedure.

The arglist identifier has this following syntax:

[Optional] [ByVal | ByRef] [ParamArray] varname [()] [As type]


[= defaultvalue]

In arglist, Optional means that an argument is not required;


ByVal means that the argument is passed by value;
ByRef means that the argument is passed by reference (ByRef is the default in Visual
Basic);
ParamArray is used as the last argument in arglist to indicate that the final argument is an
array of Variant elements; varname is the name of the variable passed as an argument; type
is the data type of the argument; and default value is any constant or constant expression,
which is used as the argument’s default value if you’ve used the Optional keyword. The
type identifier is the data type returned by the function.
The Exit Function keywords cause an immediate exit from a Function procedure.

22
7.0 Working with controls
This lesson concentrates on Visual Basic controls and the ways of creating and
implementing the. It also helps us to understand the concept of Control Arrays. Controls are
used to recieve user input and display output and has its own set of properties, methods and
events. Let us discuss few of these controls in this lesson.

7.1 Creating and Using Controls

A control is an object that can be drawn on a Form object to enable or enhance user
interaction with an application. Controls have properties that define aspects their
appearance, such as position, size and colour, and aspects of their behavior, such as their
response to the user input. They can respond to events initiated by the user or set off by the
system. For instance, a code could be written in a CommandButton control's click event
procedure that would load a file or display a result.

In addition to properties and events, methods can also be used to manipulate controls from
code. For instance, the move method can be used with some controls to change their
location and size.

Most of the controls provide choices to users that can be in the form of OptionButton or
CheckBox controls, ListBox entries or ScrollBars to select a value. Let us discuss these
controls by means of a few simple applications in the following lessons.

7.2 Classification of Controls

Visual Basic cojntrols are broadly classified as standard controls, ActiveX controls and
insertable objects. Standard controls such as CommandButton, Label and Frame controls
are contained inside .EXE file and are always included in the ToolBox which cannot be
removed. ActiveX controls exist as separate files with either .VBX or .OCX extension.
They include specialized controls such as;

• MSChart control
• The Communications control
• The Animation control
• The ListView control
• An ImageList control
• The Multimedia control
• The Internet Transfer control
• The WinSock control
• The TreeView control
• The SysInfo control
• The Picture Clip control

Some of these objects support OLE Automation, which allow programming another
application's object from within Visual Basic application.

I would like to stress that knowing how and when to set the objects' properties is very
important as it can help you to write a good program or you may fail to write a good
program. So, I advice you to spend a lot of time playing with the objects' properties

23
Here are some important points about setting up the properties

• You should set the Caption Property of a control clearly so that a user knows what to
do with that command. For example, in the calculator program, all the captions of
the command buttons such as +, - , MC, MR are commonly found in an ordinary
calculator, a user should have no problem in manipulating the buttons.
• A lot of programmers like to use a meaningful name for the Name Property may be
because it is easier for them to write and read the event procedure and easier to
debug or modify the programs later. However, it is not a must to do that as long as
you label your objects clearly and use comments in the program whenever you feel
necessary
• One more important property is whether the control is enabled or not
• Finally, you must also considering making the control visible or invisible at runtime,
or when should it become visible or invisible

7.3 TabIndex property of Controls

Visual Basic uses the TabIndex property to determine the control that would receive the
focus next when a tab key is pressed. Every time a tab key is pressed, Visual Basic looks at
the value of the TabIndex for the control that has focus and then it scans through the
controls searching for the next highest TabIndex number. When there are no more controls
with higher TabIndex value, Visual Basic starts all over again with 0 and looks for the first
control with TabIndex of 0 or higher that can accept keyboard input.

By default, Visual Basic assigns a tab order to control as we draw the controls on the Form,
except for Menu, Timer, Data, Image, Line and Shape controls, which are not included in
tab order. At run time, invisible or disabled controls also cannot receive the focus although
a TabIndex value is given. Setting the TabIndex property of controls is compulsory in
development [Link] are graphical tools used to create and or enhance
functionality of an application. They are objects which can be passed onto a form and range
from labels to file management utilities. The VB tool box includes several controls. Each
control has properties, methods and events that you can use for specific purpose in the
interface. Each control can have code attached to it though not all will have.

Just as each type of controls has its own set of properties, some of which are common to all,
so each also has its own set of events, and some of these are common to all. To see what
kind of events are handled, place an object on the form and you double click on it. This
opens the code window. Its here that you write the code to be attached to events. Each event
has its own procedure or SUB and opening and closing lines of these are already written n
for you. The name in the opening line is composed of names of the control and event linked
by an underscore. Private at the start means that the code can only be accessed from that
control or other controls on the same form
It’s important to note that the values stored in controls are accessible to other parts of a
program and can therefore be used as alternative to variables. When the user types into a
TEXT BOX, it is stored in the TEXT property. This can be used by code attached to the
textbox or to any other control. e.g. [Link]=text [Link].
Every control has one main property and this is always the obvious one-The caption for a
label and text of a text box. You do not have to specify this property when you want to read
or change its value thus; Label=Text 1.
There are two types of controls;
➢ Inherent
➢ Custom
The tool box contains the inherent controls or standard controls.
24
The custom controls are optional. You must add them to the tool box before you use them.
Controls (Active x controls)are available for almost any function imaginable. These controls
are contained in files that have extension OCX extension.

Adding custom controls


1. Open a project
2. From project menu, click at components or right click at toolbox then close
components
3. click the check box to the left of the name of the appropriate control
4. click ok to close the components dialogue box

Removing custom controls


1. On the project menu, click components or right click at the tool bar then close
components.
2. Clear the check box text to each control you want to remove
3. Click ok to close the components dialogue box
Setting control properties
You can set control properties at design time or at run time. Properties set at design time
allow the developer to set default values in the application. You can use properties window
to set controls at design time.
1. Right click a control and click at properties or left click the control or press F4
2. Type the value in the appropriate box

To set properties for multiple controls


1. Click and drag the mouse over the controls you want to select or click and press
ctrl and shift and click the controls.
2. Type the value in the appropriate property box
One can also set control properties at run time. This allows you to programmatically control
objects as the application are running. You use the following.
WITH TXTNAME
• Alignment =VB centre
• Backcolor=VB blue
• Enabled = True
• Font. underline =True
• [Link] =17
• Font name =’Times new roman”
• Height =700
• Left =600
• Text =”It is well”
• Tool tip text =”welcome”
• Top =70
• Width =600
• Visible =True
END WITH

7.4 COMMON CONTROLS


1. Command button
They are used for setting properties to other controls and for writing one event click. They
also serve as a method of selection. For selection purposes they are basically used where
there is limited number of options. The choice may be ok or cancel, start or quit. The

25
caption properly determines what text appears on the button and the name properly. To
determine the name of the command always tart with CMD for command.
Use $ character to create keyboard shortcut. Set the style property to graphical then set the
picture property to a suitable icon or bitmap
2. Labels
They are used to display text that the user does not need to edit. You can create a multiple
label by setting its word wrap property to true. To select more than one label, select the first
label then hold shift and continue selecting. To align them, choose align from format menu
3. Text boxes
Text box is a control that is an essential part of the most VB applications. They provide a
means by which one can type information at run time and it can provide information space
by use of scroll bars and multiple properties. Set multiline property to true and its scroll bar
property to both
4. A picture box
It’s the main graphics control. It can contain a picture created by paint or similar art
packages. These must be in an acceptable format.i.e BMP, WMF, JPG OR GIF. The
drawing methods can also be used in a picture box. You can load a picture in the code e.g
SET 1
5. Check boxes
They are ideal when you want to present a set of options from which the user can choose
none, one, or more than one. A check box has a toggle switches turning options on or off.
When a user clicks the box a mark appears, another click removes the mark. Examples click
/AB NOTES
6. Option button
They are normally used to select one from a set of mutually exclusive options. At any one
time, there can only be one set on a form unless they are enclosed in frames. With option
button unlike check boxes, you can only have one button checked. Checking option button
automatically, uncheck any other.e.g check LAB NOTES.

26
7. Frames
It’s like a decorative control used to hold other controls together. I.e. it’s used as a container
for grouping objects together such as options buttons.
8. Images
Image boxes can be used like picture box. A picture box has all the features of an image
control or more. Picture boxes uses much more memory and system resources compared to
image box. You cannot use an image control as a container for other controls nor can you
draw graphics or text on it in your code.
9. Timer
It’s a control that will file an event at intervals set by the user. A timer is unusual in that it’s
fixed in size and is invisible once the program is running. Its purpose is to control actions
that must take place at or after the set intervals. You could use one to set a time limit for a
response to a question to produce a ticking clock or to animate images.
10. List box
It’s a powerful VB control used to present a list of options/ choices to the user. If the list is
too long to fit in the box, vertical scroll bars will be added at run time. Items can only be
added to the list during run time. It can also be used to present information to the user. A list
box can even present thousands of choices like addresses.
11. Combo box
It’s a one line text box combined with a list box. It can also be thought to be a combination
of a drop down list with a slot in which the user can enter their own data when the program
is running. The advantage of a combo box over a text box is that most choices can be
presented without any need of typing them. Another advantage is that it uses less space.
12. Control collections
VB provides an array that contains all control in a form. This array is known as control
collections. The control collection has one property count which returns the number of
controls on the form. You can use control collection to perform an action on a group of
controls. Example; to clear all text boxes in a form. DIM CTL AS control. For each ctl in
controls. if type name (ctl) =”text box’ then [Link]= ‘‘end if next ctl
13. Control arrays
It’s a group of controls that share the same name type and event procedures. A control
array has at least one element with an index property that is greater than or equal to zero.
The index can grow to maximum of 32,767 elements if your system resources permit.
Advantages
• Control arrays allow you to add new controls at run time
• Each new element you add to a control array inherits the common events procedures
of the array. This
can facilitate development
• Controls in a control array can share code.

Creating control array at design time


This can be done in three ways;
1. Give two controls the same name
2. Copy and paste a control
3. Set the index property by using the properties window.
You refer to a control with the following syntax control name (Index). You specify the
index of a control when you crate it. Example

27
If chk dept (index).value =Vbchecked then
SELECT CASE index
CASE 0
MSG BOX (“computer”)
CASE 1
MSG BOX (“electrical”)
CASE 2
MSG BOX (“business”)
End select
End if.
Creating controls at run time
VB lets you create controls at run time. This gives you the flexibility to customize the
interface according to the needs of the user. The load statement and add method are used to
create controls dynamically. If you try to load a control that already exists a run time will
occur.
The following code creates a new control:
Dim 1 as integer
i = TXTarry (@).count –finds the next available index
Load TXT array (i) –add annex text box
TXTarray (i).top = TXT array (i-1).top+400 ‘position the text box on the form
TXT array (i).visible=true –makes it visible

You can dynamically remove controls using unload statement. If you try to unload a control
that was created at design time or that has already been unloaded a run time error occurs

Adding controls using the add method


Private sub form _load( )
Frm students. Controls. Add ‘[Link] box”,”TXT NAME’
WITH frm students! TXT NAME
• Visible = true
• Width = 2000
• Left =1000
• Top =3000
• Text =”home at last”
End with
End sub.

7.5 MANAGING FORMS


Forms are the basic elements of the user interface in VB applications. They provide a frame
work you can use through out your application to give a consistence look and feel. Forms
serve as a window that you customize to design the interface of your applications
User interface design principles
The user interface is the link between your audience and the capabilities of your application.
The following points should be considered when deigning a user interface such as a form
➢ Composition
It’s the layout or look and feel of an application. Composition includes such factors as;
I. Simplicity
An application must be as simple as possible for the user to understand.
II. Positioning of controls
Important or frequently accessed controls should be given a position of prominence. Les
important controls should be neglected to less prominent locations
III. Consistence
28
Consistency or sameness is a key consideration in user interface design keeping as similar
design or “crock” throughout your application enhances usability.
IV. Affordances
Affordances are visual clues to the function of user interface. User interface also makes use
of affordances e.g. flat buttons might be appropriate in some cases such as in games
V. White space
Including white pace in your user interface can help to emphasize elements and improve
usability. White space doesn’t necessary have to be white; it refers to the use of blank space
between and around controls on a form.
VI. Color
The use of color in your interface can add visual appeal but color can easily be a problem if
not carefully considered on your initial design
VII. Images and icons.
Use of images and icons add visual interest to your application. Images can convey
information efficiently without the need for text but images are often perceived differently
by different people. So, consider the cultural significance of images.
VIII. Fonts
They are important part of your interface. They often communicate important information
to the user/ choose one or two simple fonts as Arial or times new roman.
IX. Menus
Proper planning and design of menus and tool bars ensures that the users will understand
the purpose and features of your applications.
➢ Adding a form to a project
On the project menu, click at add form. The add form dialogue box appears
Click at form and then click open
➢ Setting the startup form
VB uses the first form in a project as the default startup form. However, as you add more
new forms to the project, you may need to change this default. This can be done by;
On the project menu, click at project name properties. The project properties dialogue box
appears.
In the startup object drop down list box, click the name of the form you want to set as the
default form and click at ok.

FORM METHODS
A method is something that an object does. They actions that an object can perform.
i. Load
The load statement initializes and loads the form into memory without displaying the form
on the users screen.e.g LOAD Frm my form
ii. Unload
Unload statement removes a form from the memory. The me statement can be used to refer
to the current form in the code.e.g unload Frm my form or unload me
iii. Hide
Hide method removes the form from the screen without removing in from the memory. E.g.
Frmmyform .hide or
Me. Hide
iv. Show
The show method includes an implied load. This means the specified form is not already
loaded when the show method is called visual basic automatically loads ice form into
memory & then displays form either modally or modeless. A modal method requires the
user to take action before focus can change to another form .A modal window does not
require user, action before the focus can change to another form.

29
FORM EVENTS.
Forms are code modules that control procedures called events. Events respond to system or user
input by running whatever code you have placed in the particular events...Click events for example
runs whenever the mouse is clicked to the form. When the event is called to execute its code, the
required is often referred to as firing or triggering the event.
These events include the following
1. Initialize.
Is typically used to prepare an application for used variables are assigned to initial values and
controls may be more or resized to accommodate initialization, data initialize event will fire only
once during the life of application.
Example
Frmmyform, show
Load frmmyform.
Form variables can be defined in this event. Form-level variables are variables that are recognized
by all procedures within that form modules.
2 load.
The load events are used to perform actions that need to occur. Prior to the form being
displayed it is used to assign default values to the form & its controls. The load event occurs each
time that form is loaded into the memory. The load fires when a form starts as a result of the load
statement show statements or when reference is made to unload form properties, methods or
[Link]
PRIVATE SUB FORM-LOAD ()
Combol. Add item “computer”
Combol. Add item ‘Electrical”
[Link] =2
End sub
3. Activate /Deactivate
When the user moves between two or more forms, you can use activate and deactivate events to
define the forms behavior. The activate events fires when the forms receives focus from another
form within the same project and when the form is visible. Deactivate fires when a form looses
focus to another form. This event fires after the lost focus event.
4 query unload
Its useful when you need to know how the user is closing the form. The query unload event occurs
before the form unload event. Query unload has additional features compared to the unload event.
Some of the things that may cause query unload event are;
❖ the user chooses the close command from the control menu on the form
❖ the unload statement is invoked from code
❖ current operating system is ending
❖ Microsoft windows task manager is closing the application
❖ The MDI child form is closing because the MDI form is closing.
To stop unloading set the cancel argument to true. Example;
Private sub query unload (cancel as integer, unloadmode as integer)
If unload mode < >VB form code then
MSGBOX (“”USE TO EXIT BUTTON TO CLOSE THE FORM”)
Cancel = true
Endif
End sub
5. unload
The unload event occurs before terminate events. Use the unload event procedure to verify that the
form should be unloaded or to specify the actions that take place when unloading the form
6 terminate
Fires when all references to an instance of a form are removed from a memory. To remove
the forms variable from memory and free the form off system resources set the form equal
to nothing.
Set frmmyform = nothing

30
ADDING TOOL BARS TO FORMS
You can add tool bars to already existing program; just follow these steps:
1. Use the project/ components to open the components box and select the
controls.
2. Click the Microsoft windows common control box and click on ok to close
the component box.
3. Double click the new tool bar in the tool box to add a new tool bar to your
form now.
4. Right click the tool bar now and select the properties in the pop up menu that
appears opening the buttons properties page.
5. Click the buttons tab in the property page now and click insert to insert a
new button into the tool bar.
6. Give the new button the caption you want and set it’s key property to string
of text you want to refer to the button with code.7
7. Add other buttons in the same way and close the property page.
8. double click button in tool now to open code window displaying
toolbar1_button click()
9. add the code you want to toolbar1_button click() by use of SELECT CASE
. EXAMPLE
Private sub toolbar1_button click (by Val button as [Link])
SELECT CASE button Key
CASE “FIRST”
MSGBOX “you clicked the first button’
. CASE ‘SECOND”.
MSGBOX “you clicked the second button”
END SELECT
END SUB.

M D I (MULTIPLE DOCUMENT INTERFACE)


M d I application presents the use with a single form that can contain, display
arrange and manage forms inside it.
The container forms are called MDI child forms.
Creating MDI application is easy you simply create a standard EXE project
and add a new MDI form HPM in the project menu.

NB: You can arrange the MDI child forms with the MDI form method Arrange ().
Example
Private sub Arrange1-click me. Arrange VB cascade
End sub.
Other methods include
VBtilehorizontal
VBtilehorizontal
VBarrangeicons

ADDING A MENU TO A FORM


You can add a menu to a form by using visual basic menu editor. To add a menu to a
form select that form and open the menu editor by selecting the menu editor in the
tools menu.
Here is how to create anew menu system in menu editor step by step.
1. enter the first menus caption and name
2. click the next button or press enter
3. click the right arrow to indent one level making this next entry a menu item
4. enter the items caption and name

31
5. click the next button
6. repeat steps 4&5 for all items in the first menu
7. click the next button
8. click the left arrow to outdent making this next entry menu
9. enter the next menus caption and name
10. click the right arrow to indent one level making this next entry a menu item
11. repeat steps 4&5 for the items in this new menu
12. repeat step 7 through all for the rest of the menus in the program
13. click on ok to close the menu editor
14. edit the code
NB: You can add main separator by choosing it on the editor menu and a short cut key
by also selecting on the editor menu

CREATING POP’UP MENUS


Pop up menus are those menus that appear when you right click a form.
To create a new pop up menu just user the menu to create a new menu named pop
up. Note that we set this menu’s visible properly false too make sure we don’t
display it in the menu bar. You can code the action the same way as the normal
menus.

7.6 VALIDITION
Data validation ensures that every data value entered into your application is accurate and of
a valid data type. Verifying the data type is one of the most common tasks in data
validation. A well designed application can prevent most data-entry errors.
Setting up your application to accept the proper information from the calculations and can
even prevent run time errors such as type mismatch
.
Types of validation
1. form-level validation
Form –level validation verifies data after all fields on a form have been completely filled in
by a user.
2. field-level validation
Field –level validation verifies the data in each field one at a time as each field is filled.

FORM-LEVEL VALIDATION
When you use form level validation, you verify the data in each field on a form in a single
procedure. You can have a ok button which can be used to verify that all text boxes has data
before a certain action is taken e.g. update fields in a table. The following code in a click
event us used to make sure that all the text boxes have data.

Private Sub Command1_Click()


Dim ELEMENT As Control

For Each ELEMENT In Controls


If TypeOf ELEMENT Is TextBox Then
If [Link] = "" Then
MsgBox ("All Text Boxes Require Data")
Exit Sub
End If
End If
Next ELEMENT
32
End Sub
FIELD-LEVEL VALIDATION
You may want to validate data as it is entered into each field. Field level validation provides
immediate direction to the user and gives the developer control over user actions. This can
be done in various ways;
1. Using the text box control properties
The textbox control contains several design type properties that restrict the type of values
user can enter. These properties include the following:
➢ Maxlength property: - this is used to set the maximum number of characters that the
user can enter into a textbox
➢ Password char property: - the password character property lets you hide (or mask)
characters that are entered into a textbox.
➢ Lock property: - the locked property setting determines whether a user can edit the
text in a text box. If locked property is set to true, the user can view the text in the
text box but cannot edit the text
2. Using events
❖ Validating change events-a text box controls fires a change event each time the user
enters a character into text box
❖ Using the validate event- the simplest way to validate data is to use the validate
event. The validate event also provides you with control over when focus can be
moved to another control. Using validate event you can prevent the focus from even
shifting top another control until all validation rules have been met.
PRIVATE SUB TXTNAME- validate ( )
If Len (txt name. text) <1 then
MSGBOX “You must type name”
CANCEL =True
Endif
End sub
Or If Len (txt state. text) < > 2 then
MSGBOX ‘State must be two characters
Cancel = True
Endif
3 using lost focus
The lost focus event occurs when an object loses focus. This can occur as a result of user
action such as tabbing to another field or clicking another object. This validation technique
can result in an infinite loop where one or more controls are using the set focus method in
the lost focus event.
4 using key press
When a user enters a standard ASCII character the key event occurs. By responding to the
key press event you can restrict the characters entered or transform them as are typed.
Example;
Private Sub txtClientNumber_KeyPress(KeyAscii As Integer)
'This procedure ensure that you only enter numbers
Select Case KeyAscii
Case Asc("0") To Asc("9")
Case 32, vbKeyDelete, Asc(vbBack)
Case Else
KeyAscii = 0
[Link]
txtClientNumber = ""
End Select
End Sub
5. Validation events

33
VB include several functions that assist in the process. These functions include;
❖ Isnumeric
❖ Isdate
❖ Isalphabetic

a) Isnumeric
This function returns a value of true if the argument is numeric. If the argument is not
numeric, false is returned
b) Isdate
This returns a value of true if the argument is a valid date. If the argument is not a valid
date, false is returned.

If Isnumeric (txtname .text) then,


MSGBOX “Name cannot be numeric “
TXTNAME. Set focus
Cancel= true

ENDIF.

If is date ([Link]) then


MSGBOX “Name cannot be date”
TXTNAME. Set focus
Cancel= true
ENDIF

6. MASK PROPERTY
The mask property forces data to be entered in a predefined template. You can et this
property at design time or at run time. Mask property can be used to validate content such as
the correct month or time of the day.
Example;
MSKphone. Mask =” (# # #) # # #. # # #”
The mask property is used with masked edit control. To add the masked edit control to the
tool box use;
❖ On the project menu click components. The components dialogue box
appears.
❖ On the controls tab, select Microsoft masked control 6.0 then click ok

Clearing a masked edit


You can clear a masked edit box by the following code;
MSK phone number. Mask =” “
You can use the text property after the masked edit box is empty
MSK phone number. Text =” “

8.0 ERROR HANDLING


Creating an error handler

34
When VB encounters a run time error, it checks to see whether an error handler has been
created. If it has not, VB automatically presents to the user a message box showing an error
number and a brief description. If the user clicks at ok, the application is terminated.
Error handlers are specific to individual procedures. This means that each event or general
procedure you create should have its own error handler. There are three basic steps in
creating an error handler.
❖ Enable an error handler.
❖ Add code to handle the possible errors
❖ Resume normal execution of the program
To enable error handler, use on error GO TO statement and provide the names of a label in
your procedure. The label marks a point in code that you want VB to jump to when a run-
time error occurs. Labels follow the same naming rules a variable. However you must add a
colon to the end of the name.
Example;
Private sub CMD open –click ( )
On error GO TO openerror
Code that opens a database
Exit SUB
Open error: code to handle an error goes here
END SUB
The following example shows the error that occurred;
Error handler:
MSGBOX”The following error occurred” and [Link]
When the error has been handled, the final step is to resume execution of the application.
There are three ways to return control.
a. Retry the line code that caused the initial error
b. Start from the line immediately following the one that caused the error
c. Terminate the application
This can be done by the following code.
DIM ANS AS INTEGER
Error handler:
ANS =MSGBOX (“An error occurred”, VBAbortRetryIgnore)
SELECT CASE ANS
CASE VBRETRY
RESUME
CASE VBIGNORE
RESUME NEXT
CASE VBABORT
UNLOAD ME
END SELECT

Example;
DIM ANS AS INTEGER
My error handler:
ANS =MSGBOX (“An error occurred “, VB abort retry ignore)
SELECT CASE ANS
CASE VB RETRY
NUM =INPUTBOX (“ENTER THE CORRECT VALUE”)
RESUME
CASE VB IGNORE
RESUME NEXT
CASE VB ABORT
UNLOAD ME

35
END SE LECT
NB;
Resume line or label can be used to return to a specific line, number or label.

36
9.0 DEBUGGING IN VISUAL BASIC
Debugging is a process by which error are identified and resolved in source code. In visual
basic error can occur anywhere during entire development cycle such as
• Design time
• Compile time
• Run Time

Design Time Bugs


Errors that occurs in the IDE and before the program is compiled are called design-
time bugs. These are the most common ones. These bugs are caused by misuse of some
component.
The following e.g. shows a function that works as long as a textbox control is passed to it. If
any other type of control (say text box, here, the extra space causes the problem) is passed,
it fails to execute and an error is reported this is a design time error, which is display the
moment the user navigates to the next statement.

Sub settext( ctrl as text box, txt as String)


[Link] = Lcase(Trim$(txt) + “ : ” + Date$
End sub

On entering the first statement of the above coding in the


general declaration section, the following error is report.

Compile-time bugs
Compile-time bugs are those that occur when we attempt to create the program
executable file (EXE) or run the project. Visual Basic can locate compile-time bugs if the
Visual Basic application is set up correctly. Visual Basic set the several points to users,
which can be change as needed.
Compile-time bugs are detected by visual basic automatically when the program is
compiled using F5. If the Start With Full Compile option is used, the Compile On Demand
can be turned on, and the developer will not find any bugs until the line of code with the
bugs is actually executed.
Compile errors occur as a result of incorrectly constructed code such as Next
statement without a corresponding For statement or programming mistakes that violate the
rules of Basic, such as misplace word, missing separator, or type mismatch. Compile errors
included syntax errors. These include mismatched parentheses or an incorrect number of
arguments passed to an intrinsic function.

Runtime bugs
A Visual Basic runtime error is the exception generated by Visual Basic when it
ascertains that the code is about to perform something illegal. An illegal function could be
something as simple as trying to determine the size of a file that dose not exist or attempting
to multiply two numbers, the result of which exceeds the storage space that could be
contained by the data type.
However, using an error handler could prevent this error dialog box from being
shown and save the program from crashing. By practices we can also use our knowledge
that a particular error identified by its error number will be generated to help guide our
logic. This sort of “inline” error handling is very powerful and can be handled using an
error handler that checks for the condition of, say Error 57, and then does something to
avoid the situation. This error can be finally rectified by changing the code suitably.

37
E.g.
Consider the following example where we declare two variable x and y. try dividing x
(assign a value 9) by y (assign 0), assigning the quotient to another variable z.

Private sub Form1_load()


Dim x as Integer
Dim y as Integer
Dim z as Integer
X=9
Y=0
Z=x/y
End Sub

Visual Basic Debugging Tools


The best way to keep bugs out is to prevent then in the first place. Visual Basic gives a
programming several tools, include IDE
options and compile directives, to help
achieve this goal.

IDE Options
Visual Basic offer several IDE
option that can help the user write better
code.
• Auto Syntax Check
• Required Variable Declaration
• Auto List Members
• Auto Quick Info
• Auto data Tips
• Option Explicit
• Option Compare Text

Additional settings and debugging aids can be viewed in a dialog box shown in the fig.
using the following steps
1. Select Option from Tools Menu
2. Choose the Editor tab in the Option dialog box

Require Variable declaration:


This option explicitly inserts the Option Explicit statement in each new form,
module, or class created. A dim, private, public, ReDim or static statement must be used to
declare a variable before the value is assigned to it. If an undeclared
variable is used, an error occurs at compile time.
e.g.
Option Explicit
Private sub Form1_Load()
Sum = 0
End sub

38
Auto Syntax Check:
The Auto Syntax Check option forces Visual Basic to check the line of code when
the user moves the cursor off the line.

e.g.
Private sub Form1_load()
Dim a integer
End sub
In this program Dim a here required “As” so compiler give a error message when we try to move
cursor to next line.

Auto Quick Info:


The Auto Quick Info in Visual Basic display required or Optional parameters for
methods. VB display all possible parameters while highlighting the one we are currently
entering. Auto Quick Info makes it easier to use methods and properties because we no
longer have to remember or look up all the arguments it’s properties and methods.

Debugging Tools are designed to help the user with logic and run-time errors. Visual Basic
provides several buttons in the ToolBar that are helpful for debugging. They are

Breakpoint: Defines a line in the code window where Visual Basic suspends execution of
application
Instant Watch: Lists the current value of an expression while the application is in the
break-mode.
Calls: Presents a dialog box that shows all procedures that have been called but not yet run
completely.

Stepping
Visual Basic provides several built-in methods for controlling the execution of the
program in real time. It is possible to execute the program line by line or procedure by
procedure or a combination of the two. These basic debugging actions are called Stepping.
Because it enables the developer to walk through the program, examining the variables and
logic, stepping is the most powerful debugging tool offered by Visual Basic. The various
debugging commands are discussed below.

Step Into: Execute the next executable line of the code in the application and steps into
procedures. This enables to check every line of code as it is being executed. This option can
be accessed from debug menu or by pressing F8.

Step Over: Execute the next executable line of the code in the application without stepping
into procedure. The procedure the user steps over does execute, but Visual Basic does not
walk through the stepped-over procedure line-by-line. Shortcut key is Shift+F8.

Step Out: Moves program execution back to the calling procedure. This is the functional
equivalent of Exit sub or Exit Function. It is simple exits the current procedure without
executing any more code in that procedure.

Set Next: Enables the user to move program execution to any executable line of code in the
current procedure.
While debugging an application, we should clearly understand which of the three modes
such as design time, run time or break mode we are in at a given time. Break mode of an
application is viewed by clicking CTRL+BREAK at run time.

39
Using the Debugging Window
Debug window is one of Visual Basic’s window that allows to run individual
commands immediately, by typing in the command and pressing the Enter key. It
automatically opens at run time.
1. In break mode, the debug window can be used to execute individual line of code,
View or change values of variables and properties, and view watch expressions.
2. At run time, it can be used to display data or messages as the programs as the
program runs.
3. At design time, the developer can view the previous output to the Debug window,
but cannot execute code.
The debug window has two part- Watch window and immediate window. The split bar
separates the Debug window into two panes. The upper pane display the Watch Window.
The lower pane display the Immediate Window.

Watch Window
Watch pane displays the current watch expressions, which are expressions whose
values are decided by the user as code is executed. The Watch pane appears automatically if
the watch expressions are defined in the project. At times we want to monitor the value of a
variable for a certain state- for example to determine weather a flag is set to True or False.
Steps to add watch expression
1. Add watch command is chosen from the Debug menu.
2. The Expression is entered in the Expression box.
3. If necessary, the scope of the variables is set and an option button is selected.
4. The OK button is clicked.

Immediate Window
The immediate pane appears by default the first time the debug window is opened.
From break mode, the code is executed immediately by entering it in this pane. This
window is the right place for the users to modify data or test functions during development.
We can enter any valid expression in this window and VB will execute it. If a reference is
made to an object outside the scope of the current code execution, Visual Basic will
generate an error.

Testing data and procedure in Immediate Pane


While debugging an application, Sometimes it may necessary to execute individual
procedures, evaluate expressions or assign new values to the variables or properties. The
Immediate Pane can be used to accomplish new values to the variables or properties. The
Immediate Pane can be used to accomplish such tasks. Expressions can be evaluated by
printing in Immediate Pane. Some advantages of these facility.
• The data or message can be viewed at run time.
• Feedback is displayed in separate area, so that it does not interfere with the output that
the user is seeing.
• Since the coding is saved as part of the form, these statements needs not be redefined
the next time we work on the
application.
e.g.
Private sub Form_load( )
Dim a as integer
Dim b, c as integer
A = 10
B= 6
C=a–b

40
Msgbox “Value of c is “ & C
[Link] “ Value of c is :” & c
End sub

On executing the above code the value of c is displayed in the Immediate window using the
[Link] statement.

Using a Breakpoint to selectively Halt Execution


At run time, a breakpoint tells VB to halt before executing a specific line of code. A
breakpoint can be set or removed at design time or at break mode. To set or remove a
breakpoint,
The insertion point is moved to the line of code where the breakpoint is to be set or
removed.
The Toggle Breakpoint is chosen from the Debug Menu or Toggle button is chosen in the
Toolbar or press shortcut key F9.
Writing Error Handlers
Visual Basic has specific built-in ways to handle runtime errors, called trappable
errors. When such an error occurs, you can direct the execution of your program to an error
handler, which is a section of code written specifically to deal with errors.

On Error GoTo Label.


The visual basic On error Goto statement is the foundation of handling trappable
errors. When you execute an On Error GoTo Label Statement in your code. Execution is
transferred to the code starting at label if a trappable error has occurred. The code following
that label is your error handler.
Private Sub Form_Load()
Dim a, b, c As Integer
On Error GoTo diverror
a = 10
b=0
c=a/b
MsgBox "Value of C =: " & c
diverror:
MsgBox "Divided by Zero Error", vbCritical, "Error"
End Sub
In this example value of b is zero, if don’t trap error then our program is terminate with an
error, but in this we trap error and give appropriate Message to user.

Err :
It is a object Contains information about run-time errors. When a run-time error
occurs, the properties of the Err object are filled with information that uniquely identifies
the error and information that can be used to handle it. To generate a run-time error in your
code, use the Raise method.
Main Properties of Err object
[Link] : Return error number
[Link] : Return error description
e.g. you may show this error message in program.

MsgBox "Des: " & [Link] & "NUMBER : " & [Link]

On Error GoTo line#

41
Besides using a label to start an error handler, you can refer to an error handler by line
number in visual basic, using on error goto line# statement.
e.g.

1 Private Sub Form_Load()


2 Dim a, b, c As Integer
3 On Error GoTo 8
4 a = 10
5 b=0
6 c=a/b
7 MsgBox "Value of C =: " & c
8 MsgBox "Divided by Zero Error", vbCritical, "Error"
9 End Sub

Using On Error Resume Next


The On Error Resume Next statement provides an easy way to disregard errors, if
you want to do so. Once you execute this statement, execution continues with the next line
of code if the current line generates an error, and the error is disregarded.

On Error GoTo 0
To turn off error trapping, you can use the On Error GoTo 0 statement.

Err Function
Returns a Variant of subtype Error containing an error number specified by the user.
Syntax
CVErr(error number)
The required errornumber argument is any valid error number.
Remarks
Use the CVErr function to create user-defined errors in user-created procedures.
For example, if you create a function that accepts several arguments and normally returns a
string, you can have your function evaluate the input arguments to ensure they are within
acceptable range. If they are not, it is likely your function will not return what you expect.
In this event, CVErr allows you to return an error number that tells you what action to take.
Note that implicit conversion of an Error is not allowed. For example, you can't
directly assign the return value of CVErr to a variable that is not a Variant. However, you
can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by
CVErr and assign that to a variable of the appropriate data type.
e.g
Sub Test()
[Link] CalculateDouble("345.45robert")
End Sub
' Define CalculateDouble Function procedure.
Function CalculateDouble(Number)
If IsNumeric(Number) Then
CalculateDouble = Number * 2 ' Return result.
Else
CalculateDouble = CVErr(2001) ' Return a user-defined error
End If ' number.
End Function

42
10.0 FILES
10.1 SEQUENTIAL ACCESS

Sequential files are like tape cassettes—you read data from them in a sequential manner. If
you want data at the end of the file, you have to read all the intervening data first.
Sequential files are often organized into text strings in Visual Basic. Here are the Visual
Basic statements and functions you use with sequential files (the # symbol refers to an open
file, as we’ll see):

• Open
• Line Input #
• Print #
• Write #
• Input$
• Input #
• Close

In addition, Visual Basic supports TextStream objects to make working with sequential files
easier, as we’ll see later in this chapter. Here are the major TextStream methods:

• Read
• ReadAll
• ReadLine
• Write
• WriteBlankLines
• WriteLine
• Close

When do you use sequential files? If you’ve got a text file full of variable-length strings,
you usually treat that file as sequential. You can also use sequential files to store binary-
format items like numbers.

10.2 Random Access Files

If sequential files are like cassettes, random access files are more like CDs. Random files
are organized into records (usually of the same length), and you can read a particular record
without having to read all the intervening data—you can move to that record in a file
directly, just as you can move to a CD track.

Here are the Visual Basic statements and functions you use with random access files:

• Type…End Type (to create and format records)


• Open
• Put #
• Len
• Seek
• LOC
• Get #
• Close

43
When do you use random access files? If you want to create your own database files,
formatted as you want them, you’d organize them into records. In fact, any file that you
want to organize into records is best formatted as a random access file.

Binary Files

Binary files are simply unformatted binary data, and Visual Basic does not interpret (such
as looking for text strings) or organize the contents (into records) of such files at all. These
files are just bytes to Visual Basic, and the statements and functions you usually use with
these files include the following:

• Open
• Get
• Put
• Seek
• Close

Binary files include EXE files, graphics files, and so on.

10.3 CREATING A FILE

The Testing Department is on the phone again. Your new SuperDuperTextPro word-
processing program is great, but shouldn’t it offer users some way to save their text in a
file? Hmm, you think, could be a good idea.

So how do you create a file in Visual Basic? The standard way is to use the Open statement
(we’ll see another way when we work with TextStream objects later in this chapter). Here’s
how the Open statement works:

Open pathname For mode [Access access] [lock] As [#] filenumber [Len=
reclength]

Here are what the various arguments mean:

• pathname—A file name (may include directory or folder, and drive).


• mode—A keyword specifying the file mode: Append, Binary, Input, Output, or
Random (if unspecified, the file is opened for Random access).
• access—A keyword specifying the operations permitted on the open file: Read,
Write, or Read Write.
• lock—A keyword specifying the operations restricted on the open file by other
processes: Shared, Lock Read, Lock Write, and Lock Read Write.
• filenumber—A valid file number in the range 1 to 511, inclusive. Use the FreeFile
function to obtain the next available file number.
• reclength—A number less than or equal to 32,767 (bytes). For files opened for
random access, this value is the record length. For sequential files, this value is the
number of characters buffered.

If the file is already opened by another process and the specified type of access is not
allowed, the Open operation fails and an error occurs. Also note that the Len clause is
ignored if mode is Binary.

44
So how do you create a file with Open? If the file specified by pathname doesn’t exist, it is
created when a file is opened for Append, Binary, Output, or Random modes. After
you’ve created the file, you refer to it using the file number.

Let’s see an example. Here, we’ll let users write the text in a text box, Text1, to a file on
disk, [Link], when they press a button. Because file operations are prone to error (we might
run into missing diskettes, locked files, and so on), we start by checking for errors:

Private Sub Command1_Click()


On Error GoTo FileError
...
FileError:
MsgBox "File Error!"
End Sub

Next, we create [Link] as file #1:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1
...
FileError:
MsgBox "File Error!"
End Sub

Now we write the text in Text1 to the file with the Print # method:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1
Print #1, [Link]
...
FileError:
MsgBox "File Error!"
End Sub

And finally we close the file:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1
Print #1, [Link]
Close #1
Exit Sub

FileError:
MsgBox "File Error!"
End Sub

When you add a text box, Text1, to the form, and a command button, Command1, labeled
“Write text to file”, and run the program, you see the display much like that in Figure 17.3.
When you click the command button, the new file is created and written.

Getting A File’s Length

When you start reading files in code, it can help to know the file’s length (for one thing, it
can tell you how many bytes to read in). There are two ways to determine file length, the
FileLen and the LOF functions.

45
The FileLen Function

The FileLen function returns the length of a file (in bytes) on disk. Here’s an example in
which we report the size of a file, [Link], in a message box using FileLen:

Private Sub Command1_Click()


MsgBox "The [Link] file is" & Str(FileLen("c:\[Link]")) & _
" bytes long."
End Sub

The LOF Function

The LOF function returns the length of a file (in bytes) opened with the Open statement.
You pass the LOF function an open file number. Here’s an example in which we report the
length of a file we’ve just written, using the LOF function:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1
Print #1, [Link]
MsgBox "The file is" & Str(LOF(1)) & " bytes long."
Close #1
Exit Sub

FileError:
MsgBox "File Error!"
End Sub

10.4 Opening A File

How do you open a file in Visual Basic? You use the Open statement. Here’s how the
Open statement works:

Open pathname For mode [Access access] [ lock] As [#] filenumber [Len=
reclength]

Here are what the various arguments mean:

• pathname—A file name (may include directory or folder, and drive).


• mode—A keyword specifying the file mode: Append, Binary, Input, Output, or
Random (if unspecified, the file is opened for Random access).
• access—A keyword specifying the operations permitted on the open file: Read,
Write, or Read Write.
• lock—A keyword specifying the operations restricted on the open file by other
processes: Shared, Lock Read, Lock Write, and Lock Read Write.
• filenumber—A valid file number in the range 1 to 511, inclusive. Use the FreeFile
function to obtain the next available file number.
• reclength—Number less than or equal to 32,767 (bytes). For files opened for
random access, this value is the record length. For sequential files, this value is the
number of characters buffered.

If the file is already opened by another process and the specified type of access is not
allowed, the Open operation fails and an error occurs. Also note that the Len clause is
ignored if mode is Binary . If the file specified by pathname doesn’t exist, it is created
when a file is opened for Append, Binary, Output, or Random modes. If you open an
46
existing file for Output, it is overwritten; if you open it for Append, new data is added to
the end of the file. After you’ve created the file, you refer to it using the file number.

For example, here we open a file named [Link] and write the contents of a text box, Text1,
to that file:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1
Print #1, [Link]
Close #1
Exit Sub

FileError:
MsgBox "File Error!"
End Sub

10.5 Writing To A File

Writing To A Sequential File

Sequential files are often text strings in Visual Basic, but they can also be combinations of
text and numbers. You usually use these standard statements to write to sequential files in
Visual Basic (we’ll also see how to use the TextStream methods later in this chapter):

Print # number, expressionlist


Write # number, expressionlist

Here, number is an open file number and expressionlist is a list of variables to write,
separated by commas. Let’s take a look at some examples.

The Print # Statement

If you want to store your data in text format, use Print # . As an example, we’ll store the
text in a text box to a file named [Link] using Print # . We start by checking for errors:

Private Sub Command1_Click()


On Error GoTo FileError
...
FileError:
MsgBox "File Error!"
End Sub

Then we open a file for output:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1
...
FileError:
MsgBox "File Error!"
End Sub

Then we print the text in a text box, Text1, to the file:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1

47
Print #1, [Link]
...
FileError:
MsgBox "File Error!"
End Sub

Finally we close the file:

Private Sub Command1_Click()


On Error GoTo FileError
Open "c:\[Link]" For Output As #1
Print #1, [Link]
Close #1
Exit Sub

FileError:
MsgBox "File Error!"
End Sub

And that’s it—now the user can write the contents of a text box out to disk. The code for
this is located in the filewrite folder on this book’s accompanying CD-ROM.

The Write # Statement

You can also use the Write # statement to write text and other types of data to a file. You
use this statement with a file number and a comma-delimited list of the variables you want
to write to that file. For example, here we open a file, [Link], and write two numbers that
the user has entered in the text boxes Text1 and Text2 to that file:

Private Sub Command1_Click()


Open "c:\[Link]" For Output As #1
Write #1, Val([Link]), Val([Link])
Close #1
End Sub

To see how to read those values back in, take a look at “Reading From Sequential Files”
coming up in this chapter.

Writing To A Random Access File

You usually write records to random access files using the Put statement:

Put [#] filenumber, [recnumber ], varname

Here, filenumber is the number of a file to write to, recnumber is the number of the record
to write (you set the record size when you open the file), and varname is the name of the
variable that holds the data to write to the file.

To work with records in a random access file, you define a record type first. For example,
here we define a new type named Record in a module (you can only define types in
modules; to add a new module to a program, use the Project menu’s Add Module item):

Type Record
Name As String * 50
Number As String * 50
End Type

48
Note that we use fixed-length strings here to make all our records the same size.

Now in a program, we can set up an array of such records in the (General) part of a form, as
well as an integer to keep track of the total number of records:

Dim WriteData(1 To 50) As Record


Dim TotalRecords As Integer

In this example, we’ll just have one record, which we fill from the text boxes Text1 and
Text2 when the user clicks a button:

Private Sub Command1_Click()


WriteData(1).Name = [Link]
WriteData(1).Number = [Link]
TotalRecords = 1
...

Next, we create a file to store our record(s) in—note that we set the size of each record in
the file with the Len keyword:

Private Sub Command1_Click()


WriteData(1).Name = [Link]
WriteData(1).Number = [Link]
TotalRecords = 1

On Error GoTo FileError


Open "c:\[Link]" For Random As #1 Len = Len(WriteData(1))
...
FileError:
MsgBox "File Error!"
End Sub

Finally, we use the Put statement to write the data to the file. We only have one record here,
but if we had a number of records, we could loop like this:

Private Sub Command1_Click()


WriteData(1).Name = [Link]
WriteData(1).Number = [Link]
TotalRecords = 1

On Error GoTo FileError


Open "c:\[Link]" For Random As #1 Len = Len(WriteData(1))
For loop_index = 1 To TotalRecords
Put #1, , WriteData(loop_index)
Next loop_index
Close #1
Exit Sub

FileError:
MsgBox "File Error!"

End Sub

And that’s it—we’ve written our data file. To see how to read records back in, see “Reading
From Random Access Files” later in this chapter.

Writing To A Binary File

49
You usually write records to binary files using the Put statement:

Put [#] filenumber, [recnumber], varname

Here, filenumber is the number of a file to write to, recnumber is the number of the record
to write for random files and the byte at which to start writing for binary files, and varname
is the name of the variable that holds the data to write to the file.

Here’s an example showing how to use Put to write a floating point number the user has
entered in a text box, Text1, to a file—note that we open that file in Binary mode and don’t
use a record number with Put here:

Private Sub Command1_Click()


Dim varOutput As Double
varOutput = Val([Link])

On Error GoTo FileError


Open "c:\[Link]" For Binary As #1
Put #1, , varOutput
Close #1
Exit Sub

FileError:
MsgBox "File Error!"
End Sub

To see how to read the binary data back in, see “Reading from Binary Files” later in this
chapter.

10.7 Reading From A Files

Reading From Sequential Files

To read from sequential file, you can use these standard statements (we’ll see how to use
TextStream methods later in this chapter):

Input # number, expressionlist


Line Input # number, string
Input$ ( numberbytes, [#] number)

Here, number is a file number, expressionlist is a list of variables the data will be stored in,
string is a string variable to store data in, and numberbytes is the number of bytes you want
to read. Let’s see some examples.

The Input # Statement

You can use the Input # statement to read text and numbers from a sequential file. For
example, if we write two integers the user has entered in Text1 and Text2 to a file, [Link],
this way using Write # when the user clicks Command1:

Private Sub Command1_Click()


Open "c:\[Link]" For Output As #1
Write #1, Val([Link]), Val([Link])
Close #1
End Sub

50
then we can read those integers back using Input # this way when the user clicks
Command2:

Private Sub Command2_Click()


Dim int1, int2 As Integer

Open "c:\[Link]" For Input As #1


Input #1, int1, int2
[Link] = Str(int1)
[Link] = Str(int2)
Close #1

End Sub

The Line Input Statement

Using the Line Input statement, you can read lines (text strings that end with a carriage
return or carriage return/line feed pair) from a file. For example, say we had this set of lines,
each separated by a carriage return/line feed pair in a file named [Link]:

Here is some
multi-line text
that we
will read in...

When the user clicks a button, we can read in the preceding text line by line with Line
Input . First, we open the file:

Private Sub Command1_Click()

On Error GoTo FileError


Open "c:\[Link]" For Input As #1
...
FileError:
MsgBox "File Error!"
End Sub

Now we need some way of looping over all the lines in the file—but how do we know when
we’ve reached the end of the file? We use the Visual Basic EOF (End Of File) function,
which returns True when we reach the end of the file:

Private Sub Command1_Click()

On Error GoTo FileError


Open "c:\[Link]" For Input As #1
Do Until EOF(1)
...
Loop

Exit Sub

FileError:
MsgBox "File Error!"
End Sub

Next we use Line Input to read lines of text from the file and append them to a multiline
text box (that is, a text box with its MultiLine property set to True), Text1, along with a
carriage return line feed pair this way:

51
Private Sub Command1_Click()
Dim NewLine As String

On Error GoTo FileError


Open "c:\[Link]" For Input As #1
Do Until EOF(1)
Line Input #1, NewLine
[Link] = [Link] + NewLine + vbCrLf
Loop

Exit Sub
FileError:
MsgBox "File Error!"
End Sub

The Input$ Statement

The Input$ statement lets you read in a string of a specified length. It might seem odd to
have to know the strings’ lengths before reading them in, but Input$ does have one very
useful aspect: if you use it together with the LOF (Length Of File) function, you can read in
a whole text file at once.

For example, here’s how we read in the file from the previous example, [Link], all at once,
without having to work line by line:

Private Sub Command1_Click()


Dim NewLine As String

On Error GoTo FileError


Open "c:\[Link]" For Input As #1

[Link] = Input$(LOF(1), #1)

Exit Sub
FileError:
MsgBox "File Error!"
End Sub

This example produces the same result as the previous example that uses Line Input.

Reading From Random Access Files

The Testing Department is on the phone. Your new program, SuperDuperDataCrunch, is


great for writing data to disk, but shouldn’t you let the user read that data back in? Hmm,
you think, good idea.

You use Get to read records from a random access file:

Get [#] filenumber, [recnumber], varname

Here, filenumber is the number of a file to read from, recnumber is the number of the record
to read, and varname is the name of the variable that should receive the read-in data.

Let’s see an example. Earlier in this chapter, we saw how to write records to a random
access file. We set up a new type named Record in a module:

Type Record
Name As String * 50

52
Number As String * 50
End Type

Then we set up two formwide arrays of records, WriteData and ReadData, and an integer
named TotalRecords to keep track of how many records are total (these variables are stored
in the (General) section of the form):

Dim WriteData(1 To 50) As Record


Dim ReadData(1 To 50) As Record
Dim TotalRecords As Integer

When the user clicked a command button, we read the text from two text boxes, Text1 and
Text2, placed that text in the first record of the WriteData array, and wrote that record out
to a file named [Link] with the Put statement:

Private Sub Command1_Click()


WriteData(1).Name = [Link]
WriteData(1).Number = [Link]
TotalRecords = 1

On Error GoTo FileError


Open "c:\[Link]" For Random As #1 Len = Len(WriteData(1))
For intLoopIndex = 1 To TotalRecords
Put #1, , WriteData(intLoopIndex)
Next intLoopIndex
Close #1
Exit Sub

FileError:
MsgBox "File Error!"

End Sub

Now we’ll see how to read that record back in. First, we open the file [Link] for
random access, setting the record size to the length of each array element:

Private Sub Command2_Click()

Open "c:\[Link]" For Random As #1 Len = Len(ReadData(1))


...

Then we use Get to read in the records:

Private Sub Command2_Click()


Dim intLoopIndex As Integer

Open "c:\[Link]" For Random As #1 Len = Len(ReadData(1))


For intLoopIndex = 1 To LOF(1) / Len(ReadData(1))
Get #1, , ReadData(intLoopIndex)
Next intLoopIndex

Next, we loop over all the records in the file (although we use LOF(1) / Len(ReadData(1))
to determine the number of records in the file, we could also loop until the EOF function is
True):

Private Sub Command2_Click()


Dim intLoopIndex As Integer

Open "c:\[Link]" For Random As #1 Len = Len(ReadData(1))

53
For intLoopIndex = 1 To LOF(1) / Len(ReadData(1))
...
Next intLoopIndex
...

Then we close the file and display the Name and Number fields of the first (and only)
record in two new text boxes, Text3 and Text4:

Private Sub Command2_Click()


Dim intLoopIndex As Integer

Open "c:\[Link]" For Random As #1 Len = Len(ReadData(1))

For intLoopIndex = 1 To LOF(1) / Len(ReadData(1))


Get #1, , ReadData(intLoopIndex)
Next intLoopIndex

Close #1

[Link] = ReadData(1).Name
[Link] = ReadData(1).Number

Exit Sub

FileError:
MsgBox "File Error!"
End Sub

Reading From Binary Files

How do you read raw data from files that have been opened in Binary format with the
Open statement? You usually use Get to read data from a binary file (although you can use
Input # as well—see the previous topic on reading from sequential files):

Get [#] filenumber, [recnumber], varname

Here, filenumber is the number of a file to read from, recnumber is the number of the record
to read for random files and the byte at which to start reading for binary files, and varname
is the name of the variable that will hold the read-in data.

Let’s see an example. In this case, we first write some binary data—such as a floating point
number—to a file, and then we’ll read it back in. Here, we let the user enter a Double value
in a text box, which we read in when the user clicks a command button, Command1:

Private Sub Command1_Click()


Dim varOutput As Double
varOutput = Val([Link])
...

Then we write that number out to a binary file, [Link] (making it a binary file by
opening it in Binary mode):

Private Sub Command1_Click()


Dim varOutput As Double
varOutput = Val([Link])

On Error GoTo FileError


Open "c:\[Link]" For Binary As #1
Put #1, , varOutput
Close #1
54
Exit Sub

FileError:
MsgBox "File Error!"
End Sub

Now it’s up to us to read that number back in as binary data when the user clicks a new
button, Command2 . We start by opening the file again:

Private Sub Command2_Click()

On Error GoTo FileError


Open "c:\[Link]" For Binary As #1
...
FileError:
MsgBox "File Error!"
End Sub

Next, we use Get to read in the number and store it in a new variable, varInput:

Private Sub Command2_Click()


Dim varInput As Double
On Error GoTo FileError
Open "c:\[Link]" For Binary As #1
Get #1, , varInput
...
FileError:
MsgBox "File Error!"

End Sub

Finally, we display the newly read-in variable in a text box, Text2, and close the file:

Private Sub Command2_Click()


Dim varInput As Double

On Error GoTo FileError


Open "c:\[Link]" For Binary As #1
Get #1, , varInput
[Link] = Str(varInput)
Close #1
Exit Sub

FileError:
MsgBox "File Error!"

End Sub

10.7 Accessing Any Record In A Random Access File

When you’ve set up a file to hold records (by creating it in Random mode with the Open
statement and passing the length of the records you want to open), you can use Get to
access any record in the file by record number:

Get #1, recordnumber, variablename

In this case, we’re reading record number recordnumber from file 1 and placing the data
read into a variable named variablename . In the same way, you can write any record with
Put:

55
Put #1, recordnumber, variablename

Using Get and Put in this way, you can read and write any record in the file.

Closing A File

How do you close a file in Visual Basic? It’s simple—you just use the Close statement:
Private Sub Command1_Click()
On Error GoTo FileError
Open "c:\[Link]" For Output As #1
Print #1, [Link]
Close #1
Exit Sub
FileError:
MsgBox "File Error!"
End Sub

56
PROGRAMMING IN VISUAL BASIC
SAMPLE PROGRAMS
TASK ONE
Conversion
1. Open a project and add a new form by
➢ Click at the project menu
➢ Click at add form
➢ Click at open
2. Set properties for the form as
Name Frmsamples
Caption Conversions
3. Put a command on the form and set the properties as
Name cmdbase
Caption Change of bases
4. Double click at the Command then type the following code
Private Sub CMDBASE_Click()
‘Program to demonstrate change of bases
Dim num1, num2, num3, num4, num5 As Long
num1 = InputBox("Enter a decimal number", "Change of Bases", 0, 21, 4)
num2 = Hex(num1)
num3 = Oct(num1)
MsgBox ("Your number in Hexadecimal is " & num2)
MsgBox ("Your number in octal is " & num3)
End Sub
5. Save and run the program

TASK TWO
Use of date
1. Open a project and add a new form
2. Set properties for the form as
Name Frmsamples
Caption Conversions
3. Put a command on the form and set the properties as
Name cmddate
Caption Working with dates
4. Add Four labels and four Textboxes on the form and set there properties as
For label For Textbox
Name Caption Name
Lblday Day Txtday
Lblyear Year Txtyear
Lblmonth Month Txtmonth
Lblweek Weekday Txtweek

5. Double click at the Command then type the following code


Private Sub CMDDATE_Click()
'Program to demonstrate the the use of date
Dim dates As Date
Dim d, m, y, w As Long
dates = InputBox("Enter any date of he year", "Use of Dates", "1/1/04", 23,
30)
57
d = Day(dates)
m = Month(dates)
y = Year(dates)
w = Weekday(dates)
txtday = d
txtmonth = m
txtyear = y
txtweek = w
End Sub
6. Save and run the program

TASK THREE
Use of string data type
1. Open a project and add a new form
2. Set properties for the form as
Name Frmsamples
Caption Handling of strings
3. Put a command on the form and set the properties as
Name cmdstring
Caption strings
4. Add 3 labels and 3 Textboxes on the form and set there properties as
For label For Textbox
Name Caption Name
Lbllower Lower TxtLower
Lblupper Upper TxtUpper
Lbllength Length TxtLength
5. Double click at the Command then type the following code
Private Sub CMDSTRING_Click()
'Program to demonstrate the use of strings
Dim fstring As String
Dim message, title As String
Dim t As Integer
fstring = InputBox("Enter any word of your choice", "Use of Strings",
"Coming Home", 34, 67)
message = "The length of the string is " & Len(fstring) & " Characters"
title = " The number of characters"
t = 4096 + 48
MsgBox message, t, title
txtlower = LCase(fstring)
txtupper = UCase(fstring)
txtlenght = Len(fstring)
End Sub
6. Save and run the program

TASK FOUR
Use of arithmetic operrators
1. Open a project and add a new form
2. Set properties for the form as
Name Frmoperators
Caption Arithmetic Operators
3. Add 3 labels and 3 Textboxes on the form and set there properties as
For label For Textbox
Name Caption Name

58
Lblfirst The first number Txtfirst
Lblsecond The Second number Txtsecond
Lblans Your answer is Txtans

4. Add 4 commands on the form and set there properties as follows

Name Caption
Cmdadd Add
Cmdsub Subtract
Cmddivide Divide
Cmdmultiply Multiply
5. Double click at each Command then type the following code
Add
Private Sub cmdadd_Click()
txtans = Val(txtfirst) + Val(txtsecond)
End Sub

Divide
Private Sub cmddivide_Click()
txtans = Val(txtfirst) / Val(txtsecond)
End Sub

Multiply
Private Sub cmdmultiply_Click()
txtans = Val(txtfirst) * Val(txtsecond)
End Sub

Subtract
Private Sub cmdsub_Click()
txtans = Val(txtfirst) - Val(txtsecond)
End Sub
6. Save and run the program

TASK FIVE
Use of Logical operators and if
A Use of Logical and Comparison operators
1 Add a command on the any form and set its properties to
Name Cmdif
Caption Compare Three numbers
2 Double click the command and type the following code

Private Sub CMDif_Click()


'Program to compare Three Numbers Use of If, Comparison ans logical operators
Dim a, b, c As Integer
Dim message, title As String
Dim t As Integer

a = InputBox("Enter the first number", "The First number", 0, 45, 70)


b = InputBox("Enter the second number", "The Second number", 0, 45, 70)
c = InputBox("Enter the Third number", "The Third number", 0, 45, 70)
If a > b And a > c Then
message = "The greater number is " & a

59
title = " The bigger number"
t = 4096 + 16 + 64
MsgBox message, t, title
ElseIf b > a And b > c Then
message = "The greater number is " & b
title = " The bigger number"
t = 4096 + 48
MsgBox message, t, title
ElseIf c > a And c > b Then
MsgBox "The bigger Number is " & c
Else
MsgBox ("Two or all the numbers are equal")
End If
End Sub
6 Save and Run the program
B Use of Xor
1 Add a command on the any form and set its properties to
Name Cmdxor
Caption XOR
2 Double click the command and type the following code

Private Sub cmdxor_Click()


‘Program to demonstrate the use of xor
Dim Y, X, Z As Integer
Dim message, title As String
Dim t As Integer
Y = InputBox("Enter the first number", "The First number", 0, 45, 70)
X = InputBox("Enter the second number", "The Second number", 0, 45, 70)
Z = InputBox("Enter the third number", "The Third number", 0, 45, 70)
If Y > X Xor Y > Z Then
message = " " & Y & " is greater " & X & " But Less than " & Z
title = " Use of xor"
t = 4096 + 64
MsgBox message, t, title
End If
End Sub

C Use of msgbox and if


1 Add a command on the any form and set its properties to
Name CmdMsgBoxandIf
Caption Use of Msgbox and If
2 Double click the command and type the following code
Private Sub cmdmsgboxif_Click()
'Program to give the use chance of adding or subtracting
Dim num1, num2, ans As Single
num1 = InputBox("Enter the first number", "The First number", 0, 60, 34)
num2 = InputBox("Enter the second number", "The Second number", 0, 45, 70)
If MsgBox("Do you want to Add the two number ?", vbYesNo, "Use of MsgBox
and If")_ = vbYes Then
ans = Val(num1) + Val(num2)
MsgBox "The Numbers were added the sum is " & ans
Else
ans = num1 - num2

60
MsgBox "The Numbers were Subtracted The Answer is " & ans
End If
End Sub

TASK SIX
Use of Select Case
A
1 Add a command on the any form and set its properties to
Name Cmdselect1
Caption Use of select Case 1
2 Double click the command and type the following code
Private Sub Cmdselect1_Click()
'Program to Determine the grade of the student marks
Dim Marks As Long
Marks = InputBox("Enter the marks for the student", "Marks for the student", 0, 34,
70)
Select Case Marks
Case 0 To 39
MsgBox ("The Grade is Fail")
Case 40 To 59
MsgBox ("The Grade is Pass")
Case 60 To 79
MsgBox ("The Grade is Credit")
Case 80 To 100
MsgBox ("The Grade is Dist")
Case Else
MsgBox ("The marks are out of range")
End Select
End Sub

B
1 Add a command on the any form and set its properties to
Name Cmdselect2
Caption Use of select Case 2
2. Add a textbox name it txtcolour and a label: name Lblcolour and Caption The
colour and arrange them appropriately

3 Double click the command and type the following code


Private Sub Cmdselect2_Click()
'Program to demonstrate the use of Select ansd Colour
Dim colname As String
colname = InputBox("Enter the name of the colour you need", "Enter the
Colour Name")
colname = Trim(UCase(colname)) 'Trimming excess spaces and changing to
upper case
Select Case colname
Case Is = "BLUE"
[Link] = vbBlue
Case Is = "GREEN"
[Link] = vbGreen
Case Is = "YELLOW"
[Link] = vbBYELLOW
Case Is = "BLACK"

61
[Link] = vbBlack
Case Is = "RED"
[Link] = vbRed
Case Else
[Link] = vbWhite
[Link] = "UNKNOWN COLOUR"
End Select
End Sub

C
Use of Select and MsgBox
1 Add a command on the any form and set its properties to
Name Cmdselect3
Caption Use of select and Msgbox
2 Double click the command and type the following code
Private Sub cmdselect3_Click()
'Program to demonstrate the use of msgBox and the value
Dim t, reply As Integer
Dim number1, number2, ans As Integer
stop1:
number1 = InputBox("Enter the first number", "The First number", 0, 60, 34)
number2 = InputBox("Enter the second number", "The Second number", 0, 45, 70)
If number1 < 1000 Or number2 < 1000 Then
t = 32 + 2
reply = MsgBox("You have not entered the correct numbers They should be a
bove_ 1000", t, "quit")
Select Case reply
Case Is = 3
MsgBox " you have chosen Abort"
End
Case Is = 5
MsgBox " you have chosen Ignore"
ans = number1 * number2
MsgBox " your answer is " & ans
Case Is = 4
MsgBox " you have chosen Retry"
GoTo stop1
End Select
End If
End Sub

TASK SEVEN
Use of Repetition Control Structures
A For…. Next (i)
1 Add a command on the any form and set its properties to
Name CmdFornext
Caption For Next 1
2 Double click the command and type the following code
Private Sub cmdfornext_Click()
'Program to add ten numbers
Dim num, sum As Long

62
Dim i As Integer
sum = 0
For i = 1 To 10
num = InputBox("Enter a number")
sum = sum + num
Next i
MsgBox "The sum is " & sum
End Sub

A For…. Next (II)


1 Add a command on the any form and set its properties to
Name CmdFornext2
Caption For Next 2
2 Double click the command and type the following code
Private Sub cmdfornext2_Click()
'Program to Output Odd integers on the form
Dim i As Integer
For i = 1 To 20 Step 2
Print i
Next i
End Sub

B Do While
1 Add a command on the any form and set its properties to
Name Cmddowhile
Caption Do While
2 Double click the command and type the following code
Private Sub cmddowhile_Click()
'Program to Determine the grade of the student marks
Dim Marks, d, f, p, o, c As Long
Marks = 0
Do While Marks <> -1
Marks = InputBox("Enter the marks for the student Enter -1 to stop", "Marks for
the student", 0, 34, 70)
Select Case Marks
Case 0 To 39
f=f+1
Case 40 To 59
p=p+1
Case 60 To 79
c=c+1
Case 80 To 100
d=d+1
Case Else
o=o+1
End Select
Loop
MsgBox ("The Fails are " & f)
MsgBox ("The Passs are " & p)
MsgBox ("The Credits are " & c)
MsgBox ("The Dist are" & d)
MsgBox ("The out of range are " & o)

63
End Sub

C Do Until
1 Add a command on the any form and set its properties to
Name Cmddountil
Caption Do Until
2 Double click the command and type the following code
Private Sub cmddountil_Click()
'Program to add ten numbers using Do until loop
Dim num, sum As Long
Dim i As Integer
Dim t As Boolean
sum = 0
t = False
Do
num = InputBox("Enter a number")
sum = sum + num
If MsgBox("Do you want to stop", vbYesNo, "Continue") = vbYes Then
t = True
End If
Loop Until t
MsgBox "The sum is " & sum
End Sub
D While Wend
1 Add a command on the any form and set its properties to
Name CmdWhileWend
Caption While Wend
2 Double click the command and type the following code
Private Sub cmdwhilewend_Click()
'program to determine the largest from Ten numbers
Dim number, big As Double
Dim k As Integer
k=1
number = InputBox("Enter the first number", "The First Number", 0, 45, 78)
big = number
While k < 10
k=k+1
number = InputBox("Enter the Next number", "The Next Number", 0, 45, 78)
If number > big Then
big = number
End If
Wend
MsgBox ("The bigger number is " & big)
End Sub

TASK EIGHT
Use of Arrays and User defined data type
A Arrays (ONE Dimensional)
1. Open a project and add a new form by
➢ Click at the project menu
➢ Click at add form

64
➢ Click at open
2. Set properties for the form as
Name Frmsamples
Caption Arrays and User defined
3. Add a command on the form and set the properties as
Name cmdarray1
Caption One Dimensional array 1

4. Double click the command and type the following code

Private Sub cmdarray1_Click()


'Program to Input ten values in an array
Dim num(10) As Long
'Input of the Ten numbers
For i = 1 To 10
num(i) = InputBox("Enter a number")
Next i
'Output of the ten numbers on the form
For i = 1 To 10
Print num(i)
Next i

End Sub
B Arrays Use of Redim Statement
1. Add a command on the form and set the properties as
Name cmdarray2
Caption One Dimensional array 2

2. Double click the command and type the following code


Private Sub cmdarray2_Click()
'Program to demonstrate the use of redim Statemnet
Dim num() As Long
Dim k, i As Integer
k = InputBox("How many Values Do you want to enter", "Numbers", 10)
ReDim num(k)
'Input of the numbers
For i = 1 To k
num(i) = InputBox("Enter a number")
Next i
'Output of the ten numbers on the form
For i = 1 To k
Print num(i)
Next i

End Sub

C Arrays Two Dimensional array


1. Add a command on the form and set the properties as
Name cmdarray3
Caption Two Dimensional array
2. Double click the command and type the following code

Private Sub cmdarray3_Click()

65
'Program to Input values in a two dimensional array
Dim num(4, 4) As Long
Dim i, j As Integer
'Input of the numbers
For i = 1 To 4
For j = 1 To 4
num(i, j) = InputBox("Enter a number")
Next j
Next i
'Output of the ten numbers on the form
For i = 1 To 4
Print "The " & i; "Row"
For j = 1 To 4
Print num(i, j)
Next j
Next i
End Sub

D User defined type data


1. Add a command on the form and set the properties as
Name cmduser1
Caption User Defined
2. Double click the command and type the following code
Private Sub cmduser1_Click()
'Program todemonstrate input of one record and output using User defined
Dim studrec As student
'This is for input
[Link] = InputBox("Enter Your name")
[Link] = InputBox("Enter The admission Number of the student")
[Link] = InputBox("Enter The fees paid by the student")
'This is for output
MsgBox ("Your Name is " & [Link])
MsgBox ("Your admission number is " & [Link])
MsgBox ("Your fees is " & [Link])
End Sub

E User defined type data The use of With Structure


1. Add a command on the form and set the properties as
Name cmduser2
Caption User Defined & With structure
2. Double click the command and type the following code

Private Sub cmduser2_Click()


'Program to demonstrate input of one record and output using User defined and With
Structure
Dim studrec As student
'This is for input
With studrec
.name = InputBox("Enter Your name")
.admno = InputBox("Enter The admission Number of the student")
.fees = InputBox("Enter The fees paid by the student")
End With
'This is for output

66
MsgBox ("Your Name is " & [Link])
MsgBox ("Your admission number is " & [Link])
MsgBox ("Your fees is " & [Link])
End Sub

F User defined type data The use of Array


1. Add a command on the form and set the properties as
Name cmduser3
Caption User Defined & Array
2. Double click the command and type the following code
Private Sub Cmduser3_Click()
'Program to demonstrate input of one record and output using User defined
and With Structure
Dim studrc(10) As student
'This is for input
For i = 1 To 4
With studrc(i)
.name = InputBox("Enter Your name")
.admno = InputBox("Enter The admission Number of the student")
.fees = InputBox("Enter The fees paid by the student")
End With
Next i
'This is for output
For i = 1 To 4
With studrc(i)
Print .name & " " & .admno & " " & .fees
End With
Next i
End Sub

TASK NINE
Sup Programming in Visual Basic
A Use of procedure without Parameters
1. Add a command on the form and set the properties as
Name cmdsub1
Caption Subroutine
2. Type the following module in the General declaration area
Sub Traingle() 'Subroutine
Const t = 0.5
area = t * h * b
End Sub

3. Double click the command and type the following code


Private Sub cmdsub1_Click()
'Program used to calculate the area of a triangle using subroutines
'Note All the variables have been declared at form level general Declaration area
h = InputBox("Enter the height of the Triangle")
b = InputBox("Enter the base of the Triangle")
Call Traingle 'Calling a subroutine called adding
MsgBox ("Your answer is " & area) 'Note that area as a variable is declared at form
level ie General area
End Sub

67
B Use of procedure with Parameters
1. Add a command on the form and set the properties as
Name cmdsub2
Caption Subroutine With Parameters (ByVal)
2. Type the following module in the General declaration area
Sub Multiply(ByVal mult As Double, ByRef m1, m2 As Long)
mult = m1 * m2
MsgBox ("Your answer is " & mult) 'Can only be output in the procedure
End Sub
3. Double click the command and type the following code
Private Sub Cmdsub2_Click()
'program to Multiply two numbers using parameters
Dim ans As Double
Dim No1, no2 As Long
No1 = InputBox("Enter the first Number")
no2 = InputBox("Enter the Second Number")
Call Multiply(ans, No1, no2)
End Sub

C Use of procedure with Parameters both ByVal and ByRef


1. Add a command on the form and set the properties as
Name cmdsub3
Caption Subroutine with Parameters ByVal & ByRef
2. Type the following module in the General declaration area
Sub Multiply1(ByVal p1, p2 As Single, m2 As Double)
'Note p1 and p2 are Value Parameters and M2 is Reference Parameter
m2 = p1 * p2
End Sub
3. Double click the command and type the following code

Private Sub cmdsub3_Click()


'program to Multiply two numbers using parameters
Dim Number1, Number2 As Single
Dim m1 As Double
Number1 = InputBox("Enter the first Number")
Number2 = InputBox("Enter the Second Number")
Call Multiply1(Number1, Number2, m1)
MsgBox ("Your answer is " & m1)

End Sub

D Use of Function without Parameters


1. Add a command on the form and set the properties as
Name cmdfunct1
Caption Function
2. Type the following Function in the General declaration area
Function add() As Integer
add = a * b
End Function
3. Double click the command and type the following code
Private Sub Cmdfunct1_Click()
'Program Using Function to add two numbers

68
'Note a and b Must be declared in the general Declaration section
a = InputBox("Enter the first number")
b = InputBox("Enter The second nunmber")
MsgBox ("your answer is " & add)
End Sub

E Use of Function with Parameters


1. Add a command on the form and set the properties as
Name cmdfunct2
Caption Function with Parameters
2. Type the following module in the General declaration area
Function Aver(ByVal S1, S2, S3 As Long) As Double
Dim k, tot As Double 'This are local Variables
tot = Val(S1) + Val(S2) + S3
k = tot / 3
Aver = k
End Function
3. Double click the command and type the following code
Private Sub Cmdfunct2_Click()
'Program Using Function to get average of three numbers using parameters
Dim Nu1, Nu2, Nu3 As Long
Nu1 = InputBox("Enter the first number")
Nu2 = InputBox("Enter the second nunmber")
Nu3 = InputBox("Enter the third nunmber")
MsgBox ("your ans is " & Aver(Nu1, Nu2, Nu3))
End Sub

69

You might also like