Visual Basic Programming SCO127
Visual Basic Programming SCO127
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.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.
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.
5
and deployment wizard which automates the creation of the set up program and ensures the
user has all necessary files.
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
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.
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;
➢ 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.
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,
Amount% = 300
• 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
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:
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:
• 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:
• 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.
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
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.
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
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
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
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
General structure
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.
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.
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.
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
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.
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.
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
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.
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
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
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.
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.
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
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
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.
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
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.
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.
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.
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]
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.
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.
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:
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
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]
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:
Now we write the text in Text1 to the file with the Print # method:
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.
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:
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:
FileError:
MsgBox "File Error!"
End Sub
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]
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:
FileError:
MsgBox "File Error!"
End Sub
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):
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.
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:
47
Print #1, [Link]
...
FileError:
MsgBox "File Error!"
End 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.
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:
To see how to read those values back in, take a look at “Reading From Sequential Files”
coming up in this chapter.
You usually write records to random access files using the Put statement:
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:
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:
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:
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:
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.
49
You usually write records to binary files using the Put statement:
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:
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.
To read from sequential file, you can use these standard statements (we’ll see how to use
TextStream methods later in this chapter):
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.
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:
50
then we can read those integers back using Input # this way when the user clicks
Command2:
End Sub
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:
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:
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
Exit Sub
FileError:
MsgBox "File Error!"
End Sub
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:
Exit Sub
FileError:
MsgBox "File Error!"
End Sub
This example produces the same result as the previous example that uses Line Input.
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):
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:
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:
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):
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:
Close #1
[Link] = ReadData(1).Name
[Link] = ReadData(1).Number
Exit Sub
FileError:
MsgBox "File Error!"
End Sub
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):
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:
Then we write that number out to a binary file, [Link] (making it a binary file by
opening it in Binary mode):
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:
Next, we use Get to read in the number and store it in a new variable, varInput:
End Sub
Finally, we display the newly read-in variable in a text box, Text2, and close the file:
FileError:
MsgBox "File Error!"
End Sub
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:
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
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
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
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
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
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
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
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
End Sub
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
66
MsgBox ("Your Name is " & [Link])
MsgBox ("Your admission number is " & [Link])
MsgBox ("Your fees is " & [Link])
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
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
End Sub
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
69