Beruflich Dokumente
Kultur Dokumente
0
For
Engineers and Scientists
ThankGod Egbe
Dept. of Petroleum Engineering
University of Port Harcourt
Port Harcourt, Nigeria
Published in Nigeria By
Visual Basic for Engineers and Scientists
Copyright 2003 ThankGod Egbe
ISBN:
All Rights Reserved. No part of this book shall be reproduced, stored in a retrieval
system, or transmitted by any means, electronic, mechanical, photocopying, recording or
otherwise, without the written persmission of the copyright owner. No patent liability is
assumed with respect to the use of information contained herein and neither is any
liability assumed for damages resulting from the use or misuse of the information
contained herein.
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have
been appropriately capitalized. The copyright owner cannot attest to the accuracy of this
information. Use of a term in this book should not be regarded as affecting the validity of
any trademark or service mark.
Windows 95, 98, 2000, NT and XP, Microsoft Word, Microsoft Excel,Microsoft Access,
Microsoft Powerpoint, Microsoft Project, Microsoft Visual Basic and Microsoft Visual
Studio are registered trademarks of Microsoft Corporation. AutoCad is a registered
trademark of Autodesk Inc., CorelDraw is a registered trademark of Corel Corporation.
Dedication
Preface
Visual Basic is a powerful but simple tool for building applications for
Windows 9x, Windows 2000, NT and XP. These applications are by far larger and more
complex than their predecessors that did not use a graphical user interface. Yet as
program size and complexity have grown, programmers effort have actually decreased,
at least for programmers who are using the right tools.
Visual Basic is one of the right tools. The time you invest in learning to use
Visual Basic will pay itseft back on your first windows programming project with Visual
Basic. Depending on your interest and discipline, the length of time you will use to learn
Visual Basic is a function of the nature of your instructors and the nature of books you
use. For people with interest in the business world, they will learn faster with text books
demonstrating various applications of Visual Basic in the business world. A lot of books
exist in this area. However, for people with interest in the Science and Engineering
world, they will certainly feel more comfortable using a textbook dedicated to
demonstrating various applications of Visual Basic in the Science and Engineering
world.
This text was written primarily for Science, Engineering and Mathematics
students as well as practicing professionals. The motivation to write this book stems from
the fact that most of the books written in Visual Basic hardly have Science and
Engineering applications and hence do not allow Science and Engineering professionals
to appreciate the importance of Visual Basic. This book is a teach-yourself guide to
learning Science and Engineering-oriented Visual Basic. It was written to meet the needs
of students and lecturers in Engineering, Sciences and Mathematics in Universities,
Polytechnics, Colleges of Education and Computer training and software development
outfits. For those preparing for Microsoft Software Certification(MCSD), you will find
this book useful in your Visual Basic Desktop application development certification
examination and the certification examination on Analysing Requirements and Defining
Solution Architecture.
The book is in two volumes, Volume 1 covers the introductory and intermediate
topics in Visual Basic which will enable beginners develop a powerful standalone
scientific applications. Volume 2 covers the advanced topics in Visual Basic and is a
must read for those who want to develop state of the art software with Visual Basic.
Volume 1 of this book has 10 chapters while Volume 2 has 12 chapters. The chapters in
Volume 1 are; User Interface Design Fundamentals, Visual Basic Programming
Fundamentals, Control Structures, Data Structures and Strings Arithmetic. Others are
Functions and Sub Procedures, Controls Array , Visual Basic for Applications, Numerical
Applications and Database Access.
In writing this book, it is assumed that the reader does not know anything about
Visual Basic or programming, so the book starts off with simple, straightforward and
well explained examples. From there, the chapters become more advanced and
comprehensively cover the essentials of programming with Visual Basic. Because each
chapter builds upon the concepts in the preceding ones, it is important that you
understand the material covered in one chapter before moving to the next. An evaluation
exercise in the form of problem set has been added at the end of each chapter to enhance
the appreciation and understanding of Visual Basic.
In addition, the book ships with a CD ROM containing code samples,Visual
Basic projects and solutions to selected exercises aimed at safisfying the expectations of
students as well as consolidating their knowledge and skills. A supporting Website is also
available where users can get periodic review, download codes and also get online
training
ThankGod Egbe
October, 2003
Acknowledgement
First of all, I would like to thank the Science and Engineering students of
University of Port Harcourt, Federal University of Technology Owerri and Rivers State
University of Science and Technology for using the manuscript of this book for their
Course and Project work and subsequently encouraging and motivating me to produce
this text book.
In producing this book, so many persons have contributed in one way or the other
to bring this book to fruition. To Engr. Armstrong Lee , I say a very big thank you to you
for providing the computer and comfortable atmosphere used in typesetting this book and
spending sleepless nights with me to edit and proof-read the manuscript. To Engr. Joe
Kintum of the Shell Petroleum Development Company, Warri, I say another big thank
you for reviving the hope of producing this book and your sustained encouragement.
The assistance and encouragement I received from my cousin, Lucky Stephen is
very well acknowledged. To John Otogbo, I deeply acknowledge and appreciate the time
you devoted reading this manuscripts especially in its raw form. To Aniebiet Udoh, my
Programming companion, I very well appreciate the sugesstion and assistance you have
provided to me especially concerning this book and the accompanying CD ROM.
The encouragement and motivation I received from Dr. Dulu Appah, Dr.
Adewale Dosunmu, Engr. Martin Chukwuezi, Mr. Boma Kinigoma and Engr. S. S.
Ikiensikimama of the Faculty of Engineering University of Port Harcourt are well
acknowledged.
To Kedei Obeten, Aniekan Udo, Jerome Onwunalu, Nnanna Erasmus, Usman
Anes, Adoga Charles, Okeoma Ihunwo, Chiringo Chinda and Ikokwu Ihechi, I thank you
all for the various ways you have contributed to make this book a success.
Also, I wil like to thank my Father, Mr. T. I. Egbe and Mothers Mrs. Mary T. I.
Egbe and Mrs. Elizabert T. I. Egbe for their encouragement right from the first day I
conceived the idea of writting this book. Ill also like to thank my brothers Richard, Egbe,
Bassey, Emmanuel, Eneh and Pringle and my cousins Igwe Johnson, Okoi Inah and
James Inah for their sustained support. To all others who have in one way or the other
contributed to make this book a success, I say thank you and God bless you all.
Most importantly, I thank the Almighty God for giving me the enablement to
write this book.
ThankGod Egbe
Supporting WebSite
For more information about the book, CD ROM or Supporting WebSite, send a mail to
info@thankgodegbe.com
Contents at a Glance
Chapter
Page
48
3. Control Structures
96
4. Data Structures
155
5. String Arithmetic
211
265
7. Controls Array
300
330
9. Numerical Applications
374
10.
414
Database Access
453
463
465
Appendix D
471
Index
485
Table of Content
Preface .............................................................................................................. vi
1. Design Fundamentals .................................................................................... 1
Visual Basic Controls In Windows Applications .............................................. 2
Visual Basic IDE ................................................................................................. 5
Properties Window.......................................................................................... 7
Toolbar ............................................................................................................ 9
Project Explorer ............................................................................................ 10
Naming Visual Basic Controls. ....................................................................... 12
Visual Basic Units Of Measurement ............................................................... 13
Designing program interface. .......................................................................... 14
Formatting Controls ...................................................................................... 16
Designing Windows Interface Using Visual Basic Controls ........................ 17
Introducing the Combo Box And Frame ...................................................... 17
Introducing The Line control, Checkbox control and Picture box control .. 19
Introducing The Text Box and the Vertical Scroll Bar ................................ 20
Introducing the horizontal scroll bar ............................................................. 21
Introducing the list box ................................................................................. 21
Introducing the Data Control ........................................................................ 23
Other intrinsic controls ................................................................................. 23
Interface Design with Windows Common Controls. ...................................... 24
Adding the Microsoft Windows Common Control to the ToolBox. ............ 25
Configuring the Tabstrip Control.................................................................. 26
The Property Pages ....................................................................................... 27
Configuring the UpDown Control ................................................................ 27
Configuring the Toolbar Control .................................................................. 28
Adding Images to the Toolbar Control. ........................................................ 29
A Closer Look at the Toolbar Buttons .......................................................... 30
Other Controls from Components ................................................................. 31
Designing Menus ............................................................................................. 32
Notes on Menus/Menu Editor ....................................................................... 33
Designing Your Own Application.................................................................... 34
Other Input Controls ..................................................................................... 36
The Combo Box ............................................................................................ 38
Enhancing the Van Der Waal Problem. ........................................................ 40
Generalized Conversion Program ................................................................. 41
ii
Navigational Design......................................................................................... 42
Problem Set 1 ................................................................................................... 44
2.
Programming Fundamentals...................................................................... 48
Setting Objects Property Using Code ............................................................. 49
Visual Basic Data Types .................................................................................. 51
Byte Data Type ............................................................................................. 52
Integer Data Type ......................................................................................... 52
Long Data Type ............................................................................................ 52
Single Data Type........................................................................................... 52
Double Data Type ......................................................................................... 52
Currency Data Type ...................................................................................... 52
String Data Type ........................................................................................... 53
Date Data Type ............................................................................................. 53
Boolean Data Type ....................................................................................... 54
Variant Data Type ......................................................................................... 54
Object Data Type .......................................................................................... 54
Other Data Types .......................................................................................... 54
Variables And Constants............................................................................... 54
Storing Data In Variables/Constants............................................................. 55
Defining Variables ........................................................................................ 57
Defining Variables Using Objects properties .............................................. 59
Defining Variables Using the InputBox Function ........................................ 63
Defining Variable using Files ...................................................................... 63
Viewing the Content of Variables................................................................. 64
Viewing Variables Value using objects properties ....................................... 64
Print Statement .............................................................................................. 66
Viewing the content of variables using message box ................................... 66
Using the Local and Watch Window ............................................................ 67
Processing Data................................................................................................ 67
Operators ....................................................................................................... 67
Arithmetic Operators .................................................................................... 68
String Operators ............................................................................................ 68
Comparison operators ................................................................................... 69
Functions ....................................................................................................... 70
Events and Event Procedures .......................................................................... 72
The Form Module and Event Procedures ..................................................... 73
Creating the Click Event Procedure of a CommandButton .......................... 74
Creating click Event procedure of a TextBox............................................... 75
Contents
iii
iv
Contents
vi
Contents
vii
8.
viii
Contents
ix
CHAPTER
1
DESIGN FUNDAMENTALS
Visual Basic Controls In Windows Applications
Visual Basic IDE
Naming Visual Basic Controls.
Visual Basic Units Of Measurement
Designing Visual Basic Interfaces
Interface design with Windows Common Controls.
Designing menus
Application design
Navigational design
Problem Set
Learning Visual Basic (or any member of Visual Studio) is interesting at times when you
realise that you would be writing programs with familiar Windows like those of MS
Word and Excel. Often you use controls (or objects) in MS Office without bothering to
know their names, all you are interested in is that it should work for your purpose. Thats
OK, infact very OK for appreciation level. After reading this chapter you will depreciate
your respect for most of the windows you see because you can design them in minutes
and at times better than how celebrated software developers designed theirs. This is
because you are now learning the language (or a language similar to that) used to
develop applications like Word, Excel and other windows based software, hence your
power of thought can make you change things for the better. We are going to begin this
book in an unconventional manner. We will start with what you know and tell you
something you are not aware of in what you know. This will make our discussion very
friendly.
FIGURE 1.1
Shut Down Windows
Dialog
You should be familiar with the function of the window. You select an option and click
OK command for windows to perform an action based on the option you have selected.
You can also click the cancel command to hide this window or click the Help button to
invoke windows help. The buttons used to indicate that an item is selected from a group
of mutually exclusive options are called option buttons. While those that enable your
program to perform an action when a user clicks them are called the Command Buttons.
In the dialog in Figure 1.1, there are
1. Three Command Button Controls
2. Four Option Button Controls
3. One Label Control
4. One Image Control
Design Fundamentals
The label control is used to display textual information to the user while the image
control is used to display graphical information to the user.
In Visual Basic, the dialog shown in Figure 1.1 is called Form window. We will be using
this term very often because virtually nothing happens without the Form for most of the
applications you will be developing in this book. It could be called different names in
other programs, however always remember that its general name is Form Window. In
compiled application it could be called Splash Screen, Dialog Box, Message Box etc.
You now know five Visual Basic objects(controls) and at least what they are used for.
Before going ahead to introduce more objects, we should pause a bit and discuss
properties of object. An objects property defines its appearance and behavior due to the
data stored in it. Lets discuss four of the properties of the objects in Figure 1.1. These
properties are
1. Caption
2. Picture
3. Value
4. Visible
The Caption property determines the textual information displayed by objects. In Figure
1.1, the caption of the Form is shut down windows . The command buttons also have
captions. The caption of the three command buttons are OK, Cancel, Help .
Observe that almost all the objects in the form including the Form itself have the caption
property. This property allows objects to display textual information about themselves or
other controls without the caption property. The exception is in the image control. Instead
of the caption used to display textual information, the image control has the picture
property that enables it to display graphical information. The option button has another
property called the Value property which is used to indicate the selected option from a
group of options. The value property can either be True or False. It is true when the item
is the selected item and False when the item is not selected. For option buttons, the value
property is a Boolean property because it has a value of True or False. All properties that
have values of true or false are Boolean properties. Other examples of boolean properties
are the visible, enable and CausesValidation properties. The Visible property determines
whether the user sees an object or not. It is true when the object is visible to the user and
false when it is invisible. Other properties of objects that are often employed in visual
interface design are the Top, the Left, the Width and the Height properties. We are going
to illustrate these properties using Figure 1.2
FIGURE 1.2
Illustrating Height,
Top, Left and Width
Properties of a
control
B
C
Figure 1.2 shows a form window with the text box at the centre of the form. The text box
is an object(or control) similar to the label control in that it is used to display textual
information. In addition, it also allows the user to edit this information unlike the label.
The text box has almost all the properties of the label in addition to other properties
unique to the text box only. The arrows labeled A to D show respectively the top, the
height, the width and the left properties of the text box. These properties are defined
below
Top:
The top is the vertical distance between the top of the form and the top of the
object
Left:
The horizontal distance from the left edge of the form to the left edge of the
object.
Design Fundamentals
FIGURE 1.3
Visual Basic
Project dialog
new
1.
2.
You should see the splash screen, wait until the splash screen disappears. You
should see a window similar to Figure 1.3) Select Standard Exe and click open .
The Visual Basic integrated development environment as shown in Figure 1.4
appears
Figure 1.4 shows the Visual Basic IDE. The function of each window is discussed
below.
NOTE
When you open Visual Basic, not all the windows shown in figure 1.4 appear.
You can view those absent using the view menu. e.g if the properties window is not
visible, activate the view menu and select properties window from the menu Items.
The start up windows are the windows present when Visual Basic was last
closed
FIGURE 1.4
Visual Basic
Integrated
Development
Environment
Menu
Bar
Tool Bar
Tool Box
Form Window
Properties Window
Menu Bar: Used to activate the top level menus. Same function with that of a menu bar
in other applications you have used
Form Window: The form window is used to create dialog boxes and windows used in
application development.
Tool Box The tool box houses the objects drawn on the form. The label, option button,
command button controls discussed previously are resident in the tool box.
You select an object from the tool box and draw an instance( or a copy) of it on the form.
By default, there are twenty one objects in the toolbox. Out of these only twenty are
programmable objects. These are called intrinsic(or standard or default) controls
because they are always present when Visual Basic loads. Other Controls from
components and third parties are also placed on the tool box before instances of them can
be drawn on the form. Figure 1.5 shows the tool box in its default state.
Design Fundamentals
FIGURE 1.5
Tool box showing
Standard Controls
Pointer
Text
Box
Check Box
List Box
Timer
File List Box
Image Box
Label Control
Picture Box
Command Button
Frame
Combo Box
Option Button
Vertical Scroll
Horizontal
Scroll
Bar
Bar
Directory List
Drive
Box List Box
Line Control
Shape Control
OLE Control
Data Control
Properties Window
As controls are drawn on the form, the properties of these controls can be
modified using the properties window. Figure 1.6 shows the properties window
displaying the properties of the form
FIGURE 1.6
Properties Window
showing form
properties in
alphabetical order.
Object List
Property value
Property
3. By selecting the property and then modifying the property by clicking the ellipsis on
the right of the property. This will usually launch a dialog box. A typical property
that is changed in this manner is the picture property.
4. By selecting the property and then open the drop down box in the property list. This
list is then filled with constants(data) on different rows. The list property is a typical
property changed in this manner.
Design Fundamentals
The properties window with form properties in categories is as shown in Figure 1.7.
Properties are set in categories by clicking the categorized tab on the properties window.
When properties are arranged in categories, related properties are grouped together under
a common heading.
FIGURE 1.7
Properties Window
showing properties
in categories
Toolbar
Contains buttons that provides quick access to the menu command. Visual Basic has four
types of tool bar. These are
1.
Standard Toolbar
2.
Edit Toolbar.
3.
4.
10
Project Explorer
The project explorer provides an easy means of working with the components of the
projects. It displays the name and filename of the components in the project. Figure 1.8
shows the project explorer. From the project explorer you can deduce so many things
about your project. Some of these include
It tells you how many forms exist in a project
It tells you if a form is saved or not
It tells you if the project has been saved or not
It tells you if a name has been given to a form or not
It tells you if a name has been given to the project or not
It reveals the active form in a project.
It enables us to identify other components in the project apart from the form.
It enables you know if these components have valid names and have been saved
It enables you identify a multiproject application and to set the active project in
such applications
FIGURE 1.8
Visual Basic project
explorer showing
project modules
Toggle Folder
View Code
View Object
Button
The project explorer has many other functions and listing all might take scores of lines.
From the project explorer you can toggle folder, you can move between projects, you can
move from the code window and back to the form. You can also remove a form or a
Design Fundamentals
11
project in addition to so many other functions that will become clear to you as you
progress in your Visual Basic carrier. The following can be deduced from the project
explorer shown in Figure 1.8
1. There are four forms in the application. You recognize a Visual Basic form with the
unique form icon
2. Three of the forms have been saved. Visual Basic forms are saved with the extension
.frm
3. Two of the forms have been given names. A form in Visual Basic is named with the
prefix frm. e.g frmOil
4. The project has been saved. A Visual Basic Project(Standard Exe ) is saved with the
extension .vbp eg PNG505.vbp
5. The project has not been given a name. Once a project has been given a name, the
name appears on top of the project explorer as project - project name. You assign
names to projects using the project properties dialog. Select properties from the
project menu and you see the project properties dialog.(see figure 1.9). You can type
any name say Petroleum in the project name text box of the project properties
dialog
6. The project contains a basic module(standard module) that has not been saved. A
standard module is saved with a .bas extension.
FIGURE 1.9
Visual Basic project
properties dialog used
to assign names to
project and also select
startup object among
other functions
NOTE
To invoke the project property dialog, activate the project menu and select properties in
the menu items.
12
Control
Prefix
S/No
Control
Prefix
CommandButton
cmd
16
Shape
shp
OptionButton
opt
17
Line
lin
TextBox
txt
18
FileListBox
fil
Label
lbl
19
DirListBox
dir
Frame
fra
20
DriveListBox
drv
Form
frm
21
Timer
tmr
CheckBox
chk
22
Tabstrip
tbs
PictureBox
pic
23
Menu
mnu
Image
img
24
ToolBar
tbr
10
Data
dta
25
Statusbar
stb
11
ListBox
lst
26
ProgressBar
pgb
12
vsb
27
UpDown Control
upd
13
hsb
28
Slider
sld
14
OLE
ole
29
Script Control
sct
15
ComboBox
cbo
30
Grid Control
grd
NOTE
You name an object using the name property in the properties window. Some objects
like the menu are however named differently. This will be discussed when creating
menus. Always begin the name of an object with the appropriate prefix and ensure that
neither space nor special character is part of the name.
13
Design Fundamentals
vbTwips
vbPoints
vbPixels
2
3
vbCharacters
vbInches
vbMillimeters
vbCentimeters
vbHimetric
vbContainerPosition
5
6
7
8
9
vbContainerSize
10
Description
Indicates that one or more of the
ScaleHeight, ScaleWidth,
ScaleLeft, and ScaleTop
properties are set to custom
values.
(Default) Twip (1440 twips per
logical inch; 567 twips per
logical centimeter).
Point(72 points per logical inch).
Pixel(smallest unit of monitor or
printer resolution).
Character (horizontal = 120
twips per unit; vertical = 240
twips per unit).
Inch.
Millimeter.
Centimeter.
HiMetric
Units used by the control's
container to determine the
control's position.
Units used by the control's
container to determine the
control's size
The default Scale Mode property is the twip, you can set it to centimeters or inches.
14
3.
Name
frmShutDown
Caption
Shut Down Window
BorderStyle
4(fixed Toolwindows)
Height
2900 twips
Width
4800 twips
Bring four option buttons and draw them on the Form. Try to arrange the option
buttons so that they will have the alignment as in Figure 1.1. Change the following
properties of the option buttons
Option Button 1: Name - optStandBy, Caption (S&tand By)
Option Button 2: Name - optShutDown, Caption - &Shut Down , Value True
Option Button 3: Name - optRestart, Caption - &Restart
Option Button 4: Name - optRestartDos, Caption: Restart in &MS Dos Mode
4.
5.
Bring a label and place it beside the option buttons. Change the following
properties of the label control
Name lblName , Caption What do you want the computer to do?, Autosize
True
6.
Bring an image control and place it on the form. Change the following properties of
the image.
Stretch True , Picture C:\Program Files\Microsoft Visual Studio\Common\
Graphics\Metafiles\Business\Computer
To change the picture property you click the ellipsis at the right of the picture
property of the image control. This will open the load picture dialogue box as shown
in Figure 1.10
You Select C: from the drop down list or type C:\ in the file name Textbox and Click
open or Press Enter. It should take you to Drive C. Select Program Files Folder or Type
C:\Program Files\
Design Fundamentals
15
In the File name textbox. select Microsoft Visual Studio from the program files folder
or type C:\Program Files\Microsoft Visual Studio
Select Common from the Microsoft Visual studio folder or type Common in the
Microsoft Visual Studio Folder.
NOTE
The ampersand character (&) is used to underline(underscore) any character it precedes.
The effect of this is that the control with the underscored character can be activated
(clicked) at runtime by pressing Alt + [the underscored character]
FIGURE 1.10
From the list of folder inside the common folder select graphics or just type graphics in
the file name textbox and press enter. This opens the graphics folder. From the graphics
folder you can select any folder to get the desired graphics you need. For our purpose,
select metafiles or type metafiles in the file name textbox and press enter. Select the
Business folder or type business in the file name folder. This opens the business metafiles
graphics. You can now select the computer icon or type it and press enter. Change the
height and width of the image to 500 each. Your interface should be as shown in Figure
1.11 Observe that the image in Figure 1.11 is different from the image in Figure 1.1 This
is because Visual Basic does not come with the image of Figure 1.1. You can get exactly
the same image by visiting yahoo and download icons.
16
FIGURE 1.11
Final Design of Shut
Down Windows
dialog
Formatting Controls
Observe that the command buttons of Figure 1.11 have different sizes and different tops
unlike those of Figure 1.1 You can use the properties window to give the objects same
height, width and top. To do this click the reference command button and read its height,
Width and Top. then change the height, left and top of the other command buttons to that
of the reference buttons. Alternatively, you can use the format menu to make the objects
have same width, top, left, right etc. To use the format menu, hold down shift and click
the object in questions such that the reference object is clicked last .Then click the
Format menu and then select Make Same Size and the select Both ( both height and
width). The command buttons should now have the height and width of the reference(or
the last selected objects). This is a quicker method than using the properties window.
Now make the buttons have same top. Let use the first button as reference. Select the
three command buttons such that the first button is selected last. Open the Format menu
and select Align Top. Now use the Format menu and make the option buttons have
same height. The label, option buttons and OK command buttons have the same left.
Using the format menu make the option buttons have the same left as the OK command
buttons. Do this by selecting the objects in questions such that the OK command button
is selected last and then Align Left using the format menu. Lastly, select the option
buttons and use the Format menu to Make Equal Vertical Spacing(i.e give them equal
vertical spacing). If the vertical spacing is too small, you can increase it or decrease it
using the format menu. Also you can repeat the same for the command buttons and make
them have equal horizontal spacing. Your design should be very much similar to the shut
down windows dialog of Figure 1.1
17
Design Fundamentals
Whats ThisButton
Command Button
Combo Box
Label
Frame
Image
Option Button
Figure 1.12 shows the Print Setup dialog box in Visual Basic. Here you would be
introduced to two new controls: these are the frames and the combo boxes. The combo
box is a multipurpose control which is used to display textual information to users in a
drop down list. Depending on property settings, this information can be made editable.
The drop down list provides a way for the user to select different options from the combo
box. In this regard it functions like a group of option buttons. On the other hand, the
frame is used to group related information together.
Other controls on the form are the command buttons, labels, option buttons and image
that you have used while designing the windows Shut down dialog. To start designing the
interface, we choose an appropriate height and width of the form then follow the steps
outlined below
1. Use the properties window to change the following properties of the form
Name
frmPrintSetUp
Caption
Print Set Up
18
BorderStyle
4(fixed Toolwindows)
WhatThisButton
True
Height
Use your Judgement
Width
Use your Judgement
2. Draw three instances of the frames on the form and configure them as in Figure 1.12
Set the following properties for the frame.
Top Frame:
Name - fraPrinter
Caption Printer
Bottom Left frame :
Name - fraPaper
Caption Paper
Bottom Right Frame
Name - fraOrientation Caption - Orientation
3. Draw two instances of the command button control on the form(not frame) and
another instance of the command button control on the top frame. Arrange the
command button an in Figure1.12. Give the command buttons appropriate names and
captions(make use of ampersand)
4. Use the ToolTip to identify a combo box and draw an instance of it on the first frame
and two instances of it on the bottom left frame. Set the following properties for the
combo boxes
Combo Box #1: Name cboPrinterName : Text: HP Laser Jet 1100 Style - 2
Combo Box #2: Name - cboPaperSize : Text: A4 210 x 297 mm Style - 2
Combo Box #3: Name - cboPaperSource : Text: - Upper Tray
Style - 2
5. Draw two instances of the option button control on bottom right frame and set the
following properties.
Option Button #1 : Name optPortrait Caption &Portrait Value True
Option Button #2 : Name - optLandScape Caption &Landscape
6. Draw an instance of the image control on the bottom left frame. Use this path to
locate the image:
C:\ProgramFiles\MicrosoftVisualStudio\Common\Graphics\Icons\Writing \Portrait
7. Draw eight instances of the label control on the top large frame and two other
instances of the label on the bottom left frame. Give the label captions as shown in
the figure and names to reflect their caption.
8.
Use the format menu to align the controls as shown in Figure 1.12. Also remember
to make related controls same size both as in Figure 1.12
Design Fundamentals
19
FIGURE 1.13
Visual Basic Controls
used in MS Excel
Paste Special dialog
box
The Line control is only used for decorative purposes. It is used to separate a group of
information in much the same way as the frame. Unlike the frame that has a caption, the
line control does not have a caption and as such a label control has to be placed by it to
describe the purpose of the grouping. The check box control is like an on/off control
used to turn an action (or a feature/setting) on or off. The picture box control is a
container control used to group related controls together just like the frame. Your ability
to see the frame/picture box depends on the border style setting. If it is set to 0 (i.e. no
borders) it means no borders, the frame will just appear on the background and can not be
seen at run time. You confirm the presence of picture box if two option buttons have a
value of true in the same Form. In Figure 1.13, there is atleast a picture box(or frame)
used to separate the option buttons. We now attempt to design the interface of Figure
1.13. We first of all design the form. You should be familiar with how to design the form
and bring other controls apart from the three new controls. Use the following steps to
design the interface.
1. Design the form as usual
2. Use the ToolTip to identify the picture box control in the toolbox. Then draw two
instances of the picture box control on the form. Set the following properties for the
picture box control
20
3. Draw seven instances of the option button control on the first picture box and five
instances of the option button on the second picture box. Give the option buttons
captions as in the figure 1.13 and names to reflect their captions.
4. Set the value property of the first option button in each group to true
5. Use the tooltip to identify the line control and draw three instances of it on the form
and arrange them on the form as shown in Figure 1.13
6. Give the line controls names using standard naming conventions for lines
7. Draw two instances of the label control on the form and place them beside the first
two lines. Give them caption of Paste and Operation and Names of lblPaste and
lblOperation respectively
8. Use the tooltip to identify the checkbox control and draw two instances of the control
on the form. Use the properties window to set the following properties of the
checkbox control.
CheckBox #1
CheckBox #2
Value :1
9. Draw three instances of the command button control on the form and arrange them
as
shown in Figure 1.13 Set the following properties for the command button.
Command Button #1: Name: chkOK , Caption : OK, Default : True
Command Button #2: Name: chkCancel, Caption : Cancel , Cancel True
Command Button #3: Name: chkHelp, Caption: &Paste Link
10. Use the format menu to set appropriate alignment for the controls and make same
size if applicable.
21
Design Fundamentals
FIGURE 1.14
Visual Basic controls
used in MS Excel
Data Form dialog
(a)
22
(b)
We can now create an interface similar to that of figure 1.15(b). Use the tool tip property
to identify a list box and draw an instance of it on the form. Design the form to get the
appearance of Figure 1.15a. and format your controls appropriately. Use table 1.1 as
your guide when naming the controls. Give the list box the name: lstFormats. Open the
drop down list in the List property of the list box and type the entries in the list box of
Figure 1.15 into your list boxs list property. Press Ctrl + Enter after each entry
FIGURE 1.16
Properties Window
showing the List
Property of the
ListBox.
23
Design Fundamentals
FIGURE 1.17
User application
showing the Visual
Basic data control
Data control
24
DriveListBox
FIGURE 1.18
User form showing
other intrinsic
controls
FileListBox
DirListBox
Shape Control
HorizontalScrollBar
We now consider some controls collectively called Windows Common controls. They are
not usually loaded in the tool box by default but can only be added to the toolbox from
components. Common examples of the windows common control are the toolbar,
statusbar , updown control ,and the tab strip control.
FIGURE 1.19
Windows common
control in MS Excel
options dialog
Tab Strip
Up down control
Design Fundamentals
25
The Updown control is commonly attached to the textbox control and it is used to
increase/decrease the value(text) in the text box. Figure 1.19 shows the updown control
in the edit tab of the option dialog in Microsoft PowerPoint 97. Here, the updown control
was used to increase/decrease the maximum number of undos in the application. The
value in the text box increases by one(or any number depending on the setting in the
properties window) when the up arrow is clicked. The tab strip control on the other
hand is used to divide the form into different sections. We now demonstrate how to use
the updown control and the tab strip control.
FIGURE 1.20
Visual Basic
components dialog
used commonly to
add non-standard
control to the tool
box
Scroll down to Microsoft windows common control and place check marks on all the
Microsoft windows common controls and click Apply. All the Microsoft windows
common controls are then added to the toolbox. You close the dialog by clicking Close.
The toolbox shown in Figure 1.21 shows a fully loaded tool box with default controls and
windows common controls. With the aid of tool tip you can identify a Microsoft windows
common control in the tool box. Among the popular Microsoft windows common
controls are the tab strip control, updown control, the tool bar control, status bar control,
image list and the tree view controls. Others are the date time picker, month view and the
progress bar..
26
FIGURE 1.21
Tool Box
containing standard
controls and
windows common
controls added
from controls
components
We now outline how to add and configure the Microsoft windows common control in the
Form.
(c)
(b)
Design Fundamentals
27
FIGURE 1.23
Property pages of tab
strip control
NOTE
The properties window is used to change properties of standard controls while the
property pages is used to change the properties of most windows common controls. You
invoke the property pages by right-clicking a control and selecting properties from the
popup menu.
28
1. Buddycontrol - Specifies the name of the textbox(or control) in which the control is
to be attached
2. Buddy Specifies the name of the property in which the control is to modify
3. Max Specifies the upper bound of the scroll range
4. Min Specifies the lower bound of the scroll range
5. Orientation Specifies the orientation of the control. This could be vertical or
horizontal.
The tool bar control is configured in the same way the tab strip was configured using the
property pages. However, unlike the tab strip with tabs, the tool bar control has buttons.
The buttons can carry texts or images or both. Using tool tip, identify the tool bar
control on the tool box and draw an instance of it on the form. Open the property pages of
the toolbar control by right clicking the instance of the tool bar control and select
properties from the pop up menu. Click the Buttons tab and then click the Insert Button
command button to add buttons to the tool bar control(see Figure 1.25). Provisions are
made so that you can give captions, keys, tags and images to the buttons just created.
NOTE
You add images to windows common control using the imagelist control. The imagelist
control is a windows common control that holds images for other controls. It is invisible
at runtime
Design Fundamentals
29
FIGURE 1.25
Property pages of the
toolbar control
NOTE
A tool bar control may have both caption and images though one is sufficient to define a
button. Most of the tool bar controls used in windows explorer have buttons and captions.
In the standard tool bar as well as other tool bars used in many applications, only images
are used to communicate with the user. Most developers use the tool bar just as the
command buttons are used, in cases like these the tool bar may have only captions
30
Design Fundamentals
31
DropDown: This creates a drop down menu which is shown when the button is pressed.
Examples are the undo button and the autoshape buttons of Microsoft Office standard and
drawing tool bar respectively.
Optional properties needed to be set for the tool bar buttons are the tool tip and the
caption properties. The tool tip text specifies the text that appears when the mouse pointer
rests momentarily on the buttons while the caption specifies the text that appears on the
tool bar(see windows explorer delete button). In standard applications, tool bars hardly
have captions. Images are used in place of the caption. This makes sense only when the
images describe the buttons sufficiently.
FIGURE 1.26
MS Office Standard
and formatting tool
bar showing different
toolbar buttons
NOTE
The slider, status bar and the date/time picker are part of a windows common control
group while the MS Chart and MS flex grid can also be added to the tool box as separate
controls from controls component.
32
FIGURE 1.27
MS flex grid
MS Chart
Slider
Date/Time
Picker
Status bar
Designing Menus
Menus are found in almost every application developed today. You can include menus in
your Visual Basic applications to provide a single click access to program functions and
commands. Visual Basic menus are designed using the menu editor. You invoke the
menu editor by selecting Menu Editor from the tools menu or by selecting the menu
editor icon from the standard tool bar. Once the menu editor appears on the form, you
create top level menu items by specifying the name and caption of the menu items.
Submenus are created by adding the sub menu item below the top level menu and
clicking the right arrow command button to convert the menu items to sub menus under
the top level menus. You can also create a sub menu under a menu item. The menu
editor in Figure 1.28a shows that the top level menus are the File and Edit menus and that
the Open, Save, Close and Exit menu item are under the File menu while the Undo, Redo
and Find are the menu items in the Edit menu. The menu editor also reveals that the Save
menu item also has a sub menu with menu items of Save All and Save As. Figure 1.28 b
shows the outlook of the menu created with the menu editor of Figure 1.28a.
NOTE
A top level menu created with visible property set to false could function as a pop up
menu at run time
Design Fundamentals
33
34
n=
PV
..................................................................................................................... 1
RT
Where
P = Pressure of Gas ,atm
V = Volume occupied by gas ,dm3
T = Absolute Temperature of gas ,K
R = Universal Gas Constant , atm dm3/mol K
n = number of moles, mol
Value of R could change when the unit system changes, therefore care is actually taken to
work with consistent unit system. From the statement of problem , three input
controls(say text boxes) and an output control(say label with fixed borders) are needed
for the user interface. The interface needed for this problem is as shown in Figure 1.29
Design Fundamentals
35
FIGURE 1.29
In Figure 1.29 the three text boxes are used for input of pressure, volume and temperature
respectively while the label( with fixed borders) is used to display results. The command
buttons are used to trigger the calculate command and the close command used to unload
the application. One problem with interface of Figure 1.29 is that users can not easily
identify the specific text box meant for pressure, volume and temperature thus
temperature value may be entered in the first or second text box there by giving results
without significance. This underscores the need to use labels to annotate the three text
boxes and the label used for output. This makes the program more interactive and user
friendly. The interface with the labels used to annotate the input/output controls is as
shown in Figure 1.30
FIGURE 1.30
Improved user
interface of the Van
Der Waal Problem
with controls well
annotated
NOTE
The label is used to annotate controls without the caption property. These controls
include the text box, the combo box, line etc. It is also used to annotate some labels used
as output controls.
36
The interface of Figure 1.30 seems to be very good in that users can identify the
appropriate text boxes and enter the corresponding input and then click calculate for
processing to be done and results displayed on the label. The problem with this design is
that units differences are not handled. To handle this, we need to keep users informed
that we are working only with SI units so that they may need to convert their units to SI
units before using our program. This makes the program more relevant to users. The
interface with the labels used to specify input units is as shown in Figure 1.31
FIGURE 1.31
Design Fundamentals
37
FIGURE 1.32
The interface in Figure 1.32 is interactive and user friendly. It can be used to interconvert
temperature from one unit to the other. Two problems exist with this interface. First the
user may not be sure whether to type the temperature units in full or just the first
character. Another problem is that if the user has another unit of temperature, he might
not be sure whether the program considered the unit. A better way to solve this problem
is to display the units considered in a frame at the right so that a user can inspect the unit
and type the appropriate unit in the input unit and output unit text box as the case may be.
This design is as shown in Figure 1.33
FIGURE 1.33
Improved user
interface for
temperature
conversion
Handling the conversion problem this way is OK. However, it still takes the user much
time to type the units in the text boxes. It would have been better if the user could just
enter the unit to be converted and select the input as well as output unit. This form of
design needs option buttons or list controls. Figure 1.34 shows the improved conversion
with option buttons
38
FIGURE 1.34
User friendly
interface for
temperature
conversion using
option buttons as
input control for
temperature units
You can see how this interface looks. It is in every respect better than the interface of
Figure 1.33. By comparing the interfaces of Figure 1.33 and Figure 1.34 we state the
advantages of the option buttons over text boxes when working with options
1. Option buttons define the scope of an application or a dialog at first glance.
2. It reduces chances of errors due to spelling
3. Its saves the user quality time in entering inputs
4. It gives the user more confidence in the results obtained.
5. It is more interactive, user friendly and visually pleasing.
However, the option buttons still have some limitations. These include the
following
Can only be used with limited range of input.
Can only be used when a developer has an idea of the users input.
Design Fundamentals
39
Drop down combo. Here the user can select an option from the list or type his or hers
Simple combo. This is similar to the drop down combo in that the user can either select
an option or type his or hers. However, unlike the drop down list, the simple combo
keeps all or some of the items in the list visible.
Drop down list. This has the same configuration as the drop down combo but differs in
the sense that items in the list cannot be edited.
Another form of the conversion problem implemented with the combo boxes are as
shown in Figure 1.35a and b
NOTE
A check box was added to the interface of Figure 1.35(b) to allow autoconvert. This
makes sense since some users who want to see their output immediately an input is
entered can do so by placing a checkmark in the auto convert check box.
40
For you to create an enhanced and user-friendly application, so many controls have to be
used. So far we have used the text box for inputs, the labels for output and for annotating
other controls without captions and the command buttons to execute commands. Two
other controls discussed are the option button and the combo box. Both the option button
and the combo box are used for input of options. However, the combo box has far
reaching applications than the option buttons.
FIGURE 1.36
User friendly and
interactive interface
for the Van Der Waal
problem.
Design Fundamentals
41
In Figure 1.36, the Use SI units check box is used to automatically select SI units from all
the combo boxes. This makes things faster if users inputs are in SI unit system.
NOTE
Different developers could have designed the interface differently. As a guide on
interface design, try to keep the form as small as possible and keep your control well
aligned. Here once the check box is selected, all the units are in SI. It makes the program
faster and more user friendly.
FIGURE 1.37
User interface for
conversion problem
using standard
controls and
Windows common
menu and toolbars
42
Navigational Design
Navigational design is a very broad aspect of window-based programming. In this
section, we discuss navigational design with respect to tab order and tab setting only. To
understand the importance of navigational design, we take a simple example using the
design shown in Figure 1.38
Design the Form shown in Figure 1.38 as follows
FIGURE 1.38
Understanding the
essence of navigational
design.
(a) Create the text boxes in the following sequence. The Mass textbox should be created
first, followed by the Temperature, Pressure and the Volume text boxes.
(b) Create the labels annotating the text boxes in any order.
(c) Create the command buttons in the following order; Clear Button first, Close second,
Next third and Execute last.
(d) Format the Form as shown
(e) Run the program.
NOTE
You run a program by pressing F5 or selecting start from the run menu. You may be
prompted to save, you can choose to ignore or save depending on the importance of the
changes you have made.
Design Fundamentals
43
(f) With the program at run mode, press the tab key. Focus should be shifted from the
Mass text box to the Temperature text box. On pressing tab again, you observe that
focus moves to the Pressure text box and then Volume text box. This of course is a
bad design. A good design allows the cursor to be initially set at the top left control
on the form and should move from left to right and top to bottom on the form as the
tab key is pressed successively.
To achieve design of this sort, you use the tab order of the controls which is a function of
the TabIndex property of each control. As you add controls to the form, the TabIndex of
each control is set to the next lowest number not already taken by the other controls on
the form. To achieve a good tab order, controls should be added to the form from left to
right and top to bottom. However, you can add controls arbitrarily and use the TabIndex
property to set the Taborder by giving the top left control a tab index of 0 and the next a
tab index of 1. This should continue until the TabIndex of each control has been set.
Apart from ensuring that focus moves in a logical manner when the tab key is pressed,
the Tabindex property is important when moving to a specific textbox on the form with
the keyboard. For command buttons you use Alt + [Underscored character in the caption
of the Control] to give focus to the command button. For a label, this is not possible since
the label can not receive focus at run time. Using Alt + [Underscored character in the
caption of the label] shifts focus to the control next in the tab order that can receive focus.
This is the principle used to move to a specific text box or combo box on the form. You
place a label beside ( or Ontop of ) a text box and set (or make sure) Tabindex of the text
box is one plus the Tabindex of the label annotating it. In this manner, Alt +
[Underscored character in the caption of the label] moves focus to the next control in the
tab order which is the text box or combo box as the case may be.
NOTE
The underscored or underlined character in the caption property of any control is usually
called the hot key(or access). You set the hot key by preceding the caption with an
ampersand. &Pressure makes P to be the hot key.
44
Problem Set 1
Question 1.1 a
Given the interface shown in Figure Q1.1. Outline the steps you will use to accomplish
the following using the properties window.
a) Give all the text boxes the same left ( use the second text box as reference)
b) Make the text boxes have the same size (use the third as reference)
c) Give the text boxes equal vertical spacing
d) What are the implications of giving them equal top
Question 1.1 b
Repeat Step Q1.1a using the Format menu.
Figure Q 1.1
Question 1.2
Hot keys in your form must be unique. Discuss
Design Fundamentals
45
Question 1.3
The Project Explorer of an application is as shown in Figure Q1.3. What are your
comments about the application? Can you advice the programmer based on your
comments.?
Figure Q 1.3
Question 1.4
a) Identify the controls in the menu editor of Visual Basic(Figure 1.28 a) . Hence or
otherwise, design the editor.
b)
Figure Q1.4b
46
Question 1.5
The drawing tool bar of MS Word is as shown in Figure Q 1.5. Write a short note on the
tool bar appearance making reference to buttons count, style and behavior. Hence or
otherwise design the tool bar
Figure Q1.5
Question 1.6
Design an interactive and user friendly interface needed to find the roots of a quadratic
equation of the form ax2+bx+c=0..
Question 1.7
Design the user interface needed to solve a simultaneous linear equation in two variables
using the Crammers rule
Hint: for equations of the form
ax + by = c
cx + cy = f
Using Crammers rule
X=
x
y
,y =
o
o
Where o =
a b
c b
a c
x =
y =
d e
f e
d f
Question 1.8
The principle of conservation of linear momentum is stated mathematically as
m1u1+m2u2=m1v1+m2v2
where m, u and v are mass, initial velocity and final velocity respectively. Subscripts 1
and 2 represent body 1 and body 2 respectively. When bodies move away with equal
velocity after collision then the momentum equation becomes
m1u1+m2v2=(m1+m2)v
Using option buttons, frame, check boxes and the input/output control, design an
interactive interface for this problem assuming that you want to determine the final
velocity of one of the bodies after collision or common velocity as the case may be. Use
check box to find out whether the bodies stick together after collision or not. Your
program interface should be able to handle units differences.
Design Fundamentals
47
Question 1.9
a) Using option buttons, check boxes, frame, text boxes, labels and command buttons,
design an interface that will be used to find one unknown from the four parameters
distance, time, acceleration and initial and final velocity using the equations of motion.
Use check boxes for the following assumptions
Uniform velocity
CHAPTER
2
Programming Fundamentals
Setting Objects Property Using Code
Visual Basic Data Types
Processing Data
Events and Event Procedures
Scope of Variables
Multiple - Form Applications
49
Programming Fundamentals
We spent the last chapter discussing user interface design. While this is very important
as far as Visual Basic is concerned, we have to understand that no matter how good an
interface may be, if it is not coded, it is as good as a beautiful car which lacks the ability
to move.
Code
1. Activate the form in question using the Type the name of the form
project explorer or the view menu.
2. As the form appears, you immediately Type dot(.) and observe that a menu
see all the objects in the form as well as appears exposing all the objects in the
the design properties of the form
form as well as the properties and
other attributes of the form(see figure
2.1)
3. Select the object in question and observe
that the properties window changes to
reflect all the design properties of the
selected object
4. Scroll to the desired design property and Scroll to (or type) the desired
change the default value of the property property and assign the new value to
to the new value
the property using the assignment
operator
Apart from the Width property, other properties of objects can also be changed. For
example, to change the Top property of an object say txtData to 3000 we write the code.
50
Me.txtdata.Top=3000
NOTE
Me is the synonym of the active form. You can use Me instead of the form name and
vice versa
When changing properties, we have to be very careful because data type mis-match may
cause unpredictable errors. As an example, let us change the text in txtResult to 30m/s.
You might be tempted to write the statement
Me.txtResult.text=30m/s
This is out-rightly wrong and Visual Basic will immediately change the font of the
statement to red(or any other colour as specified in options dialog ) signifying an error.
This error is usually due to data type mismatch (i.e the data type passed to the Text
property is not consistent with the data type expected). At this point, it is pertinent we
digress a bit and discuss Visual Basic data types before proceeding with our discussion
on changing properties using code.
Figure 2.1
Visual Basic Data types
51
Programming Fundamentals
Data
Figure 2.2
Data types supported
by Visual Basic
Object
Variant
Boolean
Date/Time
Currency
Double
Single
Long
Integer
Byte
String
Non Numeric
Numeric
Figure 2.2 shows that the two major categories of variables are Numeric and Non
Numeric. The Numeric category has six data types while the Non-Numeric category has
5 data types. Discussions on each of these data type follow
NOTE
The Variant Data type is not strictly non-numeric. Numeric data could also be variant
52
A data is said to be of Byte type if it is a whole number which falls within the range of
0 to 255. The implication of this is obvious. Negative numbers, floating or exponential
numbers and numbers greater than 255 are not Byte data types. As the name implies,
Byte data types occupy one byte of memory resource
Programming Fundamentals
53
approximation of the original number. For Science and Engineering applications, the
approximation does not cause any head ache. For Accounting applications, money
expressed in standard form has no single quantitative value. This problem is solved with
the currency data types. The currency data type stores as much as 15 digits to the left of
the decimal point and about 4 decimal places. This is okay since most currencies have at
most 2 decimal places. Currency data can also be expressed in standard notation when
there are more than 15 digits to the left of the decimal point. The range of the currency
data type is -922,337,203,685,477.5808 to 922,337,203,685,477.5807
NOTE
Any data enclosed in quote is regarded as a string. Hence they are non-numeric. The
following are strings 27, 87 , 37.45, 2.0E09 etc.
Strings are very important data types and will be discussed extensively in Chapter 5. The
range of characters accepted by a string(dynamic) can be between 0 and approximately
2 billion characters.
54
NOTE
By default, date values are stored in the form mm/dd/yy. i.e the first value is the month
value while the second is the day and the last the is month. E.g the date #3/4/2002#
means March 4th, 2002
This data type is used by advanced Visual Basic Programmers. An Object is an instance
of a class. Classes are discussed in volume 2 of this Text.
55
Programming Fundamentals
Prefix
Examples
Byte
byt
bytWest, bytNum
Integer
int
intResult, intCount
Long
lng
lngPlate,lngGas
56
Single
sng
sngKell, sngLenght
Double
dbl
dblPie,dblLimit
Currency
cur
curTotal, curIncome
String
str
strName,strClass
Date
dte
dteStop, dteStart
Boolean
bln
blnFail, blnState
Variant
var
varError, varTol
Objects
obj
ObjExcel, objWord
User defined
usr
usrEgbe,usrAnong
Some conventions use one letter prefix for variable names. These prefixes are not
common but are still used by old time Visual Basic programmers. Table 2.3 shows these
conventions
Table 2.3: Conventional one letter prefixes used to name Visual Basic variables
Variable type
Byte
Integer
Long
Single
Double
Currency
String
Date
Boolean
Variant
Objects
User defined
Prefix
y
n
l
g
d
c
s
t
b
v
o
u
Examples
yWest, bytNum
nResult, nCount
lPlate,lGas
gKell, gLenght
dPie,dLimit
cTotal, cIncome
sName,sClass
tStop, tStart
bFail, bState
vError, vTol
oExcel, oWord
uEgbe,uAnong
Postfixes used to identify Visual Basic variables are shown in Table 2.4. Remember that
these postfixes are special characters and can not be embedded in the name
57
Programming Fundamentals
NOTE
The
The prefixes and postfixes discussed above are only conventional. A variable can still be
declared with or without these prefixes/postfixes. However, always use prefixes so that
you can easily identify your variable type without scrolling to view its declaration. This is
especially important in very large programs.
Defining Variables
Defining variables means passing data to variables to store. After a variable is declared,
Visual Basic stores default values in the variables. The default values stored depend on
the type of variables. It is expected that you define your variables with appropriate data
before using it. Table 2.5 shows the default values stored in variables
Table 2.5: Default Values stored in Visual Basic Variables
Variable type
Default value
String fixed
String dynamic
Variant
Empty or 0
Date
12:00:00
Object
Nothing
At times, the default values assigned to variables make no sense. Hence, variables have to
be re-defined before being used. With very few exceptions, all variables in Visual Basic
are defined using Assignment Statement. These statements are usually of the form
58
strRegion= West
dblPressure = 2000.349
Zfactor! = 0.98
The three statements above are called Assignment Statements. Assigning data to
variables involve passing the value in the right hand side of the assignment statement to
the variable which is at the left hand side of the assignment operator. You can also
define a variable using another variable that has already been defined as follows:
Dim Length! As Single, Area! As Single
Length! = 34.4
Area! = Length! * Length!
When defining variables, two forms of errors always crop up. These are the Type
Mismatch and OverFlow Error. The Type Mismatch error occurs when a data of a
different type is passed to a variable of conflicting type. e.g passing a string data to a
variable declared as Integer(or any numeric type) invokes this error. The code
Dim nAge As Integer
nAge = 12 Years
invokes the error shown in Figure 2. 3 because nAge was declared as Integer and a string
data was passed to it.
Figure 2.3
Programming Fundamentals
59
Also if the data passed to the variable is greater than the maximum value expected by the
variable, the overflow error results. The Code
Dim nAge As Integer
nAge = 366448
invokes the Overflow error because 366448 is greater than the maximum numeric whole
number value expected to be passed to Integer variables. (i.e 366448 is not an integer
data type). When the code above is executed it gives the error shown in Figure 2.4
Figure 2.4
Visual Basic dialog
Showing overflow
error
Apart from direct assignment, other methods used to define variables are discussed below
All object properties come with default values. These values are usually of a particular
data type. The data type could be any one of the data types discussed earlier. It is very
important that a propertys data type be known before being assigned to variables.
Figure 2.5 shows the properties window for a TextBox control
60
Figure 2.5
Properties window
Showing some
Properties and property
Values(data) of the
TextBox Control
Nineteen properties are clearly visible from the properties window of Figure 2.5. The
data types of some of these properties are presented in Table 2.6
Table 2.6: Data types of selected properties of the TextBox control
Property
Data type
Name
String
Alignment
Integer
Appearance
Integer
BackColor
Long
BorderStyle
Integer
CausesValidation
Boolean
DataField
String
DataFormat
String
It is important that we know the data type of a property before attempting to interact with
it. Generally, the Name, Text, Caption and Tag properties of all objects are String
properties. Also, the Top, Width, Left and Height properties of all objects are Single
properties. Likewise, the Enabled, Visible, Cancel, Default and CausesValidation
properties are Boolean properties. The Value property may or may not be a Boolean
property. For example, the OptionButton has a Value property that is Boolean, while the
CheckBoxs Value property as well as the Horizontal and Vertical Scroll bar is an Integer
property. For avoidance of doubt, the Visual Basic Object Browser is used to confirm a
Programming Fundamentals
61
property type. Figure 2.6 shows Visual Basic Object Browser confirming the Value
property of the ProgressBar to be a Single property.
You view the Object Browser Window by selecting Object Browser from the View
Menu(Alt V O) or by pressing Function Key F2. With the Object Browser you can
confirm a property value type and make valid assignments devoid of errors. The
assignment statements shown in Listing 2.1 are all valid because the variable types do
not conflict with the property values used to define them.
Listing 2 .1: Defining Variables with non conflicting Objects property values
1:
Dim strGrade As String
2:
3:
4:
5:
strGrade=txtGrade.Text
lngLength= txtMeasurement.Width
6:
blnState=optState.value
Figure 2.6
Visual Basic Object
Browser Showing the
Value property of a
Progress bar as Single
Property
62
Though the Text property of all controls is a String property, its data can still be assigned
to numeric variables without always invoking the type mismatch error. For this to be
done, the data stored in the property value must be a numeric string otherwise the error
would still occur. This also applies to the Date and Boolean data types. Once the Text in
the TextBox translates to be a Date or Boolean value, then Visual Basic tolerates the
assignment otherwise Error 13(Type Mismatch) is triggered. Listing 2.2 shows how the
Text property is used to define Numeric, Date and Boolean variables.
Listing 2 .2: Defining Variables with non conflicting Objects property values
1: Dim dteAge As Date
2: Dim blnState As Boolean
3: Dim lngLength As Long
4: Dim strName As String
5: dteAge= txtAge.Text
6: blnState= txtState.text
7: lngLength=txtInput.Text
8: strName= txtinput.Text
In Listing 2.2, four variables; dteAge, blnState, lngLenght and strName are declared as
Date, Boolean, Long and String respectively(Line 1 to 4). Line 5 assigns the Text in
txtAge to the variable dteAge declared as Date in Line1. This assignment is conditionally
valid. If the Text in the TextBox is of the form mm/dd/yy (where mm and dd may be
any two digit number and yy may be any two or four digit number) then it is valid
because it conforms to the format. When the value 12/22/90 is entered then Visual Basic
translates the Text to be of the Date Type. However entering values of the form
12/22/90 or #12/22/90# results in an error. Also in line 6 when the data True or False
is entered in the TextBox then the assignment proceeds without error otherwise the
arrogant type mismatch error appears. Numeric values in the TextBox also go without
error because they are translated to be True Data. Line 7 proceeds without error if the text
in the TextBox translates to be numeric and within the Long range while line 8 is
globally fail safe because the variable type is same as the property value type. However
entering string outside the range accepted by string gives error due to overflow
NOTE
When entering texts in the TextBox, avoid the quotes. Adding them changes the sense
and length of the string. This also applies to Date. You only use quotes and hashes in
Strings and Dates only in direct assignments.
Programming Fundamentals
63
The InputBox function is similar to the Input Statement used in Qbasic and also used in
the same way the Qbasic Input statement is used. For e.g in Qbasic you define a variable
using the assignment as follows
Dim X! As Single
Input Supply the Value of X!; X!
Similarly, in Visual Basic you use the InputBox function as follows
Listing 2.3: Defining a variable using the InputBox Function
Dim X!
X! = InputBox(Supply the Value of X!)
On invoking the code in Listing 2. 3, the InputBox appears as shown in Figure 2.7
Figure 2.7
Visual Basic
InputBox requesting
The file function can also be used to define variables. Using the file function involves
using a command to open the file, and reading a line in the file and then assigning it to a
variable as shown in Listing 2.4
Listing 2.4 :Defining Variables using the files
1: Dim X$
2: Open C:\Egbe.txt For Input As #1
3: Input #1, X$
4:
Close #1
64
in Listing 2. 4, Line 2 opens the text file Egbe.txt in drive C. Line 3 reads the value in
the first line of the file and assigns it to variable X$. Line 4 closes the file. Detailed
discussions on files is covered in chapter 4.
NOTE
Using properties other than the Text and Caption to display data should be avoided
because it could be difficult to read accurately. You may also need to change the
BorderStyle of a label before using it to display output
To view the data in a one dimensional array, we often use the ListBox or Combo
control. Figure 2.8 shows the ListBox control used to display one dimensional array data
65
Programming Fundamentals
Figure 2.8
ListBox Control used to display one
dimensional array of data
The Flex Grid and flex array are the two most popular grid controls used to work with
two dimensional array. Figure 2.9. shows a Microsoft Flex Grid
Figure 2.9
Grid used to display
dimensional array of data
two
Though two dimensional arrays are also regarded as a multi dimensional array, we use
multi dimensional arrays to be arrays of dimension 3 and above in this section. Practical
examples of Engineering problems that lend themselves to three dimensional array are
not common. However, iterative problems involving matrices often lend themselves to
manipulations with 3 dimensional array. Array of grids and Treeview controls are used to
handle problems of this nature
66
Print Statement
The Print statement is used to print data to the Immediate Window. It is issued as a
debug.print statement as shown.
1.
2.
3.
4.
5.
6.
Statement 5 and 6 print 33 and 825 in the Immediate Window. View the Immediate
Window by pressing Ctrl + G or selecting Immediate Window from the View menu.
Figure 2.10
Using the MessageBox to
display Results
Figure 2.11
displaying descriptive result
in a MessageBox
Programming Fundamentals
67
NOTE
When viewing the content of an array using the local window, you would have to
collapse the plus sign beside the variable to enable you view the value of all the
subscripts in the array.
Figure 2.12
Displaying output
using the Local
window
Processing Data
Computer programs are written to perform one or more tasks. These tasks could be as
simple as adding two numbers or as complex as simulating a real life problem with
systems of partial differential equations. These tasks are accomplished when the data
stored in variables are processed using operators and functions.
Operators
Every programming language has a set of operators used to process data. Here we
discuss the operators under the following sub headings:
68
Arithmetic Operators
1. Addition ( + )
2. Subtraction ( - )
3. Multiplication
(*)
4. Division ( / )
5. Exponentiation ( ^ )
6. Integer division ( \ )
7. Modulus (mod)
Table 2.7 explains these operators with examples
Table 2.7 Examples with Visual Basic arithmetic operators
Operator
Symbol
Example
Remark
Addition
A + B ; 2 + 4 =6
A plus B
Subtraction
A B; 3 9 = -6
A minus B
Multiplication
A * B; 2 * 13 =26
A times B
Division
A / B; 48 / 5 = 9.6
A divided by B
Exponentiation
A ^ B; 2 ^ 3 = 8, 4 ^ 3 = 64
A raised to power B
Integer
Division
A \ B; 48 \ 5 = 9, 20 \ 6 = 3 Integer when
50\7 = 7, 45 \ 6 = 7
Divided by B
Modulus
mod
is
String Operators
The concatenation operator is the only string operator. It has the effect of joining two
strings together. E.g. Given the operation
"34" & "81" = "3481"
or with variables
SVA= "34" & "81"
The operator(+) when used with strings serves the same function as the concatenation
operator, it is therefore said to be overloaded.
69
Programming Fundamentals
Comparison operators
A Comparison operator is a character or symbol indicating a relationship between two or
more values or expressions. These operators include less than (<), less than or equal to
(<=), greater than (>), greater than or equal to (>=), not equal to (<>), and equal to (=).
Additional comparison operators include Is and Like. These operators are summarized in
Table 2.8
Table 2.8 Visual Basic Comparison operators
Operator
Symbol
Operator
Symbol
Greater than
>
<=
Less Than
<
Not equal to
<>
Greater Than or
Equal To
>=
Equal to
Note
The Like and Is operators are beyond the scope of this chapter, we will consider them in
chapters 4 and 5 respectively.
Precedence order
Exponentiation
Division
Multiplication
Addition
Subtraction
70
returns 14 because multiplication is performed first before addition. Also the assignment
statement
20 / 5 * 2
returns 8 instead of 2.
To override the default precedence, use parentheses around the portion of the expression
that is to be evaluated first. This rule of precedence is similar to the law of BODMAS
used in simple arithmetic. However, here we call it BEDMAS with the Exponentiation
operator replacing the OF operation.
When two operators of the same level of precedence are adjacent, Table 2.10 shows with
examples the sequence of evaluation of the expression
Table 2.10: Associativity of Visual Basic operators
Operator
Symbol
Evaluation
Example
Addition
Right to Left
2 + 3 + 5 = Associative
Subtraction
Right to Left
2 - 4 - 7 = Associative
Multiplication
Right to Left
3 * 5 * 6 = Associative
Division
Left to Right
12 / 3 / 5 = (12 / 3) / 5
Exponentiation
Right to Left
2 ^ 3 ^ 4 = 2 ^ ( 3 ^ 4)
Integer
Division
Left to Right
16 \ 4 \ 2 = (16 \ 4) \ 2
Modulus
mod
Left to Right
Functions
Operators operate on data and return data, which may or may not be of the same type
with the data. e.g. the Boolean (comparison) operators process numeric data and return a
Boolean data type. In the same vein, a function uses one or more operators and other
program statements to process data and return results, which may or may not be of the
same type with the data. E.g the Round function is used to round a number up to a
specified place of decimal. Its syntax is as follows:
Round(expression, numdecimalplaces)
Common examples of functions are the mathematical functions., date functions and the
Format functions Some of these are as shown in Table 2.11 and 2.12
71
Programming Fundamentals
Remark
Returns Absolute value of its argument
Returns Arc Tan of its argument
Returns Cosine of its argument in radians
Returns anti natural logarithm of its argument (ex)
Returns the Integer portion of its argument
Returns the Integer portion of its argument
Returns the Natural Logarithm of its argument
Returns a Single containing a random number. It may be used without an
argument
Returns a Variant (Integer) indicating the sign of a number
Returns Sin of its argument in Radian
Returns the real square root of its argument which must also be real
Returns Tangent of its argument in radians
Note
The difference between Int and Fix is that if number a is negative, Int returns the first
negative integer less than or equal to the number, whereas Fix returns the first negative
integer greater than or equal to the number. For example, Int converts -2.2 to -3, and Fix
converts -2.2 to -2. For positive numbers, they are essentially the same. The Fix of a
number is also given as Sgn(number) * Int(Abs(number))
Table 2.12:Date/Time Functions
Function
Syntax
DateAdd
DateDiff
WeekDay
WeekDayName
Remark
72
Month
Month (Date)
MonthName
MonthName(Month)
Yyyy
Q
M
Y
D
Year
Quarter
Month
Day of year
Day
w
ww
h
n
s
Weekday
Week
Hour
Minute
Second
Info
Some of the Date functions have more arguments than those specified in Table 2.12. The
missing arguments are optional arguments used to customize the functions. See chapter 5
and 6 on how to work with optional arguments.
As an example, we use the DateAdd function to add five second to the current time as
follows
Dim dteStart As Date
DteStart = DateAdd(s,5,Now)
In the DateAdd function used above, the interval string is s which means seconds is
used as our interval. Also, Now used as a parameter to the DateAdd function means the
current Time. It is also a Date function.
Programming Fundamentals
73
procedures are called Event Procedures. One object can have as much as thirty events it
responds to. For example the TextBox responds to 27 events. Think of an event as users
action directed towards an application. We can draw an analogy between Visual Basic
events and events in everyday life. Take the filament lamp for example. Once there is
power, you can manipulate the bulb to light in so many ways depending on users action.
Some of these include:
All these and many others are events that can be programmed to make the bulb light. For
a program to add two numbers, you can get the output by triggering the following
events(or performing the following actions) :
Event Procedures are usually written in the Form Code Module(or Code Window or
Form Module). Figure 2.13 shows the Form Code Window. You activate the code
window by selecting code from the view menu or clicking the view code icon in the
Project Explorer.
74
Figure 2.13
Form Module
Showing object
list and Procedure
list combo boxes.
Procedure List
Object List
Edit Box
Object List ComboBox(Also called Object List): Contains a list of all the objects
on the Form with at least one event. It also contains the form and a General listitem
used for non event procedure
Procedure List ComboBox(Also called Procedure List) : Contains all the events of
the selected object in the object list or all the user defined procedures if the General
List item is selected in the object List
Edit Box : Area where all the codes are written in Procedures.
Programming Fundamentals
75
Figure 2.14
Form Module Showing
an Event procedure
Note
The Option Explicit statement is used to force users to declare all variables explicitly.
Always make sure it appears in the EditBox of the code window before writing any
program. If does not appear, you can type it yourself or add it from the Options Dialog in
the Tools menu
76
Figure 2.15
Form module showing non
default event procedures
(default & non default)
Note
The default event procedure of an object is created by just selecting the object from the
Object list or by double clicking the object on the form.
The steps used in creating event procedure of an object are now summarized:
With the code window open, you select the object name from the object List Combo.
This creates the default event procedure of the object.
With the cursor at the body of the default event (or any other event) procedure of the
object in question, you activate the procedure list and select the event of interest. This
automatically creates the header and footer of the desired event procedure.
Info
You move from one Event procedure to the other by pressing Ctrl + Up/Down arrow or
by pressing Ctrl + PageUp/Down. The major difference between the two is that the
former takes you to the first line of the Next event procedure while the later takes you the
header of the Next event procedure.
Some commonly used events of objects are as shown in Table 2.14
Programming Fundamentals
77
Table 2.14:
Event
Click
Description
This event fires whenever an object which respond to a click event
is clicked directly or indirectly
Change
DblClick
The Double Click event occurs when you double click an object.
Note that it will be very difficult for the double click to occur if
program has to respond to both clicks and double clicks.
Load
Unload
Timer
Keypressed
Occurs when any key is pressed. It is used to prevent the user from
pressing some keys or for accepting selected keys only from the
keyboard. .
Validate
Unloadquery
LostFocus
GotFocus
MouseDown
Used to detect which mouse button has been clicked. After this
event is triggered, the Click and MouseUp events are activated in
succession.
KeyDown
MouseMove
78
Early in this chapter we saw how to change objects properties using code. For example to
change the text in a TextBox to Hello World you write the code
Me.txtShow.Text = Hello World
For this to be fully functional, it has to be written in an event procedure. To test this
code, follow the following steps
1. Design an interface with a CommandButton(cmdExecute) and a TextBox(txtShow).
2. Open the Click event procedure of the CommandButton
3. Write the statement
Me.txtShow.Text = Hello World
In between the header and footer of the click event procedure of the
CommandButton(see Figures 2. 16a and b )
Figure 2.16a
Form and Code window
For Hello World Program
Figure 2.16 b
Code window for the
Hello world program
79
Programming Fundamentals
Note
Because the code was written in the Click event, Right Click operations can not trigger
this event. To write code that will function for the left , right or middle mouse button, use
the MouseDown or MouseUp Event
6. End the program by pressing the Close button of the Forms Control Box or the End
Button in the Standard ToolBar(see Figure 2.17 )
Figure 2.17
Standard ToolBar
Showing the Start and
End Button.
End Button
Start Button
7. Activate the Form by Clicking View Object or the View object button on the project
Explorer or by pressing Shift + F7
8. Add another CommandButton to the Form. Name it cmdClear and Caption it Clear
9. Open the MouseDown Event of cmdClear and place the code
Me.txtShow.Text = vbNullChar
inside the MouseDown event procedure.
10. Save and then Run the program again. Observe that on clicking the Show button,
Hello World appears on the TextBox while on clicking Clear, this greeting is
cleared. You can display Hello World again by clicking show.
The effect of the code in the MouseDown event procedure is to clear the Text in the
TextBox. i.e to assign a null character to the TextBox. This has the same effect as
assigning an empty string to the text as follows
Me.txtShow.Text = ""
Other properties like Font, ForeColor, Height, Width Visible etc can also be changed at
runtime for any control using the same technique.
80
These properties are said to be read-only and hence can not be modified at runtime in an
assignment statement. Common examples of read-only properties are Name and Index
properties. ReadOnly properties can only be changed at design time and not at runtime. It
is important that you use the object browser to browse each property and know its type
and assign-status. Figure 2.19 shows the object browser identifying the Multiline
property of the textbox as read-only.
Figure 2.19
Object Browser showing
Read-only property. You
activate the object Browser by
Selecting object browser from
the view menu or by just
pressing F2
Programming Fundamentals
81
Example 1
This example uses a TextBox, a Label and three CommandButtons. A program is written
in the click event of the First CommandButton such that on clicking it the number
entered in the TextBox is doubled and then displayed on the Label control (with fixed
borders) below the TextBox. The Second Command Button is used to Clear the
TextBox and Label while the Third Commandbutton is used to unload(End or Close) the
application.
The Interface used for this program is as shown in Figure 2.20. Here two labels are
placed beside the TextBox and the main Label to annotate it. These labels are captioned
Input and Result respectively.
Figure 2.20
Interface for Example 1
Quiz
Discuss the problem(s) with the interface designed in Figure 2.20
The Code used for this program is written in the Click Event procedure of each
CommandButton is as shown in Listing 2.5
82
4:
lblResult.Caption = Y
End Sub
In Listing 2.5a, two variables, X and Y are declared as Double in Line 1
Line 2 assigns the Text in txtInput to X. This is the basic input statement in Visual Basic
Line 3 doubles the data in X and then assigns it to Y.
The data in Y is then used to set the caption to Y. Hence the label displays the data
stored in Y which is twice what was entered in the TextBox.
Note
A Method of a control describes the action performed by the control. SetFocus is one of
the methods of the TextBox control.
Quiz
How is the End statement different from the Unload Me Statement?
Programming Fundamentals
83
Add the code in Listing 2.5 a to c in the code window and test run the program. Note you
observation
Example 2
This example calculates the number of moles of an ideal gas using the Van Der Waal
equation of state expressed as
n=
PV
RT
Figure 2.21
Interface for the Van Der
Waal problem
The Code used to drive the interface shown in Figure 2.21 is as shown in Listing 2.6
Listing 2.6: Code for the Van Der Waal Problem
Private Sub cmdCompute_Click()
1:
Dim T As Double,P As Double, V As Double, n As Double
2:
Const R =0.0802
3:
P = txtPressure.Text
4:
V =txtVolume.Text
5:
T =txtTemperature.Text
6:
n = P*V/(R*T)
7:
lblMoles.Caption=n
84
End Sub
The Code in Listing 2.6 is similar to the code in Listing 2.5. The difference is that the
three TextBoxes are used for the three Input(Line 3 to 5). Line 6 performs the actual
calculation while line 7 displays the result as usual. The code for the Clear and Close
Button can easily be written from Listing 2.5 b and c respectively.
Scope of Variables
Having understood the importance of variables in programming, we now discuss the
types of variables with respect to scope. Under this category, we identify four types of
variables; these are
1).
2).
3).
4).
Public Variables
Static Variables
Static variables are procedure level variables declared with the Static keyword instead of
the Dim keyword. They are different from local variables(conventional procedure level
variables) in that they retain their values after each procedure call. To keep count of the
number of times a CommandButton is clicked, we declare a static variable as follows
1:
2:
Static n As Integer
n = n + 1
with the declaration and assignment above, the value of n is incremented each time the
procedure is called. Observe that n used in line 2 was not initialized before being used.
Ordinarily, we are supposed to initialize it to 0 before being used. However, because
Programming Fundamentals
85
Visual Basic stores a default value of zero in a numeric variable declared, it makes the
initialization option worthless. Another reason for not initializing the variable is that it will
defeat the rationale behind Static variables because on each procedure call, a value of zero
is assigned to it and hence overwriting the last value stored in it at the end of the last
procedure call. As an example, we consider a simple program that ends an application
after a CommandButton is clicked three times. This is as shown in Listing 2.7
Listing 2.7:Using static variables in Event procedure
Private sub cmdExit_Click
1:
Static I As Integer
2:
I=I+1
3:
If I = 3 Then End
End sub
Line 1 declares a static variable I and line 2 increments it each time the procedure is
called. Line 3 ends the Application if I is equal to 3
Note
When using a module level variable, make sure the procedure in which it is defined is
called first before the procedure in which it is used.
86
Figure 2.22
Form window Code window showing a
module and procedure level variable. The
Module level variables are declared under
the Option Explicit statement while
procedure level variables are declared
inside a procedure.
Public Variables
Variables that are available to all procedures in all the modules in a project are said to be
Public Variables. There are two types of public variables;
The Form object Public Variable
The Standard Public variables are usually declared in a standard module and have
global scope as far as the project is concerned. As the name implies, the Form object
public variables are available to all the procedures in a Form and other Forms as far as
the container Form is properly referenced. For example; given the variable X1 declared
in the declaration section of the Form1 as
Public X1 as Double
You can access the data stored in this variable from another Form as follows
txtResult.Text = Form1.X1
Note
A variable declared in a standard module with the Dim keyword has Public scope. A
standard module is added to the project by selecting Add module from the project
Explorer and then click Open .
Programming Fundamentals
87
Programming Accessories
Comments
It is good practice to always add comments to your program. Comments are not
executable statements but are added for users information. A program with comments is
easier to read than a program without comments. Comments appear in programs in two
ways.
1. Comments at the beginning of a new line, e.g.
'Input process starts here
The single quote is used to indicate comment. Apart from single quote, you can also use
the keyword Rem e.g.
Rem output data to a file
In Visual Basic, Rem is not popular, it was only added for backward compatibility.
2. Comment after a statement.
Comments can also appear after a statement as follows
X1 = -B/(2*A) Quadratic root when discriminant is zero
Line Continuation
When Visual Basic statements become too long, need may arise to continue them on the
next line. In situations like these, we use the line continuation character (i.e. underscore)
to effect it.
Given the statement written over one line as
X1 = (-B + SQR(B^2 4 * A * C))/(2*A)
You can write this over two lines as
X1 = (-B + SQR(B^2 4 * A * C))/ _
(2*A)
NOTE
The underscore is used as the line continuation character. A space has to be typed before
the underscore. Keywords or functions names have to be written completely before or
after the line continuation character.
With strings, the line continuation character is not used in the conventional way.
Consider the string
A$ = "Visual Basic for Science, Engineering and Maths"
88
Observe how long the statement is, you can use the line continuation character to
continue it as follows
A$ = "Visual Basic for Science, Engineering" & _
"and Maths"
Observe that the opening quote was closed before invoking the line continuation
character. Here you need ampersand , space and underscore for line continuation
Line Termination
In Visual Basic, the line termination character is the colon. Two or more statements
separated with colons have the same effect as writing them over two lines e.g.
The statement
X = 9
Y = 7
T =2*X-4
Can be written in a single line as
X = 9: Y=7: T = 2*X - 4
Line Numbers/Label
Because Visual Basic wad derived from the Basic, the old Basic technique of numbering
each line is supported by Visual Basic.
A line is numbered by defining the number and placing a colon after it before writing a
statement e.g.
2: X1 = -b/(2*A)
A label is the same as a line number only that it consists of alphabetic characters and not
numbers. e.g.
First: X1= -b/(2*A)
Here first is a line label.
Line numbers and labels are useful when working with the GOTO Statements and its
derivatives. At times, line numbers and labels are added to enhance code analysis.
Programming Fundamentals
89
With Block
The with block is used to factorise an object name from a block of statement. This is
found useful when a object is being over referenced within a segment of code. Consider
the code
txtInput.Text = ""
txtInput.SelStart = 0
txtInput.SelLenght = Len(txtInput.Text)
txtInput.SetFocus
In the code above, observe that the object name was used 5 times in just four lines. You
can make things easier for yourself by factorizing the object name using the With block
as follows
With txtInput
.Text = ""
.SelStart = 0
.SelLenght = Len(.Text)
.SetFocus
End With
Once a with block has been opened, you only use dot to refer to the object without
referencing the object since the object has already being factorised. Also, it worthy to
remember that the with block has to be closed with End With otherwise a compile
error interrupts.
90
drop down the startup object combo and select the Form you want to start up
with. Click OK to close the dialog.
Figure 2.23
Visual Basic project properties
dialog used to select start up
object(form). You invoke the
start up form by selecting
properties from the project
menu.
(f)
At run time, you move from one Form to the other using the show and hide
methods of the Form. E.g. for an application with two Forms, you would usually
have Next and Back command buttons that will enable you move to Form2 and
Back to Form1 respectively.
In the Next command Button of form1 you write the code
Private sub cmdNext_clik()
Form2.show
Form1.Hide
End Sub
Also, in the back command button of form2 you write the code
(g)
(h)
Programming Fundamentals
91
In addition to the Hide and Show methods of the Form, two other commands are
used in manipulating Forms. These are the Load and Unload commands which
are discussed below
Load: This command places the Form in memory but does not display it on the screen.
E.g.
Load Form3
Load Form4
When the show method is invoked, the load command is automatically called.
92
Unload: This command is used to remove a Form from memory, thereby releasing
memory used by the Form
e.g.
Unload Form1
NOTE
Showing a loaded Form does not call the Load event of a Form and likewise hiding a
Form does not call the Unload event of the Form.
Programming Fundamentals
93
Problem Set 2
Question 2.1
Differentiate between the following Events
a) Lost focus and Validate Event
b) MouseDown and Click
c) KeyDown and KeyPress
d) Load and GotFocus
Question 2.2
What is/are the implications of placing the End statement in an event procedure which
performs some calculations.
Question 2.3
Discuss the merit and Demerit of using the Label for Output
a) Caption property of a label
b) Text property of TextBox Control
c) Enabled property of any control
d) Height property of any control
e) Slider Control
f) Message Box
g) Files
Question 2.4
Discuss the importance of the following
a)
b) Declaring variables
c) Understanding property values types and assign status
Question 2.5
How is the UpDown control different from the slider control. Using suitable windows
examples, discuss the application of each
Question 2.6
Given the interface shown in Figure Q2.6, Write a program to perform the following
format operations
a)
b)
94
c)
Question 2.7
Design and implement a program to find the roots of a quadratic equation of the
form ax2 + bx + c using
a) Only TextBoxes for input
b) Only InputBoxes for Input
c) Only messageBox(es) for output
Question 2.8
Design and implement a program for the solution of a simultaneous linear equation
in two variables using crammers rule. Make provision for users to format their
output.
Question 2.9
The Friction factor(f) under laminar flow is defined in S. I. unit as as
f =
64
N Re
Programming Fundamentals
N Re =
95
ud
Figure Q2.10
Question 2.11
Design and implement a program to find the LCM of three integers A, B and C
Question 2.12
Design and implement a program to convert a number form Base to 10 any Base n
96
Where 2 n 10
Use a text box and updown control for output base
Question 2.13
Design and implement a program that converts a number from Base n to Base 10
Where 2 n 10
Use slider or Scroll bar for inputbase
Question 2.14
Design and implement a program that converts a number from Base m to Base n
where 2 n 10 and 2 m 10
Use as many controls as possible.
(a)
Question 2.15
The terminal velocity (Vt) of a spherical water droplet is given by
Vt =
2 Fg
cl a A
Fg = Vl w g
4
V = R 3
3
A = R 2
(b)
where
fg= gravitational force, N
R= radius of droplet, m
a= density of air, Kg/M3
g= gravitational acceleration. M/s
w density of water, Kg/M3
V = volume of droplet, m3
C= drag coefficient
A = Cross sectional area of particle
Design an implement a program to evaluate the terminal velocity such that all the
inputs are entered in form1 and the outputs (vt, V, fg and A) are display form2.
You program should have Next and Back Button to enable user navigate easily.
From form1 to form2.
Repeat problem a above such that the user is instructed to coefficients of either
0.4, 0.5, 0.6, 0.65 or 0.8.
Hint: Enter ,the values of the drag coefficient in a combo box using the list property. The
combo box should be read only.
CHAPTER
3
Control Structures
Decision Structures
Decision statements
Decision functions
For Next Loops
Do Loops
Exit and Go To Statements
Dynamic Interface Design
98
The way in which the statements of a program are arranged is called the structure of the
program. There are three basic structures in a program. These are the sequential structure,
decision structure and loop structures. The codes written in the last chapter constitute a
sequential structure because the statements are executed one after the other consistent
with how the are arranged. However, in a decision structure, one set of statement is
executed from a set of two or more mutually exclusive statements based on a condition.
The Loop structure as the name implies is used to execute a sequential, decision or
another loop structure repeatedly. In recent times, programmers have often used the term
control structures to mean the decision and loop structure. This chapter focuses on all the
forms of decision and loop structure available in Visual Basic.
Decision Structures
Having understood the flow of programs from data to variables and object properties and
back to object properties in a sequential top down manner, we now consider some
examples of conditional executions.
x - 3 , x 3
g= 2
..................................................................................................... 3.1
x - 1, x < 3
Equation 3.1 implies that for values of x greater than or equal to 3, g should be evaluated
using the upper relationship i.e. g = x 3 . Otherwise g should be evaluated using
g = x2-1.
Symbolically, we represent our problem as shown in Figure 3.1
In Figure 3.1, our interest lies in the section represented with dash lines. The flowchart
shows that we have two mutually exclusive set of statements to evaluate. If the condition
in the decision box evaluates to true then flow transfers to the right of the decision box.
otherwise, the statement to left is evaluated. In either case, g is printed before the
program is terminated. Programmatically, the problem stated above cries for decision
structure. A decision structure is used to select one of two or more blocks of statement(s)
for execution. Using the IF Then Else structure, we represent the problem discussed
above in Listing 3.1.
99
Control Structures
Figure 3.1
Flow chart
Showing a decision
Structure
Start
Input x
Else
If
x
g = x2 1
Then
g =
x3
Print g
Stop
Listing 3.1 Using decision structure in Visual Basic
Option Explicit
Private Sub Form_Load()
1:
Dim X As Double,G as Double
2:
X = InputBox("Enter X")
3:
If X >= 3 Then
4:
G = SQR (X-3)
5:
Else
6:
G = X ^ 2-1
7:
End If
8:
MsgBox " Value of G is " & G
End Sub
In Listing 3.1, line 3 is the header of the decision structure. Here, an If statement is used
to test the condition. If the Boolean expression evaluates to true, then the line following
the If statement(Line 4) is evaluated, otherwise, the line following the Else statement
(Line 6) is evaluated. Line 7 is the End If statement used to close the If structure. The
End If statement signals the End of the decision structure. Omitting this statement renders
100
the If statement incomplete and consequently invokes a compile error as shown in Figure
3.2
Figure 3.2
Visual Basic message
Box displaying a compile
error due to missing
End If statement
NOTE
Opening an If is like opening a structural bracket and hence requires an End If to close
the structure(or structural bracket). A similar error occurs if an End If occurs without a
matching If.
The code in Listing 3.1 was evaluated with only one statement between the If statement
and the Else statement hence we say the If block has only one statement. Also, the
Line(s) between the Else statement and the End If statement constitute the Else block.
Though only one statement exist between the If and Else block, it is possible to have
more than one statement in both blocks. Another feature of the codes in Listing 3.1 is that
when the If block is not evaluated, then the Else block is automatically and
unconditionally evaluated thus making the Else block the default block which only
evaluates when the If block fails the If condition test.
101
Control Structures
The difference between Listing 3.1 and Listing 3.2 lies in line 3. Line 3 of Listing 3.1 has
only the Else statement with implication that if all other conditions fail, its block should
be evaluated unconditionally. However, Listing 3.2 has the Else If statement in line 3
instead of the Else statement. The Else If statement is similar to the If statement of line 1
in that both have a Boolean expression(condition) and a Then keyword. The difference
between the two is that the If statement is used to start a decision structure while the
Else If statement is used to test another condition in case the If statement evaluates to
False.(i.e it complements the If statement ).
The major difference between a decision structure with Else statement and a decision
structure without an Else statement is that with the Else statement at least one block of
statement(s) would be evaluated. However, in a decision structure without an Else
statement, it is possible for non of the blocks to be evaluated if non of the conditions
evaluate to True. For e.g If line 5 of listing 3.2 is replaced with the statement
5:
non of the statements would be evaluated when x = 3 because both would evaluate to
false and hence both block of statements are skipped.
Listing 3.2 is shown symbolically in Figure 3.2.
Figure 3.3
Start
Input x
Else
x > =3
Then
g = SQR( X 3)
X< 3
g=X^2-1
Print g
Stop
102
Figure 3.2 shows the symbolic representation of the ElseIF statement. It is used when an
If statement occurs immediately after an Else statement. Observe that in Figure 3.2
nothing was done in the Else arm of the ElseIf decision statement. This makes the second
condition baseless and hence equates Figure 3.1 to Figure 3.2. In spite of the redundancy
of the Else arm, Figure 3.2 is more explicit than Figure 3.1. For a full occupation of
Figure 3.2, a third condition needs to be introduced such that its block will be represented
in the Else arm of Figure 3.2. Equation 3.2 shows a problem with three mutually
exclusive conditions. A logic diagram for equation 3.2 is shown in Figure 3.3. The code
used for the implementation of the problem is as presented in Listing 3.3
x -3
g= 2
x -1
2x 9 ,
x>3
x <3
............................................................................. 3.2
x=3
103
Control Structures
due to users unexpected interactions with programs. In cases like these either the default
value is assumed or a message issued out. The flow chart for this problem is as shown in
Figure 3.4. Apart from using variables in conditional statements, one can as well use
object properties. One of the most widely used object properties used in conditional
statements is the value property of OptionButton(and CheckBox). The value property of
OptionButtons are Boolean properties and hence lend themselves easily to manipulations
with decision structures.
Figure 3.4
Flow chart showing the
ElseIf structure with the Else
Block
Start
Input x
Else
If
x>3
If
g =
X< 3
g =2* X -9
Then
g=X^2-1
Print g
Stop
x3
104
Figure 3.5 shows a Visual Basic Form for a temperature conversion routine.
Temperature value entered in the text box are converted to Kelvin using the code shown
in Listing 3.4.
Figure 3.5
Demonstrating conditional
Statement with a conversion
problem
Control Structures
105
QUIZ
If all the Options in Figure 3.5 have values of False(i.e are not selected) then non of the
conditional blocks(or statements) in Listing 3.4 would be evaluated. Under what
condition can this occur and how can this be avoided when designing the interface?.
Constructing Boolean Expressions
Recall that Boolean variables store Boolean data (i.e. TRUE or FALSE) which can be
assigned to it in a direct assignment statement as
Dim X As Boolean
X= TRUE
Or in a Boolean algebraic expression as
Dim X As Boolean
X = 15 > 9
Or with object properties as
Dim X as Boolean
X=optCelsius.Value
In the last expression, since 15 > 9, then X is assigned the value True. You can also
have an assignment statement of the form
X = optCelsius.Value
Replacing Line 3 in Listing 3.4 with the above Boolean expression , we have
If X = True THEN
Or as
If X THEN
This makes it shorter though less readable than the former. The utility of Boolean
variables is enjoyed when using compound and more involved Boolean expressions
involving the logical operators And, Or and Xor. This is because these logical operators
are used to join two(or more) simple relational expressions to form compound
expressions. For example the range
3 < x < 10
is written using logical operator as
X > 3 And X < 10
Or as
3 < x And x < 10
106
The Truth Table for the logical operators is as shown in Table 3.1
Table 3.1 Truth Table for Visual Basic logical operators
a
B
a OR b
a XOR b a AND b
NOT a
a EQV b
T
T
F
F
F
T
F
T
T
F
F
T
T
F
T
F
T
T
T
F
F
T
T
F
T
F
F
F
NOTE
a and b are Logical Constants
We demonstrate an example on the utility of the compound conditional expression with
the interface shown in Figure 3.6
FIGURE 3.6
User friendly
interface for
temperature
conversion using
option buttons as
input control for
temperature unit
The interface is used to inter-convert temperatures from one unit to the other by selecting
appropriate input and output unit. The conversion factors used for this problem are as
shown in Table 3.2
Control Structures
107
108
Listing 3.5 does not need an explanation. It is the programmatic representation of Table
3.2. When the convert command button is clicked, the input and output option buttons
group are inspected and the selected option noted. One of the statements in Listing 3.5 is
executed based on the selected input and output options. The result is then displayed in
the output label(Line 36)
Nested If Structure
A decision structure which appears inside another decision structure is called a Nested
Decision Structure. Examples of nested decision structure abound in Visual Basic
applications. From a far perspective, a nested If structure could be seen as ElseIf
structure, hence it becomes imperative that we understand the difference between an
ElseIf structure and a nested decision structure. The following points should be noted
about the Nested If Structure.
If structure formed in the Then part of any decision structure is a nested If
If structure formed in the Else part of a decision may either be a nested If or an ElseIf
If structure formed in the Else part of a decision structure is an ElseIf when the Else
and the If structure are adjacent(such that logic can flow directly from the Else to the
If without executing any statement).
Control Structures
109
If structure formed in the Else part of a decision structure is a nested If when one or
more assignment(or Input or Output) statement(s) separate the Else from the If.
All nested If structures must have a corresponding nested End If statement.
The number of End If in a program should be equal to the number of nested If plus
the number of independent If .
110
34:
If optC2.Value=True Then
35:
y = 5/9 * (x 492)
36:
ElseIf optK2.Value=True Then
37:
y = 5 * x/9
38:
ElseIf optF2.Value=True Then
39:
y = x - 492
40:
ElseIf optR2.Value=True Then
41:
y = x
42:
End If
43: End If
44: lblResult.Caption = Y
End Sub
So far, all the decision structures considered have the Else part. At times, If structures can
be written without the Else part. The implication of this is that the statements in the
structure should be evaluated only when the condition under consideration evaluates to
True otherwise the block of statement should be "skipped". This form of decision
structure is called the If Then End If structure. Figure 3.7 shows a Skeletal flow
chart showing the IfThen End If structure.
Programmatically, the If Then End If structure takes the form
If Boolean Expression Then
:
:
End If
Typically, the If Then End If structure is used when the Else part of the structure is
neglected in the statement of problem e.g. to perform a calculation only when the input is
numeric you use the If Then End If structure as shown in Listing 3.8
Control Structures
111
Figure 3.7
Skeletal Flow Chart
showing the If Then
End If structure
112
2).
E.g.
If X > 0 Then
:
End If
If X < = 0 Then
:
End If
If X = 0 Then
:
End If
3) To enclose the Exit ~ statement
If Then
Exit ~
End If
NOTE
The
The character ~ is used here to mean any of the control statement like Sub, Function,
Do, For or Property. This will be discussed at the later part of this chapter.
113
Control Structures
Block #2 Statement
.
.
.
Block #2 Statement
Case Alternative #n
Block #n statement
Block #n Statement
.
.
.
Block #n Statement
End select
#2
#n
#1
#2
#n
The following comments about the syntax of the Select Case structure should be noted.
The expression can be any mathematical expression that returns any defined Visual
Basic data types.
When the expression is a Boolean expression then only two alternatives are possible .
These are case True and case False,
The expression may also be a variable or a mathematical expression
The alternatives can be any one of the following. (a)Numeric or string scalars like,
0,3,-4, Celsius,
Port Harcourt. #2/01/03#, TRUE or even variables or
constant(b)Range of values e.g Case is > 5,Case is < 15,Case is = 9 or Just case 9,
Case 10 To 15.(c) Enumerated Scalars/Ranges e.g Case 2,3,4,3,5; Case 2 to 10, 20,
23,is > 30 (d) Default Case e.g. Case Else
x1 =
b + b 2 4ac
2a
- 3.3 a
b b 2 4ac
2a
- 3.3 b
and
x2 =
114
Equation 3.3a and b depends on the discriminate D given by b2-4ac. Three cases are
possible. These are.
Case D > 0
x1 =
b+ D
b D
: x2 =
2a
2a
Case D = 0
x1 =
b
b
: x2 =
2a
2a
Case D < 0
x1= imaginary root : x2= imaginary root
The select case structure is demonstrated programmatically in listing 3.8 using the
interface of figure. 3.8
Figure 3.8
Interface for the Quadratic
Roots determination
Control Structures
115
11:
Case IS = 0 Just Case 0
12:
X1 = -b/(2*a)
13:
X2 = X1
14:
Case is < 0
15:
X1 = imaginary root
16:
X2 = imaginary root
17: End select
18: lblResult1. Caption = X1
19: lblResult2. Caption = X2
End sub
Private Sub cmdClear_Click()
22: txtA.Text = vbNullChar
23: txtB.Text = ""
24: txtC.Text = Chr(32)
25: lblX1.Caption = Chr(32)
26: lblX2.Caption = ""
End Sub
Private Sub Form_DblClick()
29: End
End Sub
Line 2 declares X1 and X2 as variant because we expect to pass either numeric or non
numeric data to it. Line 6 is the header of the select case structure, in this case the
expression is D. The different cases are in line 7, 10 and 13 while the corresponding
blocks are respectively in line 8 and 9, lines 11 and 12, lines 14 and 15. Line 16 is the
footer of the select case structure. Lines 9,10,12,13 assigns a numeric value to X1 and X2
while lines 15 and 16 assigns a non Numeric value to X1 and X2. Since X1 and X1 were
declared as Variant, these mixed mode assignments are OK. This is actually one of the
advantages of using variant variables. A flow chart showing the select case structure is as
shown in figure 3.9
116
Figure 3.9
Flow chart showing
Select Case Structure
Case 1
Statement 1a
Select Case D
Case 2
Statement1b
Case 3
Statement 1c
Case 4
Statement 1d
Figure 3.10
Candidate interface for
Nested Select Case.
Control Structures
117
118
39:
Select case cboInput.Listindex
40:
case 0
41:
y = 5/9*(x-32)
42:
case 1
43:
y = 5/9 x (x + 32)
44:
case 2
45:
y = x
46:
End select
47: End select
48: lblOutput.Caption = y
End sub
The flow chart for the nested selected case structure is as shown in Figure 3.11
Figure 3.11
Flow Chart for
Figure Nested Select
Case
Input
Index
Case 0
Case 1
Output
Index
Output
Index
Case 0
Case 1
Case 2
Case 0
y=x
y = x+273
y = 9/5x+32
y=x
Case 1
y = x+273
Case 2
Output
Index
Case 2
y = 9/5x+32
Case 0
y=x
Case 1
y = x+273
Case 2
y = 9/5x+32
Decision Statements
Like most other languages, Visual Basic has statements that are conditionally evaluated
depending on some scenerios. These statements are different from the structured form
Control Structures
119
discussed earlier because they lack the End If (or End Select) statement. They are
discussed below
If Then Statement.
The one line if statement is most times called the logical If (or Boolean) statement. It is a
variant of the If Then End If statement that is preferred when only one statement is to be
evaluated if a condition is true. Here, because of the absence of statements in a block, the
End if keyword is not required e.g.
If X > 5 Then X = X - 6
NOTE
The
When the End of line statement is used(whether implicitly or Explicitly), it converts the
If Then statement Or If Then Else statement to the structured form which requires a
compulsory End If.
Decision Functions
The following decision functions will be discussed here.
IIF function
Switch function
Choose function
The decision functions evaluate more than one statement and return one value. This
value is usually the value that matches the expression argument of the function. When
using decision functions, it is important to note that all statements in the functions are
evaluated but only one is returned. The implication of this is that all the statements in the
functions must return a valid Visual Basic data type
120
IIF Function
This is actually a one line IF Then Else statement expressed as a function which returns
one of two mutually exclusive results. The syntax of this function is
= IIF(condition, TrueStatement, FalseStatement)
In terms of the IIF function equation 3.1 is
G=IIF(X>3,SQR(X-3),X^2-1)
NOTE
Before using the IIF function, make sure its last two arguments return any of Visual basic
valid data types. Always check very well before using the IIF function because both the
TRUE and FALSE part are evaluated but only one is returned. As a consequence of this,
for the function above, passing a value less than three results in an error using the IIF
function unlike the IF Then Else statement or IF Then Else structure
Switch Function
This is similar to the IIF function since it always return a value. However, unlike the IIF
function, multiple conditions are tested and the value returned depends on the condition
that first evaluates to True.
The syntax of the switch function is
=
switch
(condition1,
statement1,
condition2,
_
statement2,condition3, statement3, conditionn, statementn)
QUERY
Can the IIf function/switch function be nested
An example problem using the switch function is demonstrated using the interface of
Figure 3.5 and driven with the code in listing 3.10
Listing 3.10: Using the switch function
1:
Dim
x As Double, Y As Double
2:
X = txtInput.Text
3:
Y = Switch (optCelsius.Value, x + 273,optRankine,1.8*x
opt.Fahrenheit, 5/9 * (x + 460)
4:
lblResult.Caption = y
121
Control Structures
Observe how the switch function was used to rewrite Listing 3.8. This simplifies the If
Then ElseIf structure when only one statement exist in each of the blocks. Based on the
fore going, we can make the following comments about the switch function
1.
The switch function is to the multiple mutually exclusive IfThenElseIf
statement just as the IIF function is to the If Then Else statement/structure.
2.
Only one statement can be evaluated when any condition is true.
3.
All the statements must return a value.
4.
All the statements are evaluates but only one returned.
Choose Function
This is like the Select Case structure expressed as a function. It selects and returns a value
from a list of arguments. The syntax of the choose function is
=Choose(expression,
...statement n)
statement1,
statement
122
Figure 3.12
Conversion problem
using the ComboBox
123
Control Structures
Dim
Dim
I =
Sum
For
Sum As Integer
I As Integer,K As Integer
0
= 0
K = 1 To 5
124
6:
7:
8:
9:
I = I + 3
Sum = Sum + I
Next K
MsgBox Sum = & Sum
Notice that the code is more readable than the earlier version without loop. Line 5 is the
header of the loop while Line 8 is the footer of the loop. The statements enclosed by the
loops are statements 6 and 7. With the structure above, it is possible to repeat statements
6 and 7 hundred times without increasing the number of lines. All we have to do is to set
K to move from 1 to 100. In Line 5, the variable K is called a Loop control variable. It
has the function of keeping tract of how many times the statement in the block has been
repeated. The For Next Loop is often used when we know the number of times the loop is
to be repeated i.e we must know the start point, the end point and the increment before
using the For Next Loop.
The general form of the for next loop is
For I = ini To lim [Step inc]
- First Statement To repeat
- more statement(s)
- Last Statement to repeat
Next [Counter]
In the above loop,
I is the loop control variable or loop counter. Its current value determines when
the loop terminates
The variables ini, lim and inc are called the parameters of the For Next loop
These parameters may be numeric constants, variables, or arithmetic expressions
The parameters can be whole numbers or floating point numbers
NOTE
It is bad programming habit to give loop parameters floating point values. Try as much as
possible to convert these floating point values to integers before using them.
Control Structures
125
inc is the step or the increment of the loop counter. The loop variable starts from
ini(its initial value) and executes all the statement(s) within its body, increments the
loop counter by the step value, inc and re-executes the statements within its body
until the loop counter becomes greater than the limit, lim(or less than the limit if inc
is negative)
When the Step inc is omitted, it is assumed to be 1. It is the only optional parameter
If lim is greater than ini then, inc should be greater than zero(if not optional).
However, if lim is less than ini, then inc should be negative and compulsory
When the step value is one(or omitted), then, the number of times the For Next Loop
executes is given by
N = lim ini + 1 ................................... 3.4
Where lim is the limit of the Loop while ini is the start value.
For a loop with step of inc, the number of times the loop executes is determined using
the Arithmetic Progression relation.
lim = ini + (N 1) inc .................................. 3.5a
The number of executions is obtained by expressing N in terms of ini, lim and inc as
follows
N = (lim ini + inc ) \ inc ......................................................................................... 3.5 b
It is pertinent to point out the following about equation 3..5b
The integer division operator was used in eqn 3 because the loop must execute for an
integral number of times.
The loop variable is always greater than the limit of the For Next Loop at completion
of the loop. This makes sense, because it is a precondition for the loop to terminate.
For a Loop with a step(inc) of 1, the loop variable, I is given as I = lim + 1 at
complertion. However for a loop with step of inc , the loop variable obey the
inequality lim < I < lim + inc
The Loop does not execute if N is less than 1 i.e if lim > ini and inc < 0.(or lim < ini
and inc > 0 )
WARNING
Equation 3.5b is undefined when inc = 0. An attempt to set inc to be 0 will cause your
program to run perpetually!. This is dangerous and should be stopped by pressing Ctrl +
Break.
126
The For Loop starts from ini (i.e. I = ini) and after each execution, it increments I by inc
until I > lim.
In order to demonstrate the utility of the For Next Loop, we implement a program to
find the sum of the series
4 + 7 +10 + + 100
here the program is written as follows
1:
Sum =0
2:
For I =4 To 100 Step 3
3:
Sum =Sum + I
4:
Next I
In the program above, a running sum is desired therefore sum is initialized to 0 in line 1
Line 2 sets the loop in motion starting from 4 to 100 with a step value of 3
Line 3 updates sum with the current value of I. Notice that you have sum both at the left
and at the right hand side of the equality sign. Since the value of I changes as the loop
progresses, it means add the current value of I to the previous value of sum and make it
the current value of sum.
Line 4 is the footer of the loop. It has the effect of returning control to A2 so that I will
be incremented before re-evaluating the statements under the loop.
NOTE
In Line 4, the value of I is incremented first and the resulting value compared with lim,
if it is not greater that lim, then it goes back to evaluate the first statement after the
header of the loop.
Place the program in the Form Load event and use the Local window to view the values
of I and sum. Run the program by pressing F8 continuously to enable you view the
sequence of execution.
Control Structures
127
Figure 3.13
Form Window and Local
Window docked together
as the code is executed
manually
Do Loops
This is an indefinite Loop Structure used to execute the statements within its block until a
condition is satisfied. The number of times the statements are executed can be zero, one,
two or infinite. Two forms of the loop exist in Visual Basic. These are discussed below.
Pre-checked Do Loop
In a pre-checked Do Loop, a condition is usually tested at the header of the Loop before
executing the statements in its block. If the condition is satisfied the loop is aborted
otherwise, it continues looping. The structure of this loop is as shown below
Do [ While/Until Condition]
.
.
.
Loop
The header and footer of the loop is as shown above. This loop has the following features
Number of execution is unknown before the start of the loop
Starts and continue looping while condition is True( or until condition is False)
If it is desired to find out the number of times the loop is to be executed, you
introduce a counter that will be incremented as the loop repeats.
Two variants of the loop exist, these are the While and Until flavour
128
Case A1
Do [While Condition]
.
.
Loop
Here the loop continues while a condition is True. If at first test the condition is
True, then the number of times the loop is executed would be zero(i.e the statements
inside the body of the loop would never be executed). The flow chart for this structure is
as shown in Figure 3.14
Figure 3.14
Flow chart showing the Pre checked
Do While Loop. This structure
tests a condition and starts
(or continues) looping while
the condition is true.
Boolean
Expression
False
True
Process Statement
NOTE
The Pre-checked Do While Loop is the same as the ancient While Wend loop used in
earlier versions of Basic. It was added into Visual Basic for backward compatibility. It
has the structure shown below
While condition
Wend
129
Control Structures
Case A 2
Do Until Condition
.
.
.
Loop
Here the loop continues until a condition is False. If at first test the condition is False,
then the number of times the loop is executed would be zero(i.e the statements inside the
body of the loop would never be executed). The flow chart for this structure is as shown
in Figure 3.15
Figure 3.15
Flow chart showing the Pre checked
Do Until Loop. This structure tests a
condition and starts(or continues)
looping while the condition is False.
Boolean
Expression
True
False
We reconsider our problem of finding the sum of the series from 4 to 100 using the loop
structure above.
Because the loop cannot automatically increment itself unlike the For Next Loop, we
have to introduce a variable that generates the sequence. This is implemented with the
pre-checked Do While structure as follows.
130
In a post-checked Do Loop, a condition is usually tested at the footer of the loop after
executing the statements in its block once. If the condition is satisfied the loop is aborted
otherwise, it continues looping and executing. The Structure of this loop is as shown
below
Do
:
:
:
Loop [ While/Until Condition]
131
Control Structures
Like the pre checked loop, two forms of this loop exist, these are discussed as cases B1
and B2
Case B 1
Do
:
:
:
Loop While Condition
This is a post-checked DoLoop that executes at least once before testing a condition at
the footer of the structure. If the condition evaluates to False, the loop is terminated
otherwise the loop continues. The statement(s) in the loop block is/are continually
executed while the condition is True. The flow chart for this structure is as shown in
Figure 3.16
Figure 3.16
Flow chart showing the post checked
Do While Loop. This loop executes
Atleast once before testing a condition
It continues looping while the
condition is True
Statements
True
False
132
Case B 1
Do
:
:
:
Loop Until Condition
This is a post-checked Do Loop that executes at least once before testing a condition at
the footer of the structure. If the condition evaluates to True, the loop is terminated other
wise the loop continues. The statement in the loops are continually executed while the
condition is True. The flow chart for this structure is as shown in Figure 3.16
Figure 3.17
Flow chart showing the post check
Do Until Loop. This loop executes
at least once before testing a condition
It continues looping until the
condition is True
Statement
False
Boolean
Expression
True
Recursive problems
For recursive problems, the Do Loop is used to execute one or more statements until a
base condition is reached. One of the commonest recursive problems is the Euclidean
recursive HCF algorithm.
133
Control Structures
B ,
A mod
B = 0
HCF(B, A mod B)
............... 3.6
A mod
B 0
Before trying to solve this problem using loops, we should first of all understand the
implications of Equation 3.6. This problem seems to be similar to Equation 3.1 since two
conditions are involved. However, the second condition is expressd in terms of the
problem being solved. This is why it is it recursive. A Recursive function is a function
expressed in terms of itself and a base condition. An example would explain better.
Consider the problem of finding the Highest Common Factor of 60 and 42. Using 3.6 we
express it as
42 ,
60 mod
42 = 0
HCF(60,42) =
......... 3.7
HCF(42, 60 mod 42)
60 mod
42 0
42 mod
18 = 0
HCF(42,18) =
......... 3.8
HCF(18, 42 mod 18)
42 mod 18 0
134
6 ,
18 mod
6 = 0
HCF(18,6) =
.......... 3.9
HCF(6, 18 mod 6)
18 mod 6 0
In Equation 3.9, the first condition is satisfied because 18 mod 6 =0 hence the HCF is 6.
Thus we conclude that
HCF(60,42) = HCF(42,18) = HCF(18,6) = 6
In summary, the Euclidean HCF algorithm states that; Given two numbers A and B
where A> B, then the HCF of A and B is equal to B if A exactly divides B otherwise the
problem reduces to the problem of finding the HCF of B and the remainder when A is
divided by B. Using loop, this problem is solved as shown in Listing 3.13
Listing 3.13: Using the Do Loop in a recursive problem
Option Explicit
Private Sub Form_Load()
1: Dim A As Integer,B As Integer,C As Integer
2: A=InputBox(Supply A)
3: B=InputBox(Supply B)
4: R = A mod B Get the remainder when A is divided by B
5: Do Until R = 0
6:
A = B
let the value of B be assigned to A
7:
B = R
Let the value of R be assigned to B
8:
R = A mod B re-evaluate the remainder
9: Loop
continue looping
10: MsgBox " HCF = " & HCF
End Sub
Note that in this problem, if A exactly divides B, the loop would not be executed at all.
Control would be transferred to statement 10. Also, if A does not exactly divide B, then
statements 6,7 and 8 are executed until line 5 is satisfied before control is transferred to
line 10.
With a knowledge of the HCF of two or more numbers, one can evaluate the LCM of two
or more numbers, simplify a fraction and carry out other interesting operations with
fractions.
135
Control Structures
NOTE
Once the HCF has been obtained, the LCM can be calculated as follows
LCM ( A, B ) =
A B
HCF ( A, B )
542
180
60
20
The result of the conversion is 202002( obtained by reading remainder upward). The
operation carried out above can be performed using loop as shown in Listing 3.14
136
2 64 + 3 63 +1 62 +2 61 +5 60
3.10
Two problems often arise when converting a number to base 10 using equation 3.10.
These are
1. Since the number of digits in the number is unknown, it will be difficult to know
the starting power of B to use.
2. Also, it is always very difficult to extract the first digit of a number.
Extracting from behind is always easier and hence for convenience, Equation 3.10 is
expressed in the form
5 60 + 2 61 +1 62 +3 63 +2 64
3.11
137
Control Structures
Using the familiar summation routine, one can now handle Equation 3.11 conveniently
using Do Loop. The technique here is to divide the number by 10 and record both the
remainder and the integer part. The remainder is multiplied by 6 raised to power 0 and
result added to Sum which was initially zero. Again the remainder and the integer part
when the new number is divided by ten are recorded. This remainder is multiplied by 6
raised to power 1 and the result added to Sum. This process continues until the number
becomes zero. The code for the implementation of this is as shown in Listing 3.15
Listing 3.15: Conversion from other bases to base 10 using Do Loops
Option Explicit
Private Sub Form_Load()
1: Dim N As Integer,B As Integer,Sum As Integer,K as Byte
2: N=InputBox("Supply number to be converted")
3: B=InputBox("Supply Input Base")
4: Sum = 0 : K = 0
5: Do Until N = 0
6:
R = N mod 10
7:
Sum = Sum
+ R * B ^ K
8:
N = N \ B
9:
K = K + 1
10: Loop
11: MsgBox " Converted number is " & Sum
End Sub
138
NOTE
You must not use the Exit statement without a Decision Statement/Structure
The Go To Statement
This is used to branch unconditionally to a specified line number or line label within a
procedure. Go To statements make code difficult to read, debug and maintain. When the
Do...Loop, For...Next, If...Then...Else and Select Case are used properly, you would
hardly find Go To useful. It is advisable that you shun the use of Go To because it is
dangerous. Like the Exit statement, dont use the Go To statement without a decision
statement/structure. The Syntax of the Go To statement is
Go To T
Where T is a line number or line label in a procedure. The code using the Go To
statement to find the sum of the first 10 natural numbers is as shown in Listing 3.16
Listing 3.16: Experimentation with Go To statement
Sum =0
I = 0
T:
I = I + 1
Sum = Sum +I
IF I < 10 Then Go To T
MsgBox Sum = & Sum
In Listing 3.16, the line label is T . The Go To statement is used here to create a loop.
Nested Loops
Previously, we saw how decision structures(IF Then Else and Select Case) were
nested. We now consider how Do Loops can be nested amongst themselves and with
decision structures. Nesting of loops is actually straightforward. A loop is said to be
Nested when it contains (an)other loop(s) within its block. The mechanism of Nested
Loop is the same as that of nested decision structure. In a nested loop, the inner loop is
said to be a slave loop while the outer loop is the master loop. For Each time the
master moves, the slave is asked to complete its revolution. An example is shown with a
nested For Next block
Control Structures
139
For I = 1 to 5
For J = 1 to 6
Sum = Sum + I
Next J
Next I
The master(outer) loop has a loop control variable of I while the slave(inner) loop has a
loop control variable of J. Here for Each I, J moves from 1 to 6, hence while I moves for
5 times, J moves for 30 times(i.e 1 to 6 five times).
Do loops can also be nested like the For Next Loop. Here also, the inner loop is called
the slave while the outer is called the master loop. Nesting of the form
For I = 1 to 5
Do Until J = 10
J=J+1
Sum = Sum + I*J
Loop
J = 0
Next I
is also common.. Here the inner loop is the Do Loop while the outer Loop is the For
Next loop.
When nesting Blocks, it is important that you note the following
Multi level nesting can be accomplished easily
No two Blocks should intersect
Perspective of nested loops should be like that of concentric circles
140
By this time your interface should be a blank Form with only option buttons.
Figure 3.18 a
Visual Basic option
dialog designed using
tab strip control. Here
the general tab is
active
Control Structures
Figure 3.18 b
The tab strip control
with the Editor tab as
the active tab
Figure 3.19a
Dynamic interface
with the Quadratic
Equation option
selected
141
142
Figure 3.19 b
Dynamic interface
with the Equation of
State option selected
Figure 3.19 c
Dynamic interface
with the conversion
option selected
Draw another instance of the PictureBox on the Form and name it picEOS
Draw all the controls in Figure 3.19b on the PictureBox
Control Structures
143
Change its BorderStyle property to 0 None and its left to that of picQuadratic(say
135)
Change the Left of the PictureBox to 10000( so that you can hide it at design time)
By this time your interface should contain only the three option buttons.
Finally, draw another instance of the PictureBox on the Form and name it
picConversion
Draw all the controls in Figure 3.19 c on the PictureBox
Change its BorderStyle property to 0 None and its left to that of picQuadratic(say
135)
Change the Left of the PictureBox to 10000( so that you can hide it at design time)
By this time your interface should contain only the three option buttons
Make the optQuadratic the default OptionButton by changing its value to True
To make the dynamic interface work, we need to write code in the Click Event
procedure of the OptionButtons to display the desired picture and hide all others. This
code is as shown in Listing 3.17
144
Listing 3.17 is actually self explanatory. It is used to set object properties only. Lines 1 to
5 is the code in Click Event procedure of optQuadratic. It is used to show the quadratic
interface and hide all other interfaces. Because of nature of Figure 3.19c, it would have
been better to add codes that will change the height of the form so that redundant spaces
would not appear if there are options that do not fully occupy the Form.
The dynamic interface just designed with the option button can also be designed with
the TabStrip. The working principle is actually the same whether the option buttons or
TabStrip control is used. We now consider how the interface can be created using the
TabStrip control. The following steps are required:
Start a New Standard Exe application with the Form, tool box and properties
windows arranged appropriately
Activate the components dialog from the Project menu.
Scroll down to Microsoft Windows Control 6.0 and select it. Click OK to add the
TabStrip(and other windows common controls) control to the Form.
Draw an instance of the TabStrip control on the Form and resize so that all the
interfaces can be created on it.
Use the Properties Window and name it tbsExample
Right Click the TabStrip control and select properties from the pop up menu.(This
opens the properties pages of the control)
Select the Tabs Tab and insert three Tabs giving them captions as shown in Figure
3.20
Close the Tabstrip properties pages
Create picQuadratic,picEOS and picConversion with the appropriate controls on
them.(as in the optionButton Dynamic interface Figure 3.19 a to c)
Make picQuadratic the default interface by setting its left to 320(or any value such
that it can be visible at design time)
Place the code in Listing 3.18 in the Form module
Listing 3.18: Dynamic interface with the Tabstrip control
Option Explicit
Private Sub tbsExample_Click()
1: Dim I as Integer
2: I = tbsExample.SelectedItem.Index
3: Select Case I
Case 1
5:
Me.picQuadratic.Left = 135
6:
Me.picEOS.Left = 135000
7:
Me.picConversion.Left = 135000
8:
Case 2
Control Structures
145
9:
Me.picEOS.Left = 135
10:
Me.picQuadratic.Left = 135000
11:
Me.picConversion.Left = 135000
12
Case 3
13:
Me.picConversion.Left = 135
14:
Me.picQuadratic.Left = 135000
15:
Me.picEOS.Left = 135000
16: End Select
End Sub
Listing 3.18 is actually similar to Listing 3.17. The only difference is that Listing 3.17
uses OptionButtons in three separate event procedures while Listing 3.18 uses the
Tabstrip control in three blocks of a decision structure. Here line 2 assigns the index
property of the TabStrip SelectedItem collection to I. This values ranges between 1 and
3.(or between 1 and the number of Tabs in the TabStrip control). A select case statement
is then used to perform different actions based on the value stored in I. I of 1 is the same
as optQuadratic(see Figure 3.19a ), 2 is same as optEOS and 3 is optConversion.
146
Problems Set 3
Question 3.1:
Design and implement the interface shown in Figure Q3.1 using
a) Only Select Case structure
b) Using If and Select Case
c) Using Only If Then Else (Nested or Compounded)
d) Using If and Choose Function
e) Using Select and Choose Function
f) Using Switch and IF structure
g) Using Nested Choose Function or Nested Switch Function
Figure Q 3.1 a
Simple temperature
Conversion interface
using ComboBoxes
Add a CheckBox to Figure Q3.1 to give the user the opton of performing AutoConvert
see Figure 1.35 a page 39)
Question 3.2
a) Design and implement the interface shown in Figure Q3.2 used for HCF and LCM
calculations
Control Structures
147
Figure Q 3.2
HCF/LCM interface for
two input entries
b) Modify the interface in Figure Q3.2 so that it can handle up to input 5 entries. The
height of your Form should be a function of the number of entries
Question 3.3
a) Design and implement the interface shown in Figure Q3.3 used to implement the Van
Der Waal equation. Include at least 5 units for Pressure,Temperature and Volume so that
the program can work with different units system.
On Clicking the SI Unit Check Box, SI of Pressure, Volume and Temperature should be
displayed in the respective ComboBoxes. Likewise, on selecting the SI units from all the
combo boxes, then the SI unit CheckBox should be checked automatically.
b) Repeat Exercise 3.3a using Two Forms. Form 1 should be the Start up Form containing
the ComboBoxes with pressure,Temperature and Volume units with a next Button as well
as the SI unit CheckBox. Form 2 should contain TextBoxes with appropriate annotating
labels and units. This form should contain the Execute Button, a Back Button and the
output label.
148
Figure Q3.3a
Proposed interface for
the Van Der Waal
problem
Question 3.4
a) Given the Table below and the interface in Figure Q3.4 Estimate the real gas
compressibility factor(z).
Reduced
Pressure
Pr Range
Between
Reduced
Temperature
Tr Range
Between
Equation z = f ( Pr ,Tr )
149
Control Structures
5.4+ and 15
150
Question 3.5
Using the Table below
Sex
Age
< 20
20 to
40
40 to
60
> 60
Male
Female
10%
15 %
8%
14%
20%
17%
12 %
10
%
Design a Visual Basic program to Calculate the tax for a given Annual Earning Using
a) Options for Sex and Age
b) Combo for Sex and Age
c) Option for Sex and Combo for Age
d) Option for Age and Slider for Sex
e) Combo for Age and CheckBox for Sex
f) TextBoxes for both Age and Sex
g) Other windows control apart from those used in (a) to (f)
Comment critically on each of the interfaces.
Question 3.6
Implement the CheckBox Based conversion program shown in Figure Q3.6.
Note: No two CheckBoxes should be selected at the same time in the input frame and
output frame.
Figure Q3.6
CheckBox
Based
Conversion problem.
151
Control Structures
Question 3.7
Implement the Multi-Quantity conversion shown if Figure Q3.7 using Select Case. Note
that the Quantity of interest is first of all selected from the Quantity ComboBox so that
the available units for this quantity populates the Input and Output Combos. Menus were
used here to trigger the commands. Here File menu has Exit as the only Menu item, and
Convert has Execute as the only menu item while Format has none, one, decimal Place,
two decimal places, three decimal places and four decimal places as the menu items.
Figure Q3.7
Multi
conversion
Quantity
152
Question 3.8
Implement the interface shown in Figure Q3.8.
Figure Q3.8
Tabstrip
aided
conversion
Note that Figure Q3.8 is similar to Figure Q3.7 with the TabStrip serving the same
function as the Quantity ComboBox. The File, Tools and Help menus have only one
menu item which are respectively Exit, Options and About. Clicking the About
option triggers a Form showing options on formatting and selection inversion.
Options on whether to display Input(or Output) units are also added in this form.
Also, the About menu item in the Help menu has a Form used to advertise the
programmer.
Control Structures
153
Question 3.9
The interfaces in Figure Q3.9 a and b are used to evaluate elementary series
problems. The Start Up Form is Form Figure 3.9a while Form Figure 3.9b shows
modally when the Options CommandButton of Form Figure 3.9a is clicked.
Figure Q3.9 a
Input/Output
interface
Figure Q3.9 b
Option interface
154
Form Figure Q3.9b is used to set most of the objects properties in Form Figure
Q3.9a. Forms Caption of Figure Q3.9 a depends on the series selected in Q3.9b.Also,
the calculation performed depends on the Output option selected. The input
checkboxes are selected so that the series can be reasonably defined.The Start and
Stop value labels in Form Figure Q3.9a may change to sum of series or number of
terms if the options checked are different. The start value and the step value check
boxes must always be selected. Only one of the Stop value, sum of series and number
of terms checkbox can be selected at any given time. If output option is Sum of
series, sum of series checkbox should make itself impossible to select. Also if output
option is Number of Terms then Number of terms checkbox should make itself
impossible to select.
Question 3.10
Design and implement a program capable of converting both whole numbers and
floating point numbers from one base to the other.
Hint: you have to carry out two conversions, first from specified input base to base
10 and then from base 10 back to specified output base.
Your program should be able to detect a floating point input value and separate it into
the whole number and fractional part. The conversion is carried out on the whole
number part and the fractional part separately and results added thereafter.
CHAPTER
4
Data Structures
Arrays
Lists
Grids
Data Files
156
Serious programming entails working with large volumes of data, therefore a discussion
on how to handle these data is relevant. Data Structure is a collection of similar types of
data making up a composite. This composite has properties and methods which make it
easy to manipulate data and test algorithms. Common Data Structures are arrays, lists,
strings, queues, trees and stack. Visual Basic supports only few of these. Discussions on
these follow.
Arrays
This is the most popular data structure and is supported by almost all programming
languages. An Array is a composite variable that consist of other variables. These
variables are called Elements of the Array Variable. An Index is used to uniquely
identify an array element. E.g A(0), A(1), A(2), A(3) are all elements of the array
variable A.
When array elements consist of a defined sequence of numbers, a For Next Loop
can be used to fill the array. E.g
For I =0 To 10
A(I) = 2*I+3
Next I
The For Next Loop is used to fill the array whose first element A(0)= 3, second element
A(1) = 5 and last element A(10)=23. The index of the first element of an array is called
the Lbound (Lower Bound) of the array while the index of the last element is called the
Ubound(Upper Bound) of the array.
Therefore the code:
DIM A(10) As Double
N =LBOUND (A)
M=UBOUND(A)
Returns 0 and 10 to N and M which are the lower and upper bounds of the array A. An
array whose Lbound is 0 is called a Zero Based Array while an array whose Lbound is 1
is one based.For convenience we will be using 0 as our lower bound
Data Structures
157
Declaring an Array
Like scalar variables, arrays must be declared before they can be used in computer
programs. Declaring an array involves specifying the array name, the lower and upper
bound of the array and the type of data expected by the array.
Dim A(1 To 10) As Double
The array above has 1 as the lower bound and 10 as the upper bound. The type of data
expected by the array is Double. You can also declare an array as
Dim A(10) As Double
In this case, the 10 is taken as the upper bound while the lower bound is zero(default).
Usually, whenever the Lbound is omitted, the default Lbound(i.e zero) is assumed.
However, you can use the Option Base statement to change this default e.g
Option Explicit
Option Base 1
Dim A(10) As Double
Because of the Option Base statement, the default is taken as 1 instead of 0
NOTE
The Option base statement can only take values of 0 and 1
158
QUIZ
How can dynamic arrays be used to insert or delete an item from an array?
Array Transfer
The clause Array Transfer was coined into this book to ease the explanation of the
dynamics of arrays. Array transfer is defined as the process of filling one array with
elements of another array. Array transfer could be total or partial. A Total Array Transfer
occurs when all the elements of one array are transferred into the elements of another
array (or simple variable). The transfer could be of two forms. Parallel array transfer or
direct transfer.
Parallel array transfer: Here all the elements of one array are transferred to a second
array as follows
Data Structures
159
160
NOTE
varNames is a simple variable while strNames can be an array of any dimension
An example illustrating the effect of array transfer to a simple variant variable is shown
in Listing 4.1
Listing 4.1: Converting a variant variable to an array
1:
Dim strNames(1 to 5) As Double
2:
Dim varNames As Variant
3:
strNames(1) = Newton
4:
strNames(2) = Ikoku
5:
strNames(3) = Lagrange
6:
strNames(4) = Einstein
7:
strNames(5) = Nobel
8:
varNames = strNames
Line 8 transfers all the elements of strNames to varNames using one assignment
statement without subscripts manipulation and loop. With the assignment statement,
varNames is now an array and hence any subsequent reference to varNames without
subscripts is erroneous. In partial array transfer, only part of the elements of the array
enters into the transaction. This could be from the source array or from the sink.
Data Structures
161
I.
II.
III.
IV.
V.
VI.
Reversing an array
Array Arithmetic
You can perform simple arithmetic on one or more arrays using our well-known
arithmetic operators. For example, given two arrays X and Y, you can generate another
array Z, which is the product of the two arrays as follows
Z = X * Y .............................................................................................................. 4.1
For our conventional data structure, this is not possible because the multiplication
operator can only operate on simple variables or array elements. However, this can be
performed using Classes. Discussions on Classes will be deferred until Volume 2 of this
Book. For now, our only weapon is array arithmetic. We have to use our For Next Loop
to manipulate each element of the array as shown in Listing 4.2
Assumption is that A and B are parallel with same Lbound
Listing 4.2: Demonstrating Simple Array Arithmetic
ReDim X(Lbound(X) To Ubound(X))
For I=Lbound(X) To Ubound(X))
Z(I)= X(I)*Y(I)
Next I
Observe that this is actually an array transfer operation involving two arrays being
multiplied together and then result transferred to Z. The Lbound and Ubound were used
to make sure that we dont overshoot the bounds of the array. This is because we arent
sure of the Lbound of both arrays. Practical forms of array arithmetic are the Summation,
Sorting and Searching and Grouping problems. We now consider these at a glance.
162
T = xi
i =1
163
Data Structures
9 is the header of the For Next Loop which initialises the loop variable to 1 with limit
of N. Line 10 increments sum by the value stored in the ith element of array x. Line 11
increments I and returns control to Line 10 until I is greater than N. The output is printed
using a Message Box in Line 13. By carefully modifying Line 10 in Listing 4.3 one can
implement very complex summation operations. For example, to evaluate the variance of
N sampled data defined as
n
( xi x)2
Variance =
n 1
NOTE
When calculating variance, a code similar to Listing 4.3 must have been used to calculate
mean before the variance can be obtained.
Sorting an Array
We will show how to sort array by using one of the most commonly used sorting
algorithms.
Bubble Sort
The Bubble Sort Algorithm accepts an array or any other data structure and bubbles the
maximum or minimum data in the array to the top/bottom as the case may be. This
procedure continues until the numbers are arranged in the desired order. We take an
example to illustrate how the bubble sort technique is used to sort the numbers 4,7,3 8,5
in ascending order.
( 24Swaps)
4First Pass:
4
4
7
7
3
3
3
3
7
7
8
8
8
8
5
5
5
5
Figure 4.1a
4
3
7
5
8
( 32 Swaps)3
4Second Pass:
3
3
4
4
4
7
7
7
5
5
5
5
7
8
8
8
8
Figure 4.1b
3
4
5
7
8
164
3
3
4
4
5
5
7
7
8
8
Figure 4.1c
3
4
5
7
8
3
4
5
7
8
3
4
5
7
8
Data Structures
165
Listing 4.4 is an implementation of Figure 4.1. Here, Lines 1 to 8 is the same as Listing
4.3. The actual bubble sort implementation starts from line 8 where a post check loop is
started. Lines 12 to 14 are used to swap the array if the ith element is greater than the ith
+1 element. This continues until the index of the For Next loop reaches N 1. The post
checked DoLoop continues until Nsort is zero(i.e a complete pass without at least one
swap). After the bubble sort has been completed, the output is printed using a message
boxes.(Lines 20 To 22). Lines 20 to 22 prints the sorted array.
Searching an Array
At times, need might arise when the position of an item in an array is desired. One of the
easiest methods used to locate the item is to use the Linear Search Technique. Here, the
item to be searched for is compared with the first and subsequent array element until
there is a match or the bottom of the array is reached. In either case a message is printed
keeping the user informed of the outcome of the search. Listing 6.4 shows how the linear
search technique is implemented.
Listing 4.5: Searching an Array
Private Sub Form_Load()
1: Dim I as integer, Nsort As Integer , N As Integer
2: Dim Temp As Double,A() as Double,searchstring As Double
3: N =InputBox("Enter count of data ")
4: ReDim A(N) As Double
5: For I = 1 To N
6:
A(I)= InputBox("Enter Array Value")
7: Next I
8: searchstring = InputBox("Enter Search Key")
9: For I = 1 To N
10:
If searchstring = A(I) Then
11:
Exit For exit because item has been found
12:
End If
13: Next I
14: find out what stopped the loop
15: If I <= N Then
16:
msgbox "Item found in position" & cstr(I)
17: Else
18:
msgbox
searchstring & "Not found"
19: End If
End Sub
Lines 1 To 7 of Listing 4.5 is same as Lines 1 to 7 of Listing 4.4. Line 8 used an
InputBox to read the searchstring. Lines 9 to 13 is a For Next loop used to search
166
array A if the desired Searchstring exists or not. If it exist, the loop is aborted in line 11
using the Exit For statement otherwise the loop goes to completion. The principle that a
loop index always exceeds the limit of the loop on completion was used in Line 15 to
find out whether the searchstring exists in the array or not. Once the loop index does not
exceed the limit of the loop, then there is a match otherwise a no match (Searchstring not
found) message is printed. By carefully modifying the Lines 9 to 13 in Listing 4.5, one
can use the program above to obtain the number of times an item appears in the array
and their respective positions.
Ranking an array
Instead of sorting an array, one might rather prefer giving the unsorted array
ranks(positions). This is done by applying the linear search technique on the sorted
array. We appreciate the essence of ranks with an example. Assuming an array contains
the following items 3,7,2,9,5,8,3,4,5,3,4,1 and it is desired to assign ranks to each item
such that the largest item is given a rank of 1 and so on as shown in Table 4.1
Table 4 .1: Demonstrating Ranking
3
4
5
Index 0 1 2
3
7
2
9
5
8
Item
4
2
Rank 8 3 10 1
6
3
8
7
4
6
8
5
4
9
3
8
10
4
6
11
1
11
For the list(array) shown in Table 4.1, the rank of each item is shown in the third row of
the table. The rank of each item is obtained by picking an item in the unsorted list and
searching for its position in the unsorted list. The position in which this item is found is
directly related to the rank of the item in the list. If this position is k, then the rank of
the item is given by
Rank(i)
k + 1
if the list is sorted in descending order. However for a list sorted in ascending order, the
rank is given by
Rank(i) =
n - k
Where n is the count of the array element and k is the index of the item in the sorted
array. The code in Listing 4.6 shows how the linear search technique is used to find the
index(rank or position) of an item in an unsorted array.
Data Structures
167
6:
7:
168
4.4 used to sort array A in descending order. Lines 21 to 27 used the nested For Loop
for the ranking. The ranking is done as follows; an Item in array B(containing the
unsorted array) is picked and compared with each element of the array A(sorted in
descending order) until a match is found. Once there is a match, then the rank of that
item is assigned to the rank array and the inner loop aborted so that the next element in
the original array( array B) is considered until all the elements of array B have been
considered. The output is printed using message boxes in Lines 29 to 31
1.
NOTE
Because Option Base 1 was used to code Listing 4.6, the rank of an item found in
position K is K and not K 1. You use K 1 only when the array lower bound is 0(or
when Option Base 0 is used)
Lists
The ListBox control has array properties used to manipulate the ListBox. These array are
List, SelectedItem and ItemData. Lists are one of the most popular data structures in
Visual Basic. They are similar to arrays since each item in a list has an index. It is
different from an array in so many respects. The following are some of the differences
between Lists as data structure and arrays.
Lists are intrinsically dynamic(grows and shrinks depending on how many items
are being stored) i.e the size(ListCount) changes as items are added/removed
from it unlike arrays whose sizes can only be changed by re-declaration with risk
of losing original values.
Arrays have fixed sizes unlike list whose size increases as items are added to the
list or decreases as items are removed.
Items can be inserted into any portion within the list unlike in arrays. Inserting
into arrays is only possible in dynamic arrays but you have to write codes to shift
all elements one level down.
Items can be deleted from the list by just specifying a valid index of the item
within the list. This is difficult with arrays though dynamic array makes it
possible but codes have to be written to make necessary shifts
List provides an easy way to count the number of items in the list
Data Structures
169
The list is available in Visual Basic through the List property. Controls with the List
property are the ListBox, ComboBox and DirListBox. Others are DriveListBox and
FileListBox
NOTE
The List property of the DirListBox, DriveListBox and FileListBox are read only at run
time.
Open the List property using the drop down box at the right of the property value
Add the items one after the other and press Ctrl + Enter to force cursor to the next
line leaving the window open
Press Enter on completion. For a ListBox you should see the items visibly in the list.
For a ComboBox, run the program and open the drop down list, you should see the items
in the list
170
With lstCompanies
.AddItem
.AddItem
.AddItem
.AddItem
.AddItem
End with
Agip
Elf
Shell
Chevron
Mobil
After creating the list, you can insert an item into the list or delete an item from the list.
Eg. The statement
lstCompanies.AddItem
Texaco , 2
inserts Texaco into the third position thus automatically shifting all items from the third
position one place downward consequently increasing the ListCount property (Number of
items in the list). The RemoveItem method used to remove item from a list requires only
one parameter which is a valid index of the item to be deleted (removed). An example is
lstCompanies.RemoveItem
This removes the item with index of 1 from the list. Once again it would be in order to reiterate that adding or removing an item from the list with invalid index gives error.
CAUTION
Before adding any item in the list, check the ListCount and be sure of your action
because an error occurs if the specified index is greater than the ListCount - 1
The List property can also be used to create a list. It is the most direct method of filling
the list array. The syntax is as follows
Object.List (Index) [=string]
Where Object is any control with the list property while Index is the index of the item to
be added to the list and string is a string expression or variable indicating the item to be
added. For example
cboNames.List(0)=Newton
171
Data Structures
cboNames.List(1)=Lagrange
cboNames.List(2)=Euler
cboNames.List(3)=Laplace
or using the With block as
With cboNames
.List(0)=
.List(1)=
.List(2)=
.List(3)=
End With
Newton
Lagrange
Euler
Laplace
QUIZ
Under what conditions would you prefer the List property over the AddItem method
when adding Items to the ListBox?
NOTE
The ListIndex of a ListBox is never constant, it changes with selection.
Figure 4.2
Demonstrating List and
Listindex using the ListBox
172
You can also use code to change the selected item using the ListIndex property. For
example the code below changes the selected item to Laplace
Private Sub Form_dblClick()
lstScientist.ListIndex = 3
End Sub
The code above when fired would select Laplace. When the specified ListIndex is greater
than the index of the last item, an error occurs.
NOTE
For A List/ComboBox the lowest permissible ListIndex is 1(no item is selected) while
the highest permissible ListIndex equals ListCount 1(last item selected). For example a
ListBox with 8 items has a ListCount of 8 and hence the highest ListIndex would be 7.
Any reference to a ListIndex outside the range -1 x 7 gives an error.
With the Listindex property you can copy the selected item from the ListBox to
any other control. To copy the selected Item from the ListBox to a Label control at run
time you use the code
lblDept.Caption = lstDept.List(lstDept.ListIndex)
Observe that the ListIndex property is used to get the index of the selected item which is
then passed to the List property. To make this more explicit you can rephrase the code as
Dim K As Long
K =lstDept.ListIndex
lblDept.Caption = lstDept.List(K)
Here a Long variable K is declared and the ListIndex is assigned to K in line 2. Line 3
sets the caption of the Label(lblDept) with the ListItem with index of K Instead of using
the ListIndex property with the List property to copy an Item from a List, you can also
use the Text property to copy an Item as follows.
lblDept.Caption = lstDept.Text
The Text property offers a simple way to copy an item from a ListBox/ComboBox. It has
the same effect as copying the selected Item using the List and ListIndex properties. The
173
Data Structures
Text property can not be used to copy an item except the item is selected manually or
selected with the ListIndex property.
CAUTION
The Text property of a List/ComboBox is ReadOnly at run time and hence an assignment
statement of the form
lstPeople.Text = Newton
should not be contemplated.
It is pertinent to note that the Text property returns a null string when no item is selected.
QUIZ
How is the Text property related to the ListIndex property?
Application A demonstrates the use of ListIndex property
Application 4.1
Aim: To show how to use the List and ListIndex properties in a Multiple ListBox
application.
Procedure: Start a new Standard EXE application with controls as shown in Figure 4.3.
Give the labels the following names. lblSurname, lblFirstname, lblNationality, lblBirth,
lblDeath and lblDiscoveries. The label annotating lblNames should be given the name
lblName_A and that annotating the firstname label should be given the name
lblFirstname_A and so on. Create Five other ListBoxes and give them the names
lstFirstName, lstSurname, lstNationality, lstBirth, lstDeath and lstDiscoveries
Load the items in Table 4.2 into the ListBoxes. Set the Left property of the five
ListBoxes(lstFirstName, lstNationality, lstBirth, lstDeath and lstDiscoveries) to 20000
NOTE
Setting the Left property to a number as high as 20000 has the same effect as setting the
visible property to False. The difference between this and setting the Visible property to
False is that with this technique, the control is invisible both at design time and at run
time unlike the False setting of the visible property which only makes the control to be
invisible at runtime.
174
Isaac
Gottfried
Leonhard
Albert
Micheal
Alfred
Max
Gallilei
Pierre-Simon
Johannes
English
German
Swiss
German
British
Swedish
German
Italian
French
German
Date of
Birth
1642
1646
1707
1879
1791
1833
1858
1564
1749
1571
Date of
Death
1727
1716
1783
1955
1867
1896
1947
1642
1827
1630
Major Discoveries
Calculus, motion etc.
Calculus, philosophy
Algebra, geometry
Relativity, Energy
Electromagnetism
Ballistite(explosive)
Quantum Physics
Astronomy&Heat
Astronomy&Motion
Astronomy
Figure 4.3
Demonstrating a MultiListBox application.
Program Behavior: As an item is clicked in the List, the labels display the biodata
Code: The code used to drive this application is as shown in Listing 4.7
Listing 4.7: Working with the List and ListIndex properties
Private Sub lstScientist_Click()
1:
Dim I As Integer
2:
I = lstScientist.ListIndex
175
Data Structures
3:
lblSurname.Caption = lstScientist.List(I)
4:
lblFirstname.Caption = lstFirstname.List(I)
5:
lblNationality.Caption = lstNationality.List(I)
6:
lblBirth.Caption = lstBirth.List(I)
7:
lblDeath.Caption = lstDeath.List(I)
8:
lblDiscoveries.Caption = lstDiscoveries.List(I)
End Sub
QUIZ
How can you implement Listing 4.7 with the Text property instead of the List property.
Application B
Aims: a) To Demonstrate how to add, remove and delete Items from a list at run time.
b) To Demostrate how to Transfer Items from a list to an array.
c) To Perform simple statistical analysis on listItems
Procedure: a)Start a new Standard EXE application or add a new form if Visual Basic is
already running.(b) Create controls and align them as shown in Figure 4.4. (c) Give the
controls the names. lblMean and lblMean_A, lblMax and lblMax_A, lblMin and
lblMin_A, lblStd and lblStd_A, lblSum and lblSum_A and lblInputValue_A. The
CommandButtons should be given the names cmdAdd, cmdRemove, cmdEdit,
cmdExecute and cmdClose. Names of other controls are txtInputValue, lstData and
fraInputList (d) Set the enable property of the first four CommandButtons to False. Set
the Default property of cmdAdd to True and the Cancel property of cmdClose to True
Figure 4.4
Adding and Removing
Items from a ListBox
At runtime
176
Data Structures
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
71:
txtInput.Text = ""
End Sub
Private Sub cmdClose_Click()
End
End Sub
Private Sub cmdExecute_Click()
Dim A() As Double, N As Integer
Dim Sum As Double, Mean As Double
Dim Min As Double, Max As Double, I As Integer
N = lstData.ListCount
ReDim A(N - 1) As Double
For I = 0 To N - 1
A(I) = lstData.List(I)
Next I
lblsum.Caption = Sum(A)
lblMean.Caption = Format(Mean(A), "0.00")
lblStd.Caption = Std(A)
lblMax.Caption = Max(A)
lblMin.Caption = Min(A)
End Sub
Private Sub cmdRemove_Click()
Dim x As Integer
x = lstData.ListIndex
lstData.RemoveItem x
cmdRemove.Enabled = False
Call ValidateExecute
End Sub
Private Sub lstData_Click()
If lstData.ListIndex < 0 Then
cmdRemove.Enabled = False
cmdEdit.Enabled = False
Else
cmdRemove.Enabled = True
cmdEdit.Enabled = True
End If
End Sub
Private Sub txtInput_Change()
If Len(txtInput.Text) <= 0 Then
177
178
72:
cmdAdd.Enabled = False
73:
Else
74:
cmdAdd.Enabled = True
75:
End If
76: End Sub
77:
78: Private Sub ValidateExecute()
79:
If lstData.ListCount > 0 Then
80:
cmdExecute.Enabled = True
81:
ElseIf lstData.ListCount = 0 Then
82:
cmdExecute.Enabled = False
83:
End If
84: End Sub
85:
86: Function Max(A() As Double)
87:
Dim L As Integer, U As Integer
88:
L = LBound(A): U = UBound(A)
89:
Max = A(L)
90:
For I = 1 To U
91:
If A(I) > Max Then
92:
Max = A(I)
93:
End If
94:
Next I
95: End Function
96:
97: Function Min(A() As Double)
98:
Dim L As Integer, U As Integer
99:
L = LBound(A): U = UBound(A)
100: Min = A(L)
101: For I = 1 To N - 1
102:
If A(I) < Min Then
103:
Min = A(I)
104:
End If
105: Next I
106: End Function
107:
108: Private Function Sum(A() As Double) As Double
109:
Dim L As Integer, U As Integer
110:
Dim I As Integer
110:
L = LBound(A): U = UBound(A):Sum = 0
111:
For I = L To U
112:
Sum = Sum + A(I)
113:
Next I
Data Structures
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
179
End Function
Private Function Mean(A() As Double) As Double
Mean = Sum(A)/(Ubound(A) Lbound(A) + 1)
End Function
Function Std(A() As Double) As Double
Dim L As Integer, U As Integer,I As Integer
L = LBound(A): U = UBound(A)
Std = 0 : N = U L + 1
For I = L To U
std= std + A(I) Mean(A)
Next I
Std =SQR(STD/N)
End Function
In Listing 4.8, functions were written for Min, Max,Sum,Mean and Std. These functions
are then called to return appropriate results.
On releasing the mouse on txtInput, you find out that the Text dragged from the source
control appears on the TextBox.
180
The ItemData
When an item is added into the list array using the AddItem method, Visual Basic
automatically adds an item into the ItemData array. This is to enable it establish a
correspondence between the sorted array and the original unsorted List. Assuming you
want to work with the Names and Nationality of each of the Scientist. You load the
names into a ListBox whose Sorted property is set to True using the AddItem method and
the Nationality into the ItemData array using the NewIndex property
NOTE
Note the the NewIndex property keeps the index of the most recently added item in the
list.
With lstScientist
.AddItem Newton
.ItemData (.Newindex)=1
.AddItem Leibnitz
.ItemData(.Newindex)=2
.AddItem Euler
.ItemData(.Newindex)=3
.AddItem Einstein
.ItemData(.Newindex)=4
Data Structures
181
End With
Since 0 was added to the ItemData array using the NewIndex property, it implies that no
matter how the list is sorted, it always remembers that Newton was the first item added to
the list. A segmental implementation of this is shown below.
Dim K As Integer,I As Integer
I= lstScientist.ListIndex
K = lstScientist.ItemData(I)
In the code above, I is the Index of the Selected Item in the Sorted List. This index is
then passed to the ItemData array to get the index of the item in the original list(unsorted
list).
The NewIndex property works very much like the AddItem method. Since the AddItem
method adds a new item to the ListBox, the NewIndex property gives the item a
NewIndex.
NOTE
As an item is sorted, the index of the item changes while the ItemData array stores the
original unsorted listitems index.
Having discussed much on the ItemData array, we now consider how it could be used to
synchronise the bio-data of each scientist with their names. Here, the code takes the form
shown in Listing 4.9
Listing 4.9: Working with sorted List
Private Sub Form_Load
1: With cboScientist
2:
.AddItem Newton
3:
.ItemData(.NewIndex)=0
4:
.AddItem Leibnitz
5:
.ItemData(.NewIndex)=1
6:
.AddItem Euler
7:
.ItemData(.NewIndex)=2
8:
.AddItem Einstein
9:
.ItemData(.NewIndex)=3
10:
.AddItem Faraday
11:
.ItemData(.NewIndex)=4
12:
.AddItem Nobel
13:
.ItemData(.NewIndex)=5
182
14:
.AddItem Planck
15:
.ItemData(.NewIndex)=6
16:
.AddItem Galileo
17:
.ItemData(.NewIndex)=7
18:
.AddItem Laplace
19:
.ItemData(.NewIndex)=8
20:
.AddItem Keplers
21:
.ItemData(.NewIndex)=9
22: End with
End sub
Private Sub lstScientist_Click()
25:
Dim I As Integer,K As Integer
26:
I = lstScientist.ListIndex
27:
K = lstScientist.ItemData(I)
28:
lblSurname.Caption = lstScientist.List(K)
29:
lblFirstname.Caption = lstFirstname.List(K)
30:
lblNationality.Caption = lstNationality.List(K)
31:
lblBirth.Caption = lstBirth.List(K)
32:
lblDeath.Caption = lstDeath.List(K)
33:
lblDiscoveries.Caption = lstDiscoveries.List(K)
End Sub
Run the program. It should be well behaved. Thanks to the ItemData property that helped
to store the original index of sorted Listitems
183
Data Structures
Figure 4.5
Demonstrating multiSelect in the ListBox
control
NOTE
The MultiSelect property of a ListBox must be set to 1(simple) or 2(extended) before the
selected array can be used. However, when the style property of the ListBox is changed
to 1-CheckBox, MultiSelect is implicit and can not be changed.
When MultiSelect is set to 2(extended) in that standard ListBox, you can use the arrow
key to extend selection.
184
Data Structures
185
The code used to drive the Forms shown in Figure 4.6 is shown in Listing 4.10
Listing 4.10: Demonstrating the MultiSelect property
Private
Sub cmdTransfer_Click()
1:
Dim I as Integer
2:
With lstGases
3:
For I = 0 To .ListCount 1
4:
If.Selected(I) = True Then
5:
Form2.lstGases.AddItem
.List(I)
6:
End If
7:
Next I
8:
End With
End Sub
Private
Sub cmdClose_Click()
11:
Form2.Show
186
12:
End Sub
Form1.Hide
In Listing 4.10 the selected property of the ListBox is used to find out whether an item is
selected or not(Line 4). If an item is actually selected, then the AddItem method is used
to add that item to the second ListBox otherwise another item is considered. This
continues until all the items have been considered.
You will need to close ( or Hide) Form1 and view Form2 to confirm that the items have
actually been transferred from Form1 to Form2. On Clicking the Close Button, Form1
hides as expected showing Form2. You can write a similar code to show Form1 from
Form2 in the Back command button.
Grids
Grids are similar to the Lists except that they operate on two-dimensional tabular data.
They constitute a very important data structure and have properties and methods similar
to Lists. Visual Basic controls which support grids include but not limited to the
following; Microsoft FlexGrid, Microsoft HierachicalFlexGrid and the Videosoft
FlexArray. Figure 4.7. shows a typical flexgrid control with Excel - like grids.
Figure 4.7
The MS FlexGrid Control
Like the List data structure, items can be added to grids and also removed from Grids.
Grids also have ability to sort data entered in the TextMatrix. Interestingly, the grid
controls have a complex sort and merge abilities deficient in lists.
Data Structures
187
188
Place a checkmark on any of the following grid controls in the components dialog
Videosoft flexarray
Microsoft FlexGrid
Microsoft HierachicalFlexGrid
Use the ToolTip to identify a grid control (say MSFlexGrid) in the toolbox and
draw an instance of it on the form.
Use the properties window to change the number of rows(rows property) and
columns(cols property) in the grid to 50 and 30 respectively
Change the FixedCols property to 0 to clear the fixed column. You can change it
to two, three and four so that you would understand what the significance of the
FixedCols property.
Press F5 to Run youre your program. Your Form should have a grid control with
50 rows and 35 columns similar to that shown in Figure 4.7
Open the Form Load Event procedure and type the following code
Listing 4.11 : Adding Items to a sorted List using the TextMatrix property
With grdStudents
.TextMatrix(0,0) = Serial Number
For I = 1 To 10
.TextMatrix(I,0) = I
Next I
End With
Run the program. You should observe that the first 10 rows have row label. You will
achieve a similar result by interchanging the row and column indices. Also, observe that
189
Data Structures
the content of the first cell is not entirely visible. Set the AllowUserResizing property to
3 FlexResizeBoth to enable you resize the row and column at runtime.
with the code above, we are now sure that the active row is row n and active column is
column m. Therefore, the active cell is cells (n,m). Since the row and col properties are
both readable and write able at runtime. You can also change the active cell using code as
follows
grid.Row = n
grid.Row = m
The statement above holds good if and only if the values of n and m are not greater than
or equal to the number of rows and columns on the grid. Luckily, we can also use code to
read and change the numbers of rows and columns in grids. Given that p and q are Long
Integers, you can get the number of rows and columns in the grid as follows
p = grid.Rows
q = grid.Cols
Observe the similarity between the syntax of the row property and the rows property. The
singular form indicates the active row while the plural form indicates the number of rows
in the grid. You really have to note this because it is a major source of confusion to
Visual Basic beginners.
190
Data Structures
191
CAUTION
Make sure you set the number of rows of the grids to be greater than the ListCount of
lstNames before transferring items from the ListBox to the Grid
You use code to increase the number of rows in the Grid as follows
IF
192
changes the active cell to Cells(4,3) by changing the active row to row 4 and active
column to 3 as follows
grdData.Row = 4
grdData.Col = 3
with the code above, the active cell is cells(4,3) and hence the text property returns/sets
the text displayed in the Active cell. By suitably changing the Row and Col of the Grid,
the text property can function like the TextMatrix property in loops. For example, the
code below uses the text property to transfer items to rows 1 to 10 of column 5 to a
ListBox(lstNames)
lstNames.Clear
grdData.Col = 5
For I = 1 To 10
grdData.Row = I
lstNames.AddItem
Next I
grdData.Text
When the FillStyle Property of the FlexGrid is set to 1 flexFillRepeat , the text can
be used to write to a selected range of cells.
QUIZ
How is the Text property of a Grid different from the Text property of a ListBox
Data Structures
193
Therefore, the code write Egbe ,ThankGod and Itua in the first three columns of
row 2
grdData.AddItem Egbe &CHR(9)&ThankGod&CHR(9)_Itua,2
QUIZ
Unlike the Text and TextMatrix properties, the AddItem method does not overwrite the
existing data in the cell(s) . It shifts all the items from the Row specified one row
downward thus increasing the number of rows by a count of 1
To Insert a blank row at a specified position, you use the AddItem method with an empty
string as follows
grdData.AddItem ,3
When the code above is fired, row 3 becomes empty and the number of rows increases by
a count of 1. Using the AddItem method in this manner is similar to the RemoveItem
method which removes an entire row from the grid. The code below removes the fourth
row and its content from the grid.
grdData.RemoveItem 3
To clear all the content of the grid without removing rows you use the clear method. This
method requires no parameter unlike the RemoveItem Method.
GrdData.Clear
194
Figure 4.8
Comparing the
TextMatrix and the
TextArray properties
TextMatrix(x,y) = TextArray(c*x + y)
.4.1
TextMatrix( n \ c , n Mod
c ) ..4.2
For Figure 4.8 with 8 columns, it implies that the Text Gas can be retrieved using
TextArray(25) or TextMatrix(3,1)
The TextArray property is particular useful when transferring Items from a
ListBox to a grid control. Here a knowledge of the number of Col(umn)s or Rows in
the grid is not important. For example, to transfer a list of about 200 sampled data from a
ListBox to a grid without a knowledge of the number of Cols or Rows is done with the
TextArray property as follows.
Dim I As Integer
For I = 0 lstSample.ListCount 1
GrdData.TextArray(I) = Form1.lstSample.List(I)
Next I
Or in terms of TextMatrix as follows
Data Structures
195
196
This same code can be used to copy/paste data in the ActiveCell of a FlexGrid. To
Copy/Paste data to a selected cells you use the Clip property of the FlexGrid control. The
syntax is
clipboard.SetText = flexgrid.Clip
to paste data from the clipboard to a FlexGrid you first of all select some cells and then
invoke the code
flexgrid.clip = clipboard.GetText
NOTE
When pasting data from the FlexGrid to selected cells only a fraction of the data is
pasted when the selection in less than expected. Also, if the selection is too large, only a
fraction of it is filled by the clipboard.
Data from other applications can be exchanged with your application using the clipboard
object. Also a string can be pasted in matrix form in a grid using the clipboard object and
string functions. Given the matrix,
3 4 6
3 9 8
2 3 3
you can store it in a string and then paste it to the flex grid using the clip property as
follows
Dim X as String, Y as String
X = chr(9): Y=chr(13)
strA = 3 + x+ 4 + x + 6 + y + 3 + x + 9 + x +_
8 + y + 2 + x + 3 + x + 3
flexgrid.clip = strA
Before attempting this you must first of all select a three by three range otherwise only
the first cell(activecell) will be filled.
QIUZ
How can you use the clipboard to copy and paste data to or from the ListBox
Data Structures
197
Formatting Cells
By setting a few properties of the grids, you can format cells and data in cells in very
much the same way as you would do in a spreadsheet application. Some of these
applications are discussed below.
CellFontName
CellFontUnderline
CellFontStrikeThrough
CellFontWidth
CellFontColor
These properties are read/write at run time and can be changed just like the previously
discussed CellFont properties. For example, to change the font color of the Active cell
you use the assignment statement
Grid1.CellFontColor = vbRed
198
Cell Alignment
You can use cell properties to perform the left align, right align and centre operations
done in Excel. The MSflexgrid or MSHflexgrid control has 10 property list values that
can be used to changed the alignment of data in the cells of the grid control. These are as
shown in Table 4.4
Table 4.4: Values and named constant of the Msflexgrid CellAlignment property.
Constant
Value Description
FlexAlignLeftTop
flexAlignLeftCenter
flexAlignLeftBottom
flexAlignCenterTop
flexAlignCenterCenter
flexAlignCenterBottom
flexAlignRightTop
flexAlignRightCenter
flexAlignRightBottom
flexAlignGeneral
To centralize data in a cell, you use the vbCentreCenter alignment constant as follows.
Grid.cellAlignment=flexAligncentercenter
Or simply with the centercenter value as follows
Grid.cellAlignment = 4
Another property that is very much similar to the cell alignment property is the
colAlignment property. This property is used to specify an alignment for an entire
column. It is an array property with array index ranging from 0 to 1 less than the index of
the last column. For example, to centralize the data in column 2 you use the statement.
Data Structures
199
Grid.ColAlignment(2) = 4
TIP
You can create selection manually by using click and drag operation.
Use code to apply the formatting features discussed earlier on a single cell on selected
cells. Performing this is actually easy. All it entails is to change the fill style property to
flexfillRepeat. Once this is done, any changes performed affects all the cells in the
selection. The fill style property has two property values (constant). The default is the
200
flexfill single (6), which implies that formatting applies to only the active cell. To change
the fontcolor of the text in cells (3,2) to cells (5,7) you use the code shown in Listing 4.12
Listing 4.12: Formatting a selection
Grid1.Row =3
Grid1.Col =2
Grid1.Rowsel =3
Grid1.Colsel =5
Grid1.fillstyle=1
Grid1.cellforecolor = vbRed
Grid1.cellfontBold = True
Grid1.cellfontsize = 12
NOTE
To change ForeColor of the fixed row and fixed col you use the fore ColorFixed and
BackColorFont
Merging cells
One of the most striking formatting feature of a spreadsheet application is its capability to
merge cells. The MSflexGrid control has a property that can be used to merge cells
freely. This is done through the merge cell property of the MsflexGrid control. The
property values and constants of the MSFlexGrid MergeCell property is shown in
Table 4.5
Table4.5. Property values and constants of the MSflexgrid Mergecell property
Constant
Value
Description
FlexMergeNever
FlexMergeFree
FlexMergeRestrictRows
FlexMergeRestrictColumns
FlexMergeRestrictBoth
201
Data Structures
202
203
Data Structures
FlexSortStringNoCaseAsending
FlexSortNoCaseDescending
FlexSortStringAscending
FlexSortStringDescending
FlexSortCustom
Table 4.3 shows that grids have a more involved sorting capability than the List. For
Instance the List has the following shortcomings
Data Files
After studying how to work with data, it become imperative that we delve into a
discussion on how to save and access these data in files. Files structure used to save the
data used by(or generated by) an application is called data file. Other file types are Binary
Files used commonly to save graphics and Ini Files (or Resource file or Registry) used to
save application setting.
Because of its simplicity, we would only discuss the data files and cover other file types
in volume 2 of this text.
Data files could be sequential or random access depending on how data can be added or
retrieved. A sequential file allows data to be store one after the order in an orderly
manner. This is similar to the Additem method without an index.
Before writing or reading from files, the files have to be opened. For example, the code
below opens a file for input
Open C:\Egbe.txt For Input As #1
204
The statement above opens a file Egbe.txt in drive C so that data can be read from the
file. Note that when opening a file, the syntax requires a fileNumber parameter. In this
case we use #1 because it is the first file opened. For the second file we use #2 and so on.
Apart from the input mode, you also write to a file by opening it for output mode as
follows
Open C:\Egbe.txt For Output As #1
or in Append mode As
Open C:\Egbe.txt for Append As #1
The difference between opening a file in output mode and in append mode is that in
output mode, the data written to the file replaces any existing data in the file. However, if
a file is opened in Append mode, the data added to the file are added to the bottom of the
file without affecting the original data in the file.
We demonstrate a simple application to demonstrate the utility of files using Listing 4.14
Listing 4.14: Saving and Reading data from files
Private Sub cmdExecute_Click()
1:
Dim a As Double, b As Double, c As Double
2:
x1 As Double, x2 As Double
3:
a = txtinputa.Text
4:
b = txtinputb.Text
5:
c = txtinputc.Text
6:
x1 = (b * -1 + Sqr(Abs(b ^ 2 - 4 * a * c))) / (2 * a)
7:
x2 = (b * -1 - Sqr(Abs(b ^ 2 - 4 * a * c))) / (2 * a)
8:
lblX1.Caption = x1
9:
lblX2.Caption = x2
End Sub
Private Sub Form_Load()
12: Dim S1 As String, S2 As String, S3 As String
13: On Error Resume Next
14: Open "C:\Egbe.txt" For Input As #1
15: Input #1, S1, S2, S3
16: txtinputa.Text=S1:txtinputb.Text=S2:txtinputc.Text= S3
17: Close #1
End Sub
Private Sub Form_Unload(Cancel As Integer)
20: On Error Resume Next
Data Structures
205
206
8:
close #1
CAUTION
When working with files, you have to be very careful so that you dont give conflicting,
file number to two open files. This causes unpredictable errors. You use the Freefile
function to determine the next available file number
To write to a file using the free file function, you use the code
Dim n As Integer
n = freefile
Open file.Dat for Output As # n
Write #n, S
Close #n
You can use the clip property to write the data in selected cells to file as follows
strA = Flexgrid.clip
Open file.Dat for
Write #n = strA
Output As #1
Problem Set 4
Question #1
Input Unit
Enter the information shown below in a grid and use the grid to perform a simple length
conversion.
Output Unit
Inch
Metre
Centimetre
Yard
foot
Inch
1
0.0254 2.54
0.027778
0.083333
Metre
39.37
1
100
1.093613
3.28084
Centimetre
0.39370079 0.01
1
0.010936
0.0328084
Yard
36
0.9144 91.44
1
3
Foot
12
0.3048 30.48
0.333333
1
Hint: 1 inch = 0.0254m = 2.54cm = 0.027778yd = 0.083333 ft
1m = 39.37inches = 1m = 100cm = 1.093613yd = 3.28084ft
Your interface should be similar to that of Figure Q3.1a and your grid should be invisible
at run time.
Data Structures
207
Question #2
A grading system of a certain university is as shown below.
Score
Grade
0 -10
F
11-20
E
21-30
D
31-40
C
41-50
B
51-60
A
Write a program to determine a students grade without using
a) Choose function
b) Switch Function
c) Select Case
d) Logical If
e) If then Else
f) List
g) Grid
Question 3
A programmer used a For Next loop to remove the first 15 items from a list box with
ListCount of 20 as follows
For I = 0 to 14
LstA.RemoveItem I
Next I
what is wrong with the code and how can it be improved upon.
Question 4
Design a program that uses drag drop operation to drag selected items from one list box
to another. Users should be given the option of cutting or copying the items from the
source list box.(use check box for this )
Question 5
The thermodynamics property of state is given as
P = Pf
+ x(Pg - Pf)
208
Table Q4.5: Segment of steam table table needed for Problem set 4.5
Pressure
Temp.
Vf
Vg
Hf
Hg
o
kpa
C
m3/kg
kJ/kg
Sf
sf
KJ/kg
209
Data Structures
Sort By
Surname
First Name
Average
Physics
Chemistry
Biology
Help
About
210
Question 7
Write appropriate codes to drive the interface of figure Q4.7.
Note that the particulars of students must be saved in a data file and must be updated each
time the form Loads or Unloads.
Figure Q4.7a
Proposed interface
for students look up
form.
Figure 4.7b
Proposed Form used to add
Data to Form Figure 4.7a
Data Structures
211
CHAPTER
5
Strings Arithmetic
String Operators
Option Compare Statement
String Functions
Format Functions
Message Box
Input Validation
Problem Set
String Arithmetic
213
Strings are generally regarded as non-numeric data types(values) other than dates or
Boolean. They have very important applications in Science, Engineering and Everyday
routines. Generally, in Visual Basic, all data entered through the text box are captured as
strings and subsequently converted to the appropriate data types during assignment (or
before assignment). A good understanding of string is necessary for proper Visual Basic
manipulations.
Strings could be simple expression or variables. String expressions are usually enclosed
between double quotes as in thankyou, West Africa, You can also assign string
expressions to variables in which case the variables have to be declared as string. An
example is illustrated thus.
Dim strX As String
strX= ThankGod
Here, reference to the string ThankGod can be made through the variable strX. It is
better and more convenient to assign strings to variables instead of using string raw
string data.
Strings could be of Fixed length or variable length .
String Operators
Two operators used to manipulate strings are
1) Concatenation Operator(&)
2) Comparism Operator(Like)
Concatenation Operator
The concatenation operator(&) acts on strings and returns strings. It has the effect of
joining two strings. Consider the strings
Atim and aka
You can join the two strings using the concatenation operator as follows
Atim & aka = Atimaka
214
NOTE
Unlike the addition operator in numbers, the concatenation operator is NOT
COMMUTATIVE, hence care has to be taken to ensure that we are conscious of the
sequence of the operators and consequences of the operation.
Like Operator
The like operator is used to compare two strings. The syntax of the like operator is
result = string like pattern
As an example, consider the Boolean expression
If x = "a" Then
this can be written with the like operator as
If x like "[a]" Then
Observe that in the Like operator, the square bracket is used to match a single character.
Note that in strings, by default the lower case character is different from the upper case
character. Hence if x stores the character "A" then the Boolean expression
X like "[a]"
evaluates to give false.
Given the Boolean expression
X = "a" or X = "b"
OR X = "c" OR X = "d"
String Arithmetic
215
216
NOTE
To match the special characters left bracket ([ ), question mark (?), number sign (#),
asterisk (*), enclose them in brackets. The right bracket (]) can not be used within a group
to match itself, but it can be used outside a group as an individual character.
String Arithmetic
217
String Functions
A lot of string functions abound in Visual Basic. Manipulations of strings are handled
with the help of these in built functions. We now consider these functions and their
applications.
Val Function
The VAL function converts strings to numbers. This is especially important in numeric
strings or strings that begin with numbers. Any string which begins with an alphabetic
character returns a VAL of zero. We consider some examples. Given the String
strLenght = 300 metres
intLenght= Val(strLenght) Assigns 300 to intLenght
The operation above reads a length measured with the unit. VAL function discards the
text to the Right of the string. This is necessary because 300 metres can not be
assigned directly to the integer Variable or any of the derivatives of numeric variables.
Also the string
strSeries = B300
intLenght= VAL(strLenght) Returns Zero
The example above gives zero because the string begins with a non-numeric character.
218
NOTE
1. The VALue of a string whose first character is not LIKE 0-9 is zero because
getting the value of string means removing non numeric characters from the point
of first occurrence of the non numeric characters.
2. Also that the presence of spaces before or between the strings does not affect the VAL
function e.g 2 3 4/99a43 returns 234.
3. A string is said to be a numeric string if it consist of only numeric characters. Eg
"45","67", "89 9" etc.
Len Function
The Len function returns the number of characters including spaces in a string E.g Given
the string
Dim Str1 As String, P As Integer
str1 = Anong Abi
intP=LEN(str1)
Result: intP = 9
If care is not taken, one might have a result which is somewhat different from the above
result. This is because spaces are counted as characters and hence spaces preceding and
succeeding a character might be counted. To avert this problem you use the Trim, Ltrim
and Rtrim functions discussed below to remove leading and trailing spaces.
The Len function is used in the GotFocus event of a TextBox to select the text in the
TextBox whenever the TextBox receives focus. This is shown in Listing 5.1.
String Arithmetic
219
Listing 5.1: Selecting the Text in a TextBox using the Len Function
Option Explicit
Private sub txtInput_GotFocus()
1: txtInput.SelStart = 0
2: txtInput.SelLenght = Len(txtInput.Text)
3: txtInput.SetFocus
End Sub
In listing 5.1, line 1 instructs windows to start selecting from position 0 (i.e before the
first character).Line 2 sets the number of characters to be selected to be equal to the LEN
of characters in the TextBox. Line 3 gives focus to the TextBox. For this program, it
might not be necessary because the code is written in the GotFocus event. It is good habit
to include Line 3 whether you need it or not because you can never tell what is going to
happen if it is omitted.
220
Rtrim Function
The Rtrim function trims spaces to the right of a string ignoring spaces to the left.
Example
StrName = Egbet
In the string above, there are two spaces before the character E and one space before
character t. Evaluating the Len of the string gives 8. After invoking the Rtrim function
on the string, it reduces the Len to 7. On invoking the Ltrim function on the resulting
string, It trims the spaces to the left and leaves a LEN of 5.
Other examples on the LTrim and Rtrim functions are illustrated and explained with
comments as follows:
Dim strname as String,intP as Integer
strName = Egbet
intP= Len(strName)
Returns 8
StrName=Rtrim(strName) Removes trailing spaces
P=Len(StrName) Returns 7
StrName=Ltrim(strName) Removes leading spaces
P=Len(strName)
Returns 5
Trim Function
The Trim function combines the effect of both the Ltrim and Rtrim functions. It removes
spaces both before and after a string.
Given the string
1:StrPeople= Bahumono
2:StrPeople1=LTRIM(RTRIM(strPeople))
3:StrPeople2=TRIM(strPeople)
statements 1 and 2 have the same effect.
However the Trim functions are used to remove spaces from strings accepted through
text fields before comparing the strings or manipulating same. Also, when writing
password driven applications, it is always recommended to TRIM string before
comparing it with the standard.
Simple Application
We develop a simple application which will help us test some of the String functions. The
interface shown in Figure 5.1 is used for this purpose.
String Arithmetic
221
Figure 5.1
Testing String
functions.
222
Example
Named Constant
Remark
StrConv(str1, 1)
vbUpperCase
StrConv(str1, 2)
vbLowerCase
StrConv(str1, 3)
vbProperCase
You can use the UCase, LCase and StrConv functions to implement the Change case
format option of Microsoft Word(See Figure 5.2). The Case functions are important in
string comparison and document editing.
Figure 5.2
Change case dialog
of Microsoft Word.
ASCII Functions
ASCII functions are the CHR and ASC functions. They are used to convert keyboard
characters to codes and vice versa. These codes were set by the American National
Standard Institute (ANSI) and are called American Standard Code for Information
Interchange (ASCII). These codes result from the fact that information or characters are
stored in the computer as numbers and hence every feature in the computer has a number
associated with it. These numbers are called ASCII(pronounced ASKEY). The ASCII of
A is 65, B is 66 and Z is 90. Also the ASCII of a is 97 and so on. See Appendix C
String Arithmetic
223
for a complete listing of all the printable and non printable ASCII Character Codes as
well as the KeyCode constants.
The ASC function is used to get the ASCII code of a character.
Eg ASC(A) returns 65 and ASC(d) returns 100. On the other hand, the CHR
function converts a number to a Character. E.g CHR(80) returns P etc.
The interface of Figure 5.3 is used to demonstrate the utility of ASCII Codes/Characters
Figure 5.3
Playing With
ASCII functions.
224
NOTE
The range for ASCII Code is from 0 to 255 .
For a string with more than one character, the ASC function returns the ASCII code of
the first character in the string. Also, when comparing strings, it is usually based on their
ASCII values. E.g the string A is considered less than a using a binary comparison.
Also, the string Anong is considered greater than the string Aba. Here if the first
two characters have the same first characters, then the next characters are compared until
two distinct characters are encountered.
Figure 5.4:
Working with
the KeyPress
Event.
String Arithmetic
225
The code in Listing 5.4 is used to prevent comma(,) or decimal point(.) from appearing
in the TextBox(or disabling comma(,) or decimal point(.) while focus is on the TextBox
of interest). At times remembering the ASCII could be tasking hence most people prefer
using the CHR function to convert the KeyAscii parameter to character so that
comparison can be made using strings of Characters. Replace statement 1 with the
statement below
1: If Chr(KeyAscii) = , or Chr(KeyAscii) = . Then
Run the application again. Observe that it gives that same result. Also when dealing with
range of characters, the Chr is more convenient to use because group of characters can
be prevented using the Like operator. Using Like we can replace statement 1 with the
code
1:
If Chr(KeyAscii) Like [,.] Then
with the Like operator you can program so many key combinations without using the
conditional Or operator. Also consecutive alphabets and numbers are handled easily with
the Like operator. Example, replacing statement 1 with the statement below prevents all
capital letters, percent sign and dollar sign from appearing in the textbox
1:
If Chr(KeyAscii) Like [A-Z$%] Then
The Exclamation sign is often used to negate the Like operator so that only characters in
the square brackets can appear in the text box as follows
1:
If Chr(KeyAscii) Like [!0-9.] Then
Replace line 1 of Listing 5.4 and observe that no other character apart from 0 to 9 and
decimal point appear in the text box.
You will find yourself using this code as often as possible because you will almost
always restrict your users from making certain keystroke in certain input fields in order to
prevent mismatch errors and other silly errors. This is usually called Input Validation.
The CHR function has another interesting application when manipulating multiline text
boxes(i.e text boxes with multiline property set to True). Here concatenating a string
with CHR(13) + CHR(10)(or vbCrLF) causes the string at the right of the vbCrLf to be
displayed in the next line. E.g when the statement below is invoked in a Form with a text
box whose Multiline property is set to True and scrollbar property set to vertical, we
obtain the output shown in Figure 5.5.
Text1.Text= North & vbCrLf & South & vbCrLf & West
226
Figure 5.5
Displaying text in multipleLine text box using the
CHR function.
Because of the importance of CHR(10) and CHR(13), Visual Basic has named constants
used in place of them. The named constant for CHR(10) is vbLf ( i.e Line feed) while the
named constant for CHR(13) is vbCr ( i.e Carriage return). A combination of character
13 and character 10 is given the named constant vbCrLf (Carriage return line feed
combination) . Other important Chr functions are CHR(9)(i.e horizontal tab character)
with the named constant vbTab and CHR(0) with the named constant vbNullChar.
String function
The string function is used variant (string) containing a repeating character string of the
length specified. The syntax of the string function is
String(number, character(or Character code))
Here number is the number of times character should be repeated
For example to return a string consisting of 5 zeros, you write the function as
lblResults.Caption = String(5, 0)
instead of using character string, you can use character code as follows
lblResults.Caption = String(5, 48)
The code has the same effect since character 48 is 0
NOTE
When the character argument of the string consist of a string with more than one
argument, then only the first character is returned the specified number of times.
227
String Arithmetic
These functions work with array of strings. The SPLIT function splits a string to a
character array while the JOIN function converts a character array to a string.
Given the Array
strA(0) = E ; strA(1) = n ; strA(2) = g; strA(3) = i; strA(4) = n
and strA(5) = e
you can use the JOIN function to join the array into a single string with any specified
separator.
Eg the statement
JOIN(strA, ,) gives
E,n,g,i,n,e
However, using an empty string ( )as separator joins the array into a single character.
Note that in the Join function, the first argument(or parameter) is a String array while
the second is a string specifying the separator(or delimiter). If the separator argument is
omitted, it gives a string separated with spaces as follows E n g i n e
The SPLIT function is the reverse of the JOIN function. It returns a zero-based, onedimensional array containing a specified number of substrings . When using the split
function, you have to assign it to a dynamic array as follows
Dim strB() as string
strB =SPLIT(E,n,g,i,n,e, ,)
Here a dynamic array was declared and the split function splits the string
E,n,g,i,n,e into the array. The split function was used with two parameters. The
first parameter is the string expression(or variable) to be split while the second is a
character specifying the Separator.
The full syntax of the split function is given as
228
Figure 5.6
Evaluating
polynomial
Functions with the
Split function.
strF = UCase(Trim(txtFunction.Text))
4:
dblX = txtXvalue.Text
5:
strA = Split(strF, "X")
6:
If UBound(strA) > 0 Then
7:
dblY = Val(strA(0)) * dblX + Val(strA(1))
8:
ElseIf UBound(strA) = 0 Then
9:
dblY = Val(strA(0)) * dblX
10: End If
11: lblResult.Caption = dblY
End Sub
In Listing 5.5, Line 3 Trims the content of the Function textbox and then converts it to
upper case. This is necessary so that we will not worry about the case when splitting the
string in line 5. Line 6 finds out the upper bound of the array so that the constants A and
B( or A only as the case may be) can be obtained and the function evaluated in line 7 or
9. Line 7 is evaluated if upper bound of strA > 0 in which case the string was split to
strA(0) and strA(1). In line 9 the string has only one term and hence the coefficient was
multiplied by the Xvalue.
String Arithmetic
229
230
In Listing 5.6, line 2 declares a dynamic array. This is important because the size of the
array depends on the number of character in the string which is unknown.
Line 3 assigns the string THANKGOD to the string variable strWest
Line 4 Trims spaces from the string and assign the number of characters in the resulting
string to the variable intN
Line 5: Starts the loop from 0 to one less than the number of characters in the string
Line 6: here as I changes, the array index changes and each character is extracted and
assigned to the array. when I is 1 line 6 is strA(1) = mid(strWest, 1, 1) i.e
assigns the first character to strA(1)when I is 2 line 6 is strA(2) =
mid(strWest,2,1) i.e assigns the second character to strA(2)
line 7 increments I and line 6 is re executed until I gets to intN
Listing 5.6 shows that the Mid and the Split functions are capable of splitting a string to a
one dimensional array. Once a string has been split or can be traversed, then the
following can be implemented
a) Convert it from base m to n where m and n are integer values
b) Evaluate sum of digits for numeric string
c) Evaluate the place value of a digit
d) Encrypt/Decrypt the string
Given the number 1213 in base 4. Conventional method used to convert it to base 10 is
as follows
1 x 43 + 2 x 42 + 1 x 41 + 3 x 40 ........................................................................................ 5.1
If the digits of the number are stored in a zero based array A, the conversion becomes
A0 x Bn + A1 x Bn-1 + A2 x Bn-2 + + An x B0
5.2
Where B is the Input Base and n is the upper Bound of array A(number of characters - 1)
Observe that the power decreases from the Upper bound of the array to 0 while the array
index increases from 0 to the upper bound of the array. Expression 5.2 can be written in
terms of summation as
n
Bn -1 ....................................................................................................................... 5.3
i -0
Expression 5.3 is the general relation used to convert a number A from Base B to base
10.
Equation 5.3 is tested using the interface of Figure 5.7 with the code in Listing 5.7
231
String Arithmetic
Figure 5.7:
Implementing number
conversion with strings.
base
NOTE
Because the split Function was used to split the string, we assume that there is a space
separating each character. When testing the program, separate the digits with a space
otherwise you will have an unexpected result. To get good result replace Lines 5 and 6
with the statements below implemented with the Mid Function
232
Hexadecimal Numbers
Numbers in base 16 are called hexadecimal numbers. In binary, the digits are 0 and 1. In
base 10, our digits are 0 to 9. Also in Base 16, the digits are 0 ,1, ,9,A,B,C,D,E,F
i.e A = 10, B= 11 etc. With good understanding of strings, we can write a program
capable of converting the number AF27C16 to Base 10.
From base 16 expansion, the result is
A x 164 + F x 163 + 2 x 162 + 7 x 161 + C x 160 - -
- 5.4
First, the mid function is used to store the jth digit of the hexadecimal number in an
array element dj as follows
N=Len(strNum)
Redim D(N) as Integer
For
I =1 TO N
D(I) = Val(Mid(strNum,I,1)
Next I
Use the ASC function to check the ASCII of all the digits. If the ASCII is greater
than 57 then, we know that dj contains one of the hexadecimal digits A,B,C,D,E and
F.
Subtract 55 from the ASCII of the characters whose ASCII is greater 57
If Asc(D(I)) > 57 Then D(I)= Asc(D(I)) 55
We can apply the same principle to convert a number from base 10 to base 16. However,
we need to perform repeated divisions and store the jth remainder in an array dj . The
elements in dj are now checked. If any remainder is greater than 9 then 55 should be
added to the number and results converted to character using the CHR() function.
StrReverse Function
String Arithmetic
233
Q = strReverse(T)
Then Q is assigned the string "luaP"
An application of the string reverse function is demonstrated below.
Recall that the Join function Joins a one dimensional array to form a string with a
specified delimiter. Given the Number 247 in base 10 we can convert it to any base b
(assume b = 5) as follows
247 divided by 5 remainder 2 integer part 49
49 divided by 5 remainder 4 integer part 9
9 divided by 5 remainder 4 integer part 1
1
Read the remainder from down to get the results. i.e 1442
Note the operation can be summarised as follows:
1. Read a number
2. Read the Base to be converted to
3. Divide the number by the base and obtain the remainder and the integer part
4. Store the Remainders in an array
5. Set the Number to be the Integer part obtained in 3 above
6. Repeat Step 3 to 5 until number becomes Zero
7. Join the Array containing the remainder and reverse it.
The steps above can be converted to a program as shown in Listing 5.8(you can test this
program with the interface of Figure 5.7)
Listing 5.8: Using the Join function
Private Sub cmdExecute_Click()
1: Dim N as Integer, I as Integer
2: Dim strSum as String, R() as String,B As Integer
3: N = Trim(txtNumber.Text)
4: B = txtBase.Text
5: I = 0
6: Do
7:
ReDim Preserve R(I) as string
8:
R(I) = cstr(N Mod B)
9:
N = N \ B
10:
I =I + 1
11: Loop while N > 0
12: strSum = Join(R, )
234
A loop can be used to replace each character in a string using the Mid statement
A combination of the Mid Statement and Mid Function could be a powerful tool in
Encrypting text.
String Arithmetic
235
Figure 5.8
Interface used to Test
Encryption program.
236
237
String Arithmetic
The InstrRev function works like the Instr function but however it locates the position of
last occurrence of the specified character. The syntax of the InstrRev function is
InstrRev(string1, string2[, start[, compare]])
Where string1,string2,start and compare are same as the Instr function. Note the syntax
difference between the two. Start is the third parameter here while Start is the first
parameter in the Instr function.
Note that the InstrRev function starts scanning from right unlike the Instr function.
Given the String strSample =
InstrRev(strSample, a)
MaThemAtiCal,
returns 11
238
Figure 5.9
Interface illustrating
the Instr and
InstrRev Function
Program behavior
A sample string is entered in the sample string TextBox and a search string is entered in
the search string TextBox. An option is selected from the search direction frame and the
case sensitivity frame. The start position of search is indicated using the slider control.
On executing, the result is displayed on the label. You really have to spend some time
studying the code because it is the basis of what follows.
Listing 5.10:Using the Instr and InstrRev functions
Private Sub cmdexecute_Click()
1: Dim strsample As String,strsearch As String
2: Dim intp As Integer, strResult As Integer
3: strsample = Trim(txtsample.Text)
4: strsearch = Trim(txtsearch.Text)
5: intp = sldPosition.Value
6: If optsensitive.Value = True Then
7:
If optleft.Value = True Then
8:
Select Case sldPosition
9:
Case 0
10:
strResult = InStr(strsample, strsearch)
11:
Case Is > 0
12:
strResult = InStr(intp, strsample, strsearch)
13:
End Select
14:
ElseIf optright.Value = True Then
15:
strResult = InStrRev(strsample, strsearch, intp)
16:
End If
17: ElseIf optinsensitive.Value = True Then
String Arithmetic
239
18:
If optleft.Value = True Then
19:
Select Case sldPosition
20:
Case 0
21:
strResult = InStr(strsample, strsearch, 1)
22:
Case Is > 0
23:
strResult =InStr(intp,strsample,strsearch,1)
24:
End Select
25:
ElseIf optright.Value = True Then
26:
strResult = InStrRev(strsample, strsearch,intp,1)
27:
End If
28: End If
29: lblresult.Caption = strResult
End Sub
In Listing 5.10, Lines 3 and 4 trim the content of the TextBoxes and subsequently assigns
it to the string variable. Line 5 assigns the value of the slider to the integer variable. Note
that as the slider is dragged, the value changes. Lines 6 and 17 are the two most important
lines in the code. If optSensitive is selected then line 8 to 16 is executed. Otherwise if
optInsensitive is selected, Lines 18 to 27 are evaluated.
We now consider an application of the Instr function in Input Validation.
The application below accept a positive(i.e unsigned) floating or whole number and
doubles it. The KeyPress event was used to ensure that no other character apart from 0
to 9 and decimal point appears. Also, not more than one decimal point should be entered
in the TextBox. The Instr is used to find the position of decimal point in the string. If
Instr is greater than zero (i.e decimal points occur at least once) then the KeyAscii
prevents subsequent decimal points from being entered. Listing 5.11 has the code used to
restrict non numeric characters and multiple occurrences of decimal point in a text field
using KeyPress event.
Listing5.11:Restricting non numeric characters and multiple occurrences of decimal point
Option Explicit
Option Compare Binary
Private Sub txtInput_KeyPress(KeyAscii As Integer)
1: Dim intP As Integer
2: Dim strInput As String
3: strInput = txtInput.Text
4: intP =Instr(strInput, .)
5: If Chr(KeyAscii) Like "[.]" And intP > 0 Then
6:
KeyAscii = 0
7: End If
8: If Chr(KeyAscii) Like "[!0-9.]" Then
9:
KeyAscii = 0
240
10:End If
End Sub
Here Line 4 locates the position of decimal point in the string. If no decimal point exist in
the string, then 0 is assigned to the integer variable intP; otherwise a positive whole
number is assigned to intP. Line 5 evaluates to True if a decimal point already exists in
the string and the key being pressed is also a decimal point. Line 6 disables the key being
pressed if Line 5 evaluates to True. Line 9 disables all other keys apart from 0 to 9 and
decimal point.
Though this program works well, it should not be used in practical programs because the
backspace key(ASCII 8) is also disabled. By carefully modifying Line 8, Listing 5.11
can be used to enable backspace and still restrict all other not numeric characters apart
from decimal point.
NOTE
When the second argument of the Mid function is 1, it gives the same result as the LEFT
function
e.g Mid(strRegion,1,n) = Left(strRegion,n)
241
String Arithmetic
to the form
242
Given the number 345.6764 in octal system. To convert it to decimal, you need to use the
Instr function to locate the position of decimal point and split the number into its
fractional part 0.6764 and integer part 345 using either the split function or the left and
mid functions. Conversion is then
performed separately and results added(or
concatenated as the case may be).
Replace function
The replace function is used to replace a specified character or sub string in a given string
a specified number of times. The syntax of the string function is
Replace(expression, find, replacewith[, start[, count[, compare]]])
Here expression is the string to replace, find is the substring to be replaced and
replacewith is the replacement string. These are the only required or compulsory
arguments. The search, count and compare are optional arguments. Start is used to
indicate where the replacement should start while count is the number of replacements to
make and compare is used to indicate the type of comparison.(the default depends on the
option compare statement)
Given the string
Y = 3 * x ^ 2 + Sin(x) + 3*x*Cos(3*x)
To replace all the x in the string with the variable a (which holds 1.5) this is done as
follows
Y =Replace(Y, x, a)
On invoking this function, Y now becomes
Y = 3 * 1.5 ^ 2 + Sin(1.5) + 3 * 1.5*Cos(3 * 1.5)
String Arithmetic
243
Fractions can be manipulated the same way numbers are. The technique is to accept the
fraction and locate the position of the division operator in the string. The strings to the
Left gives the numerator while the strings to the right of the division operator gives the
denominator.
E.g given the fraction
T = 3/20.
Using the Instr Function you can get the position of the divide operator as
P =Instr(fraction, /) This should give 2
The numerator is given as
Num =Left(fraction,P-1)
And denominator as
Den = Mid(fraction, P+1)
With the numerator and denominator, you can Add two fractions, multiply two fractions
and perform any kind of mathematical operation with fraction. Mixed fractions are
written as 3/4/5. Here, the fraction means 3 whole number four over five. The Instr
function (and InstrRev function) or the split function can also be used to manipulate the
mixed fractions as well. To simplify a fraction, you need to evaluate the greatest common
divisor(GCD = HCF) of the numerator and denominator and then divide numerator and
denominator by this GCD.
The method of Decimal shifting is used to get fractions that are equivalent to an
infinitely repeating rational number. We can illustrate the method of decimal shifting
with an example. Given the decimal number
S = 0.10110110110110110110110110101101101101
We can obtain a fraction that is equal to the given number by multiplying S by 1000 to
obtain
1000S = 101.101101101101101101
Subtracting S from 1000S, we obtain
999S = 101
or
S=
101
999
244
The operation we have just performed can be done using strings without human
intervention. A string function is used to inspect the string for repeating sequence of
digits. Thereafter the fraction equivalent to the number is returned. When this is done in
base 2, it is called Binary shifting and in base 8 it is called octal shifting.
NOTE
In base n after shifting m places we multiply by (nm) i.e. shifting 3 places to the right in
binary we multiply by 23
Scientific Notation
&
B- & Cstr(n-2)
where B serves the same function as E in Base 10. Note that in this book we will use B
for Base 2 , C for Base 8(octal) and H for base 16(Hexadecimal)
Formatting Output
Results obtained after processing variables need to be displayed in the proper format.
Visual Basic has a number of format functions that can be used to format number, date,
currency etc. these are as discussed below.
NOTE
All Format functions return string values
String Arithmetic
245
246
FormatNumber Function
The FormatNumber, FormatCurrency and FormatPercent functions have the same
sequence and number of parameters. The FormatNumber function is different in that no
sign (i.e. currency or percent) is attached to the output. The syntax of this function is
FormatNumber(Number,NumDigitAfterDecimal,IncludeLeadingDigi
t,UseParensforNegativeNumbers,GroupDigits)
Given the numbers
X= -23478.8284
Using the FormatNumber as
=FormatNumber(X)
returns -23,478.83
however, using the FormatNumber function as
= FormatNumber (X,3,,vbFalse)
returns
-23478.828
In the first example, the default was used and hence the number was formatted to two
decimal places with digits grouped together.
247
String Arithmetic
VbShortDate
vblongTime
vbShortTime
Description
Displays date vbshortDate and
time as vbLongTime
Returns the day of the week,
the day of the month, the
month name and the year
Returns the day, the month
and the year e.g. 12/29/80
Returns hours, minutes and
seconds along with AM/PM
indicator
Returns hours and minutes in
military time. E.g. 23:25
meaning 11:25 PM and 2:18
meaning 11:25PM
248
Round Function
The round is used to round a number to a specified number of decimal places. The
complete syntax of the round function is
= Round(expression [,numdecimalplaces])
The numdecimalplaces argument is an optional argument with default value of 0.
Format Function
The format function is a multipurpose function. It can be used to format number,
currency, percent and date/time. The commonly used syntax of the format function is
Format(expression[, format]):
Since output of Numbers, percent and currency are all numbers, the Format function
treats them accordingly. The format function uses both named constants and code as
format parameter. Common named constants are currency, fixed, standard, percent and
scientific.
e.g. to format the number
x= 28347.2
in currency style you use
= Format(x,"currency")
and in scientific style you use
=Format(x, "Scientific")
returns 2.83472E04
with date, the named constants in table 5.3 is used Example, given the date
x =#02/03/03#
you can choose to format it as
=Format(x, "vbLongDate")
249
String Arithmetic
One interesting thing about the Format function is that it allows users to customize output
to their taste. The code used to define this format is presented in Table 5.4
Table 5.4: codes for customizing the format function
Code
Function
Description
0(zero)
Digit Place Holder
Displays a digit or displays zero(0) if no
digit appears in that location
#(hash)
Digit place holder
Displays a digit or displays an empty
string("") if no digit appears in that
location. Chances of having leading or
trailing zeros do not exist
.
Decimal separator
Indicates where decimal point should be
displayed
,
Thousand separator
Indicates where the separator are
displayed
%
Percent indicator
Indicates where a percent sign is
displayed. It also multiplies the number
by 100
E-, eScientific notation
Expresses number in standard form with
no sign displayed when exponent is
positive
E+, e+
Scientific notation
Expresses number in standard form with
a sign always attached to the exponent
Table 5.5: Using the format functions
Number(x)
Format
23.4702
=format(x,"#.#####")
23.47022
=format(x,"#.00000")
23.4702
=format(x,"#.000")
23.4702
=format(x,"#.####")
0.2347
=format(x,"#.##%")
0.2347
=format(x,"#.00%")
0.000235
=format(x,"0.00E+00)
0.000235
=format(x,"#.#0E+00)
Output
23.4702
23.47020
23.470
23.470
23.4
23.40
0.24E-3
.23E03
250
Message Box
Message Boxes are very important in developing interactive windows program. They
enjoy the broadest application in input validation, which are necessary in fail safe
programming design. Figure 5.10 shows a message box invoked in Microsoft Word.
Figure 5.10
Windows Message
Box
It displays the message The selected floppy disk is not in use. Check to "
The features outlined above are common to all windows message boxes. Adding a
message box to your application is as simple as using string functions. Usually a string
variable is declared to store the message and others follow directly. An example on how
to display a similar message box is illustrated below
1: Dim strMessage As String
2: strMessage=The Selected floppy is not in use.Check" & _
"to make sure a floppy disk is inserted
3: Msgbox strMessage,vbCritical + vbRetryCancel,Micro & _
soft Word
Place the lines of code above in the click event of a command button or load event of the
Form and observe that it works very well. In the code Line 1 declares a string variable
strMessage. Line 2 assigns the message to strMessage. Line 3 invokes the message
box. Note how the continuation operator was used to continue statement 2. This is always
the practice because most times the message you will issue might span beyond a single
line of statement. The commonly used syntax of the MessageBox statement is
MsgBox prompt[, buttons] [, title]
Here prompt is a string representing the message to be displayed by the MsgBox.
buttons is an integer specifying the button(s) and icon displayed by the message box.
title is a string specifying the title of the message box.
251
String Arithmetic
Name Constant
VbOKonly
OK and Cancel
VbOKCancel
VbAbortRetryIgnor
VbYesNoCancel
Yes and No
VbYesNo
VbRetryCancel
In the message box example above , we can replace vbRetryCancel in line 3 with
vbYesNoCancel and observe that the buttons displayed will be the Yes, No and
Cancel button. Usually, the button combination displayed depends on the message and
the action we want our users to respond to.
32
vbQuestion
Warning
48
vbExclamation
Information
64
vbInformation
Because addition is commutative the sequence of placement does not matter. Therefore
the statements vbQuestion + vbYesNo gives the same effect as vbYesNo + vbQuestion..
Also the value of a button or icon can be used instead of using named arguments. The
message box of Figure 5.11 could be displayed with the following lines of codes.
252
The 32 in line 4 is the constant for vbQuestion while 4 is the constant for vbYesNo.
The example shows that either the named constant or the button constant could be used to
produce the same effect. It is better to use the named constant so that your code could be
readable. However, those with strong memory prefer the shorter and faster option. You
can make things worst for others by adding the constants because Visual Basic
understands. Eg if the second argument is 21, Visual Basic understands that it is
vbCritical and vbRetryCancel. You might get unexpected errors with wrong button
constants so it is advisable that you use named constants.
253
String Arithmetic
Return Value
Return Constant
OK
VbOK
Cancel
VbCancel
Abort
vbAbort
Retry
vbRetry
Ignore
vbIgnore
Yes
vbYes
No
vbNo
Program decisions are taken based on the return value(or constants). In the message box
of Figure 5.11 we can add the following lines of code to determine if the user really
wants to exit the application or clicked the buttons inadvertently.
Listing 5.13: Using the Message Box as a function
Option Explicit
Private Sub cmdExit_Click()
1: Dim strMessage As String, strTitle As String
2: Dim intReturn As Integer
3: strMessage ="Are you sure you want to Exit" & _
" This Application ?"
4: strTitle = "Confirm Exit"
5: intReturn = MsgBox(strMessage, 32 + 4, strTitle)
6: If intReturn = vbYes Then or if intReturn = 6 Then
7:
End
8: End If
End Sub
Observe that an integer variable intReturn was declared in line 2 to hold the return
value. Line 5 also shows a little syntax difference, here the Message Box was used as a
function and thus was assigned to an integer variable. Also, note that a parenthesis was
used to enclose the arguments. Except message boxes whose return values are not
important, it is always advisable to use message boxes in this manner. Line 6 used a
conditional statement to determine the return value (i.e. the button clicked). If it is the
Yes button then the End statement is used to exit the application otherwise the message
box just closes with no action performed.
254
By default, the first button of the message box receives focus whenever the message box
shows up. This is usually the default behavior. You can change this state by specifying
your own default button. This is implemented by adding the default button to the
button/icon parameter as follows
VbQuestion + vbYesNo + vbDefaultButton2
The implication of the statement above is that as the message box comes up, the
SecondButton is set as the default button(i.e the No Button becomes the default button)
This can also be implemented by using the button constants as follows
vbQuestion + vbYesNo + 256
Table 5.9 shows the setting for the message box default buttons.
Table 5.9: Message Box default buttons argument constants
Default Button
Value
Constant
First
vbDefaultButton1
Second
256
vbDefaultButton2
Third
512
vbDefaultButton3
Fourth
768
vbDefaultButton4
NOTE
When the Enter key is pressed, the default button is triggered. It is always advisable to
set the button that will have the least effect on the application to be the default button e.g.
when the message box of Figure 5.12 appears, pressing enter inadvertently Ends the
application. However, if the default button is set to vbDefaultButton2, pressing the Enter
key only closes the message box without affecting the state of the application.
255
String Arithmetic
Or
MsgBox
Since the first and third arguments of the message box are strings, you can apply your
knowledge of strings to get the best out of the message box. We saw earlier how to use
the concatenation operator to concatenate a very long message together. You can also use
the carriage return character ( Chr(13) or Enter Key) to display the message on different
lines according to your taste. This is applied follows:
1: Dim strMessage As String
2: strMessage ="The Selected floppy is not in use.Check to"
3: strMessage = strMessage & Chr(13) & "make sure that the"
4: strMessage = strMessage & "floppy disk is inserted."
5: MsgBox strMessage,vbCritical+vbRetryCancel,"Micros" & _
"oft Word"
on invoking the code above in an event procedure, we obtain the message box shown in
Figure 5.12
Figure 5.12
Customising the
Message box with string
CHR function
Notice the manner in which the Chr(13) was concatenated to the string. This style gives
the message box a compact and controllable size. You can also achieve the same effect
with the named constant (vbCr). ASCII Character 10 (vbLf) also gives the same output.
It is not uncommon to see programmers using the carriage return line feed combination
i.e CHR(10) + CHR(13) or vbCrLf for their implementations.
256
At a very low level, we demonstrate the effect of invalidated users input with an addition
program. Create and decorate a form as shown in Figure 5.13 .
Figure 5.13
Demonstrating input
Validation with an
program
addition
Listing 5.14: Demonstrating effect of invalidated input with a simple addition program
Private Sub cmdAdd_Click()
1:
Dim A As Integer, B As Integer
2:
Dim C As Integer
3:
A = txtNum1.Text
4:
B= txtNum2.Text
5:
C = A + B
6:
lblResult = C
End Sub
Run the program and put 23 in the first and 11 in the second. You should have expected
results. Now, put 3 in textbox # 1 and 3B into textbox #2. Test the program again.
What do you notice? You would have an error similar to that displayed in Figure 3.14
when you execute Listing 5.14.
String Arithmetic
257
Figure 5.14
Dialog Box
displaying Error 13
(Type Mismatch
Error)
258
Function Name
Number of Argument
Argument Type
IsNumeric
Variant
IsNull
Variant
IsEmpty
Variant
IsDate
Variant
NOTE
All the data inspection functions return a Boolean data type.
We demonstrate an example with the IsNumeric Function. The Program below consist of
a Command Button( cmdExecute), a text box(txtNumber) and a label(lblResult). Its
function is to accept a positive number from a user and evaluate its square root.
Listing 5.15: Demonstrating input validation with the data inspection function.
Private Sub cmdExecute_Click()
1: Dim dblNumber As Double,strMessage As String
2: If IsNumeric (txtNumber.Text) Then
3:
dblNumber = txtNumber.Text
4:
If dblNumber >= 0 Then
5:
lblResult.Caption = SQR(dblNumber)
6:
Else
7:
StrMessage=Your Entry Must by a number & _
g
greater than or equal to zero
8:
Msgbox strMessage , vbInformation
9:
End If
10: Else
11:
Msgbox Your data must be numeric ,vbInformation
12: End If
End Sub
The If Then Else statement was used to implement listing 5.15. The calculation is done
if the argument is numeric, otherwise a message box is invoked requesting for a numeric
entry. A common implementation used in many software design is to avoid calculation
using Exit Sub if an invalid entry is encountered. The implementation using this
technique is as shown in Listing 5.16
String Arithmetic
259
Listing 5.16 Input validation with the data inspection function and Exit Sub statement
Private Sub cmdExecute_Click()
1: Dim dblNumber As Double,strMessage As String
2: If NOT IsNumeric (txtNumber.Text) Then
3: StrMessage=Your Entry Must by a number greater than
4: Msgbox strMessage & or equal to Zero , vbInformation
5:
Exit Sub
6: End IF
7: dblNumber = txtNumber.Text
8: If dblNumber >= 0 Then
9:
Msgbox Your data must be numeric ,vbInformation
10:
Exit Sub
11: End If
12: lblResult.Caption = SQR(dblNumber)
End Sub
The Example above uses the Exit Sub Statement to exit the subroutine when an Invalid
Entry is Encountered in the Text box. This technique is better than the first. The reason is
that if two or more text boxes are in the form, we can use a subroutine to process all the
text boxes and avoid the problematic nested If Then Else structure.
Sometimes in cases where multiple input fields exist, we need to draw the users attention
to the particular field with the problem. You accomplish this with the SetFocus method
as follows.
1: With txtNumber
2:
.SelStart = 0
3:
.SelLenght = Len(.Text)
4:
.SetFocus
5: End With
The purpose of the code segment above is to select(highlight) all the text in the text box
which has the non-numeric entry. Lines 1 and 5 are the header and footer of the With
block. Line 2 tells the system to start selecting just before the first character. Line 3 tells
the system the number of characters to select. i.e It evaluates the Length of the text box.
Line 4 sets the cursor blinking at the textbox. Place the 5 lines of codes above between
all the message box statements and the exit sub statements in Listing 5.16 and run the
program again. It should behave expectedly.
Apart from data type inspection, you can perform other forms of input validation like
data range and data quality in practical problems.
260
When working with numerous text fields, it is better to place validation code in the
Validate event of each textbox so that a user must complete an input textbox with
required data before moving to another field. The Cancel parameter in the Validate event
is used to prevent focus transfer from the text box if it is set to True. Listing 5.15 shows
an input validation code implemented in the Validate event.
Listing 5.15: Input Validation using the Validate Event
Private Sub txtTemperature_Validate(Cancel As Boolean)
1: If Not IsNumeric(txtTemperature.Text) Then
2: MsgBox "Temperature must be numeric!", vbExclamation, _
"Invalid Input"
3: Cancel = True
4: End If
5: If Val(txtTemperature) < 0 Then
6:
MsgBox "Reservoir temperature must be greater 0" & _
"degree Farenheit ", vbExclamation, "Invalid Input"
7:
Cancel = True
8: End If
End Sub
Listing 5.15 has two conditional statements used to test for data type and data range
agreement. The Cancel parameter does all the job for the validate event. Setting it to
True prevents focus transfer from one control to another control whose CausesValidation
property is set to True.
QUIZ
How is the CausesValidation property of one control related to the Validate event of
another control ? . re?lated to
String Arithmetic
261
Problem Set 5
Question 5.1
Given that strA is to hold input of the form 8.6+4.9-7.2+2+7+4-4-7-4-6+4-9+1-3
Study the Code segment below and explain what it does
Dim Sum As Single,intP1 As Integer, intP2 As Integer
Dim strA as String
StrA = -2+9-5.8-7+5.9-9+3-8-5+112-3+73
Sum =0
Do
intP1 = Instr(2,A, +)
intP2 = Instr(2,strA, -)
IF intP1 > 0 and intP1 < intP2 Then
Sum = Sum + Val(Left(strA,intP1 1))
strA = Mid(strA,intP1)
Else If intP2 > 0 And intP2 < intP1
Sum = Sum + Val(Left(strA,intP2 1))
strA = Mid(strA,intP2)
End If
Loop While (intP1 > 0 or intP2 > 0)
Sum = Sum + Val(strA)
Question 5.2
Write a program that accepts a number and add separator to the number after three digts
from the right. E
.g the number 42635734725733 should become 42,635,734,725,733
Question 5.3
Write a program which accept a number and converts it to words e.g input of 2543
returns Two Thousand Four Hundred and three
Question 5.4
Write a program which accepts a number in words and converts it to digits. Example Six
thousand Five Hundred and Two should Return 6502
Question 5.5
Given the input Sample
.2,3,4,5,12,+4,~1,.2,3,4.,`1,1,3,2,3,12,.12,23,16,17,19,
13,17,0,2,0,2,35,3,4,(4,11,4,3,4,10,12,23,17,,,13,14,17,1
4,18,19,20,4,2,*3,4,6,12,5,3,9,8,4,5,7,9,7,6,6,7,2,L,l,Ll
,3,1,0,1,11,3,8,3,4,6,3,6,7,8,9,3,12,=3,3,2,w,3,2,3,4./,p
262
,r,4,,3,gg,4,5,6,a,4,5,6,1,c,5,47,(,,4,3,4,5,6,2,1,4,5,@,3,4,2,4
Write a program that scans the string, remove bad characters.(In this case bad characters
are any entry apart from numbers and comma used as delimiter). Also, in situations
where consecutive commas occur without numbers in between, remove all except one.
Split the Resulting String into an array and find the following
Mean, Median ,Mode, Range and Standard deviation of the distribution.
Note:You have to Prepare a frequency table for the Distribution.
Question 5.6
Write a program that accepts a Trigonometric or polynomial function in a textbox and
evaluate it at some specified value of X
Question 5.7
Write a program which accepts atleast 5 sentences in a text box and display each line in
another text box with multipline set to True.
Question 5.8
Write a program capable of converting a number(including duodecimal and hexadecimal
numbers) from one base to the other.
Use the following level of input validation
a) Message box to prompt the user for data type and data range controversies
b) Enable property to disable the convert button when data type or data quality problem
arises
c) ASCII functions in the keypress event to prevent unwanted characters from being
typed in the text box.
d) Use Visual Basic controls that will strictly restrict the user from entering invalid data.
Note: A number in base n must consist of digits which are all less than n. i.e in base 8 no
entry should be up to 8.
Question 5.9
Write a program to implement the interface shown in Figure Q5.9 . You may use either
string functions or script control (see chapter 9)
Your program should be able to evaluate any other function placed in the text box.
String Arithmetic
Figure Q5.9
Proposed interface for
Trigonometric functions
manipulations
Question 5.10
Figure Q5.10 shows the standard windows calculator. Design and implement the
calculator. You may ignore the menus.
Figure Q5.10
Standard Windows
Calculator.
Question 5.11
Write a program to find the nth term of the sequence
1, 11 , 21 , 1211 , 111221 , 312211, 132221,11133211
263
264
Question 12
Design and implement the change case dialog shown in Figure Q5.12
Figure Q5.12
Proposed interface
for change case dialog
Question 13
Write A Program which accept a decimal number and converts it to simplified proper
fraction.
Question 14
In Linear form, two dimensional arrays can be written with each element separated with a
comma and each row separated by a semi colon(;) as follows.
A = {3,2,-1,3;3,2,21,4;-1,0,3,4;2,-3,4,5} Write a program which accepts a matrix in the
Linear form to the conventional form shown below.
2 1
3
2 21
3
A=
1 0
3
2 3 4
4
4
String Arithmetic
265
Question 15
Design and implement the interface shown in Figure Q5.15a and b used to manipulate
fractions. Note that Figure Q5.15shows as a modal form on Figure Q5.15a when the
options command button is clicked.
Figure 5.15a
Proposed interface
for fraction and
whole numbers
manipulations.
Figure 5.15b
Option dialog used to customize
the setting of figure 5.15a
CHAPTER
6
Functions and Sub Procedures
Creating Functions
Sub Procedures
Sub Main
Event Procedures
Problem Set
267
Creating Functions
After studying string functions, the clause creating function should be quite familiar.
Once the syntax of a function is known, one can use it to achieve results. One thing that
comes to mind when using function is that all functions must return a value. Our only
worry is that we have to know the data type to return so that we can make valid
assignments. Also, the number, types as well as sequence of arguments are equally
important in functions utilization. For example, the following attributes about the Len
function must be known before using it. These are
It has only one argument
It returns an integer
It accepts string as the argument
Its argument is not optimal
Knowing these, you can make use of the Len function as follows
Dim strName As String
Dim intLength As Integer
strName= Itua
intLength= Len(strName)
This works very well because we have used valid data types. You can also write your
own function and use it in much the same way as the in-built functions. Given that you
want to write a function to add two numbers, your function header and footer should take
the form.
Private Function Sum(X As Integer, Y As Integer) As Integer
.
.
.
End Function
The body above assumes that a function Sum is being declared. The function has two
integer parameters X and Y while the function returns as Integer.
From the information we gathered about the Len function, we immediately know that it
was declared as
268
Function Definition
The definition of a function entails writing code to enable the function know how to do
things with the data passed to it. Defining the sum function is quite easy since it entails
adding the data passed to it (arguments) and assigning the results to the name of the
function as follows.
Public Function Sum(X As Integer, Y As Integer ) As Integer
Sum= X + Y
End Function.
So easy! Once the header of the function is written, the implementation is just to
manipulate the parameters and assign the result to the function name. You could as well
declare a variable (a local variable ) to hold the sum before assigning as follows
Public Function Sum(X As Integer, Y As Integer ) As Integer
Dim intTemp As Integer
IntTemp = X + Y
Sum = intTemp
End Function.
269
Both functions perform the same operation. The later Method used a local variable to
hold the sum before it is eventually returned to sum.
The declaration and definition of a function used to find the maximum of three numbers
is demonstrated as follows.
Function Max(X As Integer, Y As Integer, Z As Integer) As integer
.
.
End Function
Notice the absence of the Public/Private keyword in the function declaration. Here,
because the scope was omitted, a Public scope was assumed. The omission was
intentional. Always add the Public/Private keyword in your declaration so that it could
be readable though the compiler always use the default if no scope is specified.
The definition is written as
Function Max(X As Integer, Y As Integer, Z As Integer) As integer
Max = X;
If Y > Max Then Max = Y
If Z > Max Then Max = Z
End Function
In the function declared above, all the parameters are passed as Integer. The Max is
assumed to be equal to the first parameter. This Max is then compared with the second
and third parameters. Y is assigned to Max if Y is greater than Max. The last line assigns
Z to Max if Z is greater than the current value stored in Max
To implement reusable functions in Visual Basic, you write your functions in a standard
Module. To add the standard module to the project, follow the steps below:
270
1. Open the Project menu and select Add Module. This opens the dialog shown in
Figure 6.1
Figure 6.1
Visual Basic Add
Module dialog.
2. Click the Open button in the Add Module dialog to open the standard Module as
shown in Figure 6.2.
Figure 6.2
Visual Basic Standard module
3.
271
Use the Tools menu to create the Function declaration by Selecting Add Procedure
from the Tools menu. This shows the Add Procedure dialog in Figure 6.3
Figure 6.3
Visual Basic add procedure
dialog
4. Type Max as the procedure name and select Function option and Public option as the
procedure Type and Scope respectively.
5. Click OK to create the procedure header and footer as well as close the Add
Procedure dialog. The header and footer usually do not have parameters and return
type as shown in Figure 6.4. You add the appropriate parameters(or arguments) as
well as the return type.
Figure 6.4
Standard module showing
the header and footer of
the max function created
using the Add Procedure
dialog.
272
6. Enter appropriate code in the body to completely define the function as shown im
Figure 6.5
Figure 6.5
Standard module
showing the complete
declaration and
definition of the Max
function.
NOTE
Because of the presence of the standard module, you will be prompted to save your
project three times. One for the Form object, another for the Standard module and the last
for the project.
273
Figure 6.6
Testing the Max function
with Visual Basic Form and
controls.
Listing 6.1 shows that you use the user defined function in very much the same way as
the intrinsic functions are used. The user defined function was called in Line 6 with three
arguments passed to it. Observe that the variable passed to the function is different from
the variable used in the function declaration. This is OK as far as they agree in type.(i.e
Integer- Integer or Double Double as the case may be)
274
Figure 6.7
Error due to argument
Type mismatch when
passing arguments
ByRef. You avoid this
error by passing
arguments ByVal
When the ByVal keyword is placed before each argument, then Visual Basic uses only
the value of the arguments passed to implement the function. A revised and some what
fail safe version of the Max function passing arguments ByVal is as shown in Listing 6.2
Listing 6.2 Passing Function parameters ByVal
Option Explicit
Public Function Max(ByVal X As Integer,ByVal Y as Integer,
_ ByVal Z As Integer) As Integer
1: Max = X
2: If Y > Max Then Max = Y
3: If Z > Max Then Max = Z
End Function
With the code in listing 6.2 placed in the standard module, then one can call the Max
function in main with Integer, Long or Double arguments. The function can also be called
with string or date variable if an only if the string or date holds a numeric data. Another
good reason why arguments are passed ByVal is that the function can not change the
data stored in the variable since only the value is passed and not the variable. The
implication of this would become obvious subsequently.
Writing programs with user-defined functions make programming very cool. It makes it
easier for you to introduce algorithmic approach in solving complex programming
problems. We will now consider how to write more meaningful Visual Basic functions
under the following headings;
1.
Functions with no argument
2.
3.
4.
5.
6.
7.
8.
9.
10.
275
276
Some functions with one argument might involve loops and/or conditional statements.
One of such functions is the function used to return the factorial of a number written as
follows:
Listing 6.3: Implementing function with loops
Public Function Fact(ByVal Number As Integer) As Long
1: Dim I As Integer
2: Fact = N
3: For I = N-1 To 1 Step -1
4:
Fact = Fact * I
5: Next I
End Function
In the function above , once a number is entered, it is assigned to Fact so that the
For Next loop starts from the next lower consecutive number to 1. However, if 1 is
Entered, 1 is assigned to Fact. On Encountering the For Next loop, it decrements
number by 1(i.e the loop starts from 1 to ) step 1. Since this is not possible, the loop
fails and 1 is returned. In this case all went well. However, if index was declared as Byte
there would have been an overflow error because a byte has minimum of 0 and maximum
of 255. The function in Listing 6.3 was implemented using the relationship
N! = N.(N-1).(N-2) ... 1
CAUTION
Passing Integers greater than 12 to this function results in OverFlow Because 13! Is
greater than the Max value for Long. A Sharp solution is to resort to using currency so
that up to 15 digits could be used. This does not get beyond 17. A lasting and
recommended solution is to make the function return Double. However, this technique
sacrifices accuracy!
Other examples of functions which lend themselves to manipulation with one variable is
presented in Appendix A
277
Recall that the code segment below was implemented in chapter 3 (Listing 3.14) to
convert numbers from base 10 to base n.
Option Explicit
Private Sub Form_Load()
1: Dim N As Integer,B As Integer,Sum As String
2: N=InputBox("Supply number to be converted")
3: B=InputBox("Supply output Base")
4: Sum = ""
5: Do Until N = 0
6:
R = N mod B
7:
Sum = cstr(R) & Sum
8:
N = N \ B
9: Loop
10: MsgBox " Converted number is " & Sum
End Sub
You can Convert the program to a standard function by eliminating Line 2 and 3 (input
Lines) and passing them as arguments to functions. Line 13 will also be removed and
passed as the function return value. The declaration and definition takes the form shown
in Listing 6.4
Listing 6.4: Implementing the Number base problem as a function with two arguments.
Option Explicit
Function ConvertFromBase10 (ByVal N As Long, ByVal B As _
Long) As Long
1: Dim N As Integer,B As Integer,Sum As String
4: Sum = ""
5: Do Until N = 0
6:
R = N mod B
7:
Sum = cstr(R) & Sum
8:
N = N \ B
9: Loop
10: ConvertFromBase10 = Sum
End Sub
The difference between actual programs and functions should become obvious to you. In
functions, the Input are the parameter passed to the function while the output is then
returned to the function name as function return value. Observe that Listing 6.4 does not
have Lines 2 and 3. These lines were omitted intentionally so that Listing 3.14 can be
compared one on one with Listing 6.4
278
Clearly this is a function with three arguments. The implementation of this is left as an
exercise.
279
3:
max = X1
4:
If Ubound(X2) > -1 Then
5:
For I = 0 To UBound(X2)
6:
If X2(I) > max Then max = X2(I)
7:
Next I
8:
End If
End Function
In the function above, Line 3 sets the max to be equal to the only required argument.
Line 4 used an If statement to test whether other optional arguments are specified. Line 5
sets a loop to process other arguments if Line 4 evaluates to True. Also If the other
arguments are not specified then the loops fail to execute because the start point is
greater than limit and increment is > 0. In this case the function returns the first argument
as the max. However, if more than one argument is specified, the Ubound of the function
will be greater than -1 hence, the second to the last arguments are taken as the array of
parameters. In this case the For Next loop in line 5 executes atleast once thus
comparing the current max with the argument specified. This continues until all the
arguments are treated. When using paramarray, it is important that we note the following:
1. The minimum number of arguments must be specified when using the function.
2. The Ubound of the paramarray is 1 if only the minimum argument(s) is/are
specified.
3. Paramarray type must always be variant.
4. A For Next loop should be used to process other arguments if the ubound of the
array is greater than 1.
5. The Lbound of a Paramarray is unaffected by the Option Base statement.
A function with optional argument is a function with fixed argument though some
arguments may be omitted at times. In this case, a default argument is assumed. A
function with five arguments can be written with the last three arguments as optional.
Here the function can be called with two, three , four or even five arguments. The fact
that this function can not be called with more than five arguments makes it different from
a function with indefinite arguments. A function with indefinite arguments can be called
with as many as 100 arguments and always carry the keyword paramarray in its
declaration. Likewise, a function with optional argument carries the optional argument in
its declaration as follows.
280
281
Table 6.1; Tests results for the SumAp function using the immediate window.
Syntax
Print
Result
Implication
15
Print Sumap(10,2)
54
Print Sumap(13,,2)
49
Print Sumap(10,2,5)
Sumap(5)
Print Sumap(,1,3)
Error
Print Sumap(,,3)
Error
Print Sumap()
Error
Having understood how to write and use functions with optional arguments, you can
think of situations where you will need functions with optional arguments. Functions
with optional arguments can also be written in terms of functions with default arguments
as shown in the procedure above.
Listing 6.7: Alternative implementation of function with optional arguments
Public Function SumAp(ByVal Limit As Long, Optional start _
= 1, Optional increment As Integer = 1) As Long
1:
Dim I As Long
3:
SumAp = 0
4:
For I = start To Limit Step increment
5:
SumAp = SumAp + I
6:
Next I
End Function
Observe how simple the default arguments made the function to be. We advise that you
write functions with default arguments as shown in listing 6.7 instead of using the
IsMissing functions. The reasons why default arguments are preferred to optional
arguments include but not limited to the following
282
NOTE
The size of an array is given by Ubound Lbound + 1
A function used to determine the Average of an array of data is as shown in Listing 6.8
Listing 6.8: implementation of function with array as argument.
Function Average(A() As Variant) As Double
1: Dim Size As Integer, I As Integer, Sum As Double
2: Size = UBound(A) - LBound(A) + 1
3: For I = LBound(A) To UBound(A)
4:
Sum = Sum + A(I)
5: Next I
6: Average = Sum / Size
End Function
A variant dynamic array was declared in the header as the parameter of the array. This is
the method that will be applied to all arrays passed as parameters to functions. A better
program to write is to provide two or three optional parameters. These parameters will
stand for the Lower bound of the user array, the upper bound of the user array and the
number of terms to be evaluated in the user array. In this case you can set the lower
bound of the user array to be 0(default or 1 depending on the Option Base statement) if
not specified. The other optional arguments must be specified using the IsMissing
Function as shown in Listing 6.9.
Listing 6.9: Alternative implementation of function with array as argument
Function Average(A() As Variant, Optional LowerBound
Integer = 0, Optional UpperBound) As Double
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
283
284
strings or dates and any data type assigned to it, then it should strike our mind that by
implication, variant data type can also accept arrays of any dimension and type. This is
the principle used to return arrays from functions in Visual Basic. With this in mind, we
can now write our own function that returns an array. We take a simple example with a
function that accepts an array and returns the absolute value of the deviation of each item
in the array from the mean. i.e xI mean where xI is the ith array item. This is as shown
in Listing 6.10
Listing 6.10: implementation of function which returns an array
Function MeanDev (X() As Double) As Variant
1:
Dim lb as Integer, Ub as Integer,Temp() as Double
2:
Dim index as Integer
3:
LB=Lbound (X) : UB=Ubound(X)
4:
Redim Temp (LB to UB) As Double
5:
Mean = Average (X)
6:
For I = Lb to Ub
7:
Temp (I) =Abs (X (I) Mean)
8:
Next I
9:
MeanDev = Temp
End Function
To return an array to a function is as simple as assigning an array to the function name
which must be declared as variant. Note that Listing 6.10 assumes that you have the
average function which is visible in the module containing the MeanDev function .
NOTE
As used in this context, MeanDev function is not the same thing as mean deviation
because mean deviation returns only one value (a scalar) not an array.
The function written in Listing 6.10 returns an array of variant. To return an array of
specific type, your header should be as shown below.
Function MeanDev (X() As Double) As Double()
Note that without the open and close parentheses attached to the double, the function
wouldnt work.
285
class are called Properties while the functions used to manipulate the data are called
Methods. An object must not necessarily be a control like the text box or command
button. A variable can also be declared as an instance of a class and hence called an
object . Visual Basic calls variables declared as instances of a class object variables. You
declare an object variable in the same way you declare other variables. Given the
declaration
Dim X As TextBox
We say that variable X has been declared as an instance of the TextBox Class and hence,
variable X is called an object variable.
NOTE
When a text box is removed from the toolbox and placed on the Form, we say an instance
of the text box class has been created. Objects created in this form are called controls.
After declaring an object variable, you define it by setting it to be equal to any control of
the same class. E.g
Set X = txtSurname
After setting X to be equal to one of the controls in the form, we can now manipulate X
in code the same way we would have manipulated any text box control.
To confirm this, start a new line and write X dot. You observe that all the properties of x
appears after pressing dot. Once a property is changed, you can assign this property to
any text boxs property and have the same result as assigning a property from a text box
control to another text box. Note that the following statements are valid
X .Text = This is interesting
txtSurname.Text = X.Text
We will demonstrate an example with a function that accepts a text box object and
returns the number of characters in the text box. The function was implemented in listing
6.11 with an optional argument that determines whether spaces should be counted or not.
Listing 6.11: Implementing a function which accepts an object as argument.
Option Explicit
Function Mlen(txtBox As TextBox, Optional intsetting As _
Integer = 0) As Long
1:
2:
3:
4:
286
5:
Mlen = Len(Trim(txtBox.Text))
6:
Case 2
7:
Mlen = Len(LTrim(txtBox.Text))
8:
Case 3
9:
Mlen = Len(RTrim(txtBox.Text))
10:
Case is >= 4
11:
For index = 1 To Len(txtBox.Text)
12:
T = Mid(txtBox.Text, I, 1)
13:
If Asc(T) <> 32 Then strTemp = strTemp & T
14:
Next I
15:
Mlen = Len(strTemp)
16:
End Select
End Function
In the function above, if the setting is less than 1 then the function evaluates the len of
text box with spaces counted. Setting 1 Trims the text completely before evaluating the
Len. Setting 2 and 3 left and right trim the text before evaluating the Len. A setting 4 and
above evaluates the Len of the text after removing all the spaces(both inner and outer
spaces). You can test the program above with a simple input/output program. Place a text
box and a label on the form and give them appropriate names. Then place the following
code in the click event of the form
lblResult.Caption =mLen(txtInput,0)
It should give you the number of characters in the textbox including spaces. Replace the
second argument with 4 and observe that it gives you exactly the number of characters
with the spaces not counted. This is a very important function. We have been able to
modify the Visual Basic Len function. Note if the second argument is not specified, the
Mlen function and the Len function gives the same results. Test your Mlen function with
other sets of values; your program should be well behaved.
Now what if you want to return the Len of the trimmed string, the string itself and the
trimmed string and whether the string has been modified or not?. That is an attempt to
return more than one value from the function! In this case, the function has to return a
text box(i.e an object). By this time, you will be doubtful whether a single function can
return four values by just returning a textbox. Of course, this is possible if you remember
that the textbox has scores of properties that can be modified and returned with the
textbox. For the task we have at hand, we are confronted with the problem of returning
four values, two of type string, one Long and one Boolean from one function. To solve
this problem we search the properties window and look for two Read/Write properties of
the text box that evaluates to give a string and then assign the text to these properties. The
first property that is very handy is the text property. The problem now is, apart from the
text property which other property of the text box can be used since two text properties
are required. On searching the object browser you notice that the name property is a
287
string property but it is read only so it cant be used. The Visual Basic Object Browser in
Figure 4.10 shows that the Tag property is a string property that can rightly be used.
Figure 6.8
Visual Basic Object
Browser showing
the properties of a
Text Box.
On checking the object browser carefully, you will discover that other string properties of
the textbox are the SelText and Password character. Also two common properties that
evaluate to give Boolean are the Visible and Enable properties while the height property
returns Long. Having all these in mind, we can modify our function as follows
Listing 6.12: Function which return as object.
Function Mlen(txtBox As TextBox,
Integer = 0) As TextBox
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
Optional
intsetting
As
Integer
strTemp
strTemp
strTemp
288
14:
Case is >= 4
15:
For I = 1 To Len(txtBox.Text)
16:
T = Mid(txtBox.Text, I, 1)
17:
If Asc(T) <> 32 Then strTemp = strTemp & T
18:
Next T
19:
Mlen.Height = Len(strTemp) :Mlen.Tag =strTemp
20:
End Select
21:
If Mlen.Height <> txtBox.Height Then Mlen.Enabled _
=
= False
End Function
NOTE
The enabled property helps you to check whether the string has been modified or not.
Once you check the Mlen Enabled property and it evaluates to false, then you know that
the string has been changed. You can then access the Tag Property to get the
changed(Trimmed) string.
Recursive Functions
A recursive function is a function that can call itself. A recursive function can only be
implemented recursively with a language which supports recursion. Fortunately, Visual
Basic supports recursion and hence can be used to implement recursive functions
recursively. A simple and common example of a recursive function is the HCF function.
Here, the problem of evaluating the HCF of two numbers using the Euclidean recursion
relation stated as follows.
B ,
A mod B = 0
HCF(A,B) =
HCF(B,A mod B)
A mod
B 0
289
As
Observe how short the function is. This is because a recursive problem was implemented
recursively. In any recursive problem, you have a base case(s) and the recursive case(s).
The function continues to call itself until the base case is reached.
CAUTION
When a function calls itself inside its body, it is said to be recursive.
Another example of a recursive function is the factorial function defined as
N! = N.(N-1).(N-2) ... 1
N! = N * (N- 1)!
The recursive definition is written as
1 ,
N = 0,1
Fact(N)
Fact(N-1) * N ,
> 1
290
Sub Procedures
A sub procedure is a collection of Visual Basic statements written to perform one or more
actions on variables and/or objects. Like functions procedures, sub procedures may have
zero, one, two or more arguments. The major difference between a function procedure
and a sub procedure lies in the returned data types. While a function must return a
value(conventional data types, arrays or objects), a sub procedure must not necessarily
return a value, but accomplishes some tasks within the project/system. Also, while a
function procedure returns only one value, a sub procedure can return more than one
value.
NOTE
The Fact that functions can return an object which in turn comprises of so many
properties that can be isolated does not translate to mean that functions can return more
than one value. The reason is that only one object is returned. However, a subroutine can
return as many values (arrays/objects) as possible.
Because sub procedure are not meant to return a specific value, the declaration of sub
procedure does not include the return type. A typical header for a sub procedure is as
shown
Public Sub swap(number1 As Double, number2 As Double)
.
.
.
End Sub
Observe that the only difference between this declaration and the function declaration is
the presence of a sub(instead of Function) keyword and absence of return value for swap.
Also, the footer of the sub procedure ends with End Sub instead of End Function in
function Procedure discussed earlier.
In the body, one of the most striking differences between a function body and a sub
procedure body is the absence of the Sub Name in the body. On no account should the
Sub name be used within its body unlike in function procedures where the function name
can be used as a variable in the body of the procedure.
In order to compare sub procedure and Function procedure, we demonstrate an example
using the swap Procedure
291
Listing 6.16: Using the user defined Sub procedure in a Visual Basic program
Private Sub cmdSwap_Click()
1:
Dim Xvalue As Double, Yvalue As Double
2:
Xvalue = txtX.Text
3:
Yvalue = txtY.Text
Call Swap(xvalue, yvalue)
5:
txtX.Text= Xvalue
6:
txtY.Text= Yvalue
End Sub
Run the program and notice that as you click the swap button, it toggles the number in the
textboxes. This is how sub procedure works. You call the procedure with the call
292
keyword. Also you do not need to enclose the arguments in parenthesis unlike in
Function procedures. Once the Sub is called, an action would be performed (i.e
interchanging the text in the text boxes). You can also write statement 4 without the Call
keyword as follows
Swap xvalue, yvalue
It will still work. Observe that when the call keyword is removed, then the parentheses
enclosing the arguments should be removed otherwise a compile error pops up.
NOTE
Like a function procedure, a sub procedure can call another Sub procedure or a function
as far as the procedure or function is visible within the scope of the sub.
Also, arguments of a sub procedure can be passed ByRef and ByVal as with functions.
293
The code automatically selects all the content of txtSurname. This example is meant to
demonstrate passing objects as argument to Sub Procedure. Apart from the textbox, other
objects could also be passed to the sub.
Important aspect of programming where objects passed to sub procedure help to simplify
programming tasks are
When chart titles or axes or series are passed to a format object sub procedure
During input validation when each text box on the Form has to be passed to an
EnsureNumeric Sub procedure for validation. This is demonstrated using Listing 6.18
Listing 6.18:Using objects passed to sub procedure for input validation
Public Sub ValidateTextBox(txtBox As TextBox)
If Not IsNumeric(txtBox.Text) Then
MsgBox "Entry must be Numeric ", & _
vbExclamation, " Invalid Entry "
txtBox.SelStart = 0
txtbox.SelLength = Len(txt.Text)
txtbox.SetFocus
End IF
End Sub
With the code above, you simply validate each textbox on the form before assigning data
to it. After variable declarations, you place the call to the ValidateTextBox sub and pass
each textbox to the sub one after the other as follows.
ValidateTextBox(txtPressure)
ValidateTextBox(txtVolume)
ValidateTextBox(txtTemperature)
Observe how passing objects to subroutine simplify validation in a multi-textbox
applications.
b + b 2 4ac
X1 =
2a
X2 =
b b 2 4ac
2a
294
For real roots, b2 4ac > = 0. We can implement this sub by passing the arguments
A,B,C byVal and then returning the calculated roots to X1 and X2 which are going to be
passed ByRef. After the call to the sub, you can access X1 and X2 to get the roots. The
Sub is as shown below in Listing 6.19.
Listing 6.19: Returning multiple values from functions
Public Sub Quadratic(ByVal A As Double,ByVal B As
ByVal C As Double, ByRef X1 As Double, ByRef X2 As
1:
Dim dblDiscriminant As Double
2:
dblDiscriminant = B ^ 2 - 4 * A * C
3:
If dblDiscriminant >= 0 Then
4:
X1 = (-B + Sqr(dblDiscriminant)) / (2 *
5:
X2 = (-B - Sqr(dblDiscriminant)) / (2 *
6:
End If
End Sub
Double, _
Double)
A)
A)
Because X1 and X2 were passed ByRef(by reference), the values in the variables can be
accessed by assigning them to other variables or object properties. This is an example of
returning multiple values from subroutine. A test driver used to test the workability of
Listing 6.19 is shown in Listing 6.20 using the interface of Figure 6.9.
Figure 6.9
Obtaining quadratic roots using
sub procedure that return multiple
values
295
Sub Main
Sub Main is a sub procedure used to start an application without a Form. To start an
application with the Sub main instead of a Form, follow the steps outlined below.
1. From the Project menu, choose Project Properties.
2. Activate the General tab in the project properties dialog.
3. In the Startup Object list box, select sub main as the start up object.
296
4. Click OK .
You need the sub main when you want to execute a code that loads a data file and then
displays one of several different Forms depending on what is in the data file. You can do
this by creating a Sub procedure called Main in a standard module. Listing 6.21 shows a
Sub Main used typically to start a project
Listing 6.21: Starting a project with the Sub Main
Sub Main()
1:
Dim S1 As String
2:
Open "C:\Egbe.txt" For Input As #1
3:
Input #1, S1
4:
If S1 = "A" Then
5:
Form1.Show
6:
Else
7:
Form2.Show
8:
End If
Close #1
End Sub
Here one of two Forms can be used to start a project depending on the content of the File
opened in Line 2. Another importance of the Sub main is that it could be used to load a
splash screen on start up. Here, the sub main is used to start the splash screen. A splash
screen is a Form, usually displaying information such as the name of the application,
copyright information, and a simple bitmap while an application is loading. Figure 6.10
shows the splash screen of Microsoft Visual Basic while Listing 6.22 shows the code
used to activate a typical splash screen.
Listing 6.22: Showing a splash screen with the aid of Sub main
Private Sub Main()
' Show the splash screen.
1:
frmSplash.Show
' Show the main form and unload the
' splash screen immediately.
2:
frmMain.Show
3:
Unload frmSplash
End Sub
The comment in Listing 6.22 actually explains the sub procedure. In practice, you will
need to add some start up procedures before showing the main Form. Without the start up
procedures, you might not notice the splash screen because it will be too fast.
Visual Basic Start Up splash screen.
297
Apart from using the Sub main, you can also use the Timer control and the DateAdd
function to control the splash screen as shown in Listing 6.23
Listing 6.23: Controlling the splash screen using the Timer Control.
Option Explicit
Dim FirstTime As Date
Private Sub Form_Load()
1:
FirstTime = Now
2:
Timer1.Enabled = True
3:
Timer1.Interval = 1000
End Sub
Private Sub Timer1_Timer()
6:
Const Number = 6 'Number of seconds to wait
7:
Dim TargetTime As Date
8:
Dim IntervalType As String
9:
IntervalType = "s" '"s" specifies seconds as interval
10:
TargetTime = DateAdd(IntervalType, Number, FirstTime)
11:
If Now > TargetTime Then
12:
Form1.Show
13:
frmSplash.Hide
14: End If
End Sub
Listing 6.23 has two event procedures, the Form Load and the Timer control Timer
event. The Form Load is used to initialize the FirstTime to now( current time or date as
the case may be)and to enable the Timer control as well as to set its interval to 1000
(milliseconds which is equivalent to 1 second.) Line 6 declares a variable used to set the
number of seconds to wait. Line 9 sets the IntervalType to seconds, "s".(see Table
2.11 and 2.12). Line 10 sets the target time using the date add function. Lines 11 to 14 are
used to hide the splash screen and show Form1 if the current time(now) exceeds the
TargetTime
NOTE
For the code shown in Listing 6.23, you have to add the timer control to the form. In
listing 6.21, the date function Now was used to get the current time. You can achieve the
same effect by using the Time function. The difference between Now and Time is that
the Time function returns only the current time why Now returns both the current time
and the current date. Also, the Timer function is different from the Time function in that
the Timer returns a single representing the number of seconds elapsed since midnight.
298
By carrying out appropriate string manipulation, one can convert the Timer to Time and
vice versa.
Problem Set 6
Question 6.1
a Using strings write a function that reverses an array of numbers.
b Repeat Problem 1a using conventional data structures
Question 6.2
Write a function that determines the nth position of occurrences of a particular character
in a string. Add limiting conditions such that if n > number of occurrences of that
character, then it returns the last position of occurrence of the specified character.
Question 6.3
Write a modified Val Function Mval that converts a string to numeric Value. Your
function should have optional Boolean argument and ignores leading non numeric
character if the setting is Set to True. E.g A34 should return 34 and A2B.C3 should
return 2.3. note if the optional argument is set to False, it should behave like the Len
Function. Take This as the default
Question 6.4
Write a function that converts a hexadecimal number to base 10.
Question 6.5
a) Write a function that converts a matrix in conventional form to linear form.
b)Write a function that converts a matrix in linear form to conventional form.
Question 6.6
Write a function, confrac that converts a fraction to decimal. Also implement a function
that converts a function that converts a number in decimal to fraction. Use the technique
of decimal shifting to handle recuring decimals.
Question 6.7
a) Most pressure gauges report time and pressure in the form
HH:MM:SS,PP e.g 01:21:56,4000 means after a time of 01 hour, 21 mins and 56
seconds, the pressure is 4000 psi. Write a function that accepts an array of n data in the
form expressed above and return an n by 4 matrix such that the hours values are placed
in the first column of the matrix, the Minutes in the second column of the matrix , the
Second in the third column and pressure in the fourth column.
299
b) Write a function that calls the function in 6.7a above and converts the n data in the
form HH:MM:SS,PP data to an n by 2 array(consisting of Time and Pressure) such that
the HH:MM:SS values are converted to Hours.
Question 6.8
a) Repeat Listing 6.23 using the Timer function instead of the DateAdd function
b) Repeat Listing 6.23 using the DateDiff function instead of the DateAdd function
Question 6.9
Given the Serious limitation of the Visual Basic split function, write a modified Split
function that splits a given string to a one dimensional array with or without a delimiter.
In the absence of a delimiter, your function should assume an Empty string(Zero len
String) as the Delimiter.
CHAPRTER
7
Controls Array
Creating Controls Array
Array of Text Boxes
Array of List Boxes
Array of Grids
Array of PictureBoxes
Array of Lines
301
As mentioned in the last section, array is an important data structure that is widely
supported by almost all-programming languages. The advantages of using array instead
of multiple simple variables abound. Array lends itself to easy manipulations using
control structures and permits batch processing of data stored in it. Other important
attributes of arrays are that their elements can be loaded and unloaded at runtime by redeclarations. Like variable arrays, Controls array are group of similar controls in a Form
having the same name but are differentiated by their index in the group. Controls array
are manipulated in much the same way variable arrays are manipulated. Some of the
benefits of using controls array include but not limited to the following:
Properties of all elements of a control array can be changed easily using a Loop
structure.
Elements of the controls array share the same event procedure and hence only one
event procedure is required to handle the responses of all the elements of the array.
Apart from the first element, other elements of the array can be loaded and unloaded
at runtime.
Menu arrays are similar to controls array and posses all the attributes of controls array
and enjoy all the benefits of using controls array.
From the preceding discussion, we know that two or more similar controls with the same
name in the same Form are elements of a control array. By default, Visual Basic gives an
index of zero(0) to the first control and an index of 1, 2 ,3 to subsequent elements of
the array.
302
Figure 7.1
MessageBox
confirming the
creation of
control array.
NOTE
Once the first element of the control array has been created, any of the three methods can
be used to create other elements.
303
Now, open the code window and create the Click event procedure of cmdPlus and the
cmdNum buttons. What do you observe? Figure 7.2 shows that the Click event procedure
of cmdNum has an index parameter unlike the Click event of the cmdPlus.
Figure 7.3
Form Module showing
the event procedure of a
conventional control and
that of a control array
The index parameter in cmdNum event procedure is used to identify a specific item (or
element) in the array. Assuming you want the buttons to behave like the Calculator
buttons such that the caption of any button clicked should replace the text in the screen
you use the code below
Private sub cmdNum_click (Index as integer)
txtScreen.text = cmdNum(Index).caption
End sub
Observe how 6 controls are lumped together and processed as a single control. The index
is used to identify each control in the array. The code above is the basis of the code used
in the calculator project. We illustrate this in Listing 7.1 by giving you a modified event
procedure for the number CommandButton .
Listing 7.1: Click event procedure of an array of CommandButton(Calculator Extract)
Private Sub cmdnum_click (Index as integer)
1:
Dim strscreen as string
2:
strScreen = txtScreen.text
3:
txtScreen.Text = strScreen + cmdnum(Index).caption
End sub
Listing 7.1 is a segment of the code used to implement the windows calculator . Line 2
extracts the text on the Screen and assigns it to a variable. Line 3 concatenates the
304
caption of the Button clicked to Text on the screen. The Complete code for this is is left
as an exercise for the reader. The Code for the PlusMinus Button is as shown in Listing
7.2.
Listing 7.2: Reviewing the event procedure of a simple CommandButton control
Private Sub cmdPlusMinus_click ()
1:
Dim strScreen as String
2:
strScreen = txtScreen.Text
3:
txtScreen.text = -1 * Val(strScreen)
End sub
Observe that the PlusMinus button toggles the sign displayed by multiplying the Text on
the screen by 1
NOTE
This was actually designed with the Form Object CommandButton because the standard
CommandButton does not have the forecolor property. You add the Form Object controls
by selecting Form Object from the Visual Basic Components dialog.
305
NOTE
Before an element of a control array is loaded using code, at least one of its elements
must have been created at design time. When a control array element is created at run
time, the control inherits all the properties of the first element of the controls array except
the Visible property. This is the reason why control array elements are made visible after
creation as follows:
Because the Visible property is not inherited, you have to set the visible property of any
element created to True to enable you notice the presence of an additional element
Load cmdNum(1)
cmdNum(1).Visible = True
Follow the steps outlined below to test the code above
Create a new Standard Exe application
Add one command button with name cmdNum
Change the index of the control to 0
Open the Load event of the Form
Type the two lines of code above
Run the program.
Observe that despite setting the Visible property of the control, the newly created
CommandButton is still not visible. What might have been the cause of this? If you
remember that a control array assumes the same Top, Left, Width and Height properties
of the first element of the array then, it should strike you that the second control has been
created but cannot be seen until its left (or top) property is adjusted. Now modify the
code in the Form Load event as follows:
List 7.3: Creating a second instance of a control array at runtime
Private Sub Form_Load ()
1:
Load cmdnum(1)
306
2:
cmdNum(1).Visible = True
3:
cmdNum(1).Top = cmdNum(0).Top + cmdNum(0).Height + 200
End sub
Figure 7.4
Geometrical interpretation
Of the Top properties of
Two consecutive elements
Of a control array.
cmdNum(1).Top
Run the program. The second control should appear below the first. Line 3 was used to
set the height of this second element to 200 twips from the first. Figure 7.4 shows the
Visual representation of Line 3 of listing 7.3
cmdnum(0).Top
cmdnum(0).Height
Spacing of 200
NOTE
It is instructive to realize that code can only be used to remove elements of controls array
added with code. Also note that any reference to a control array element that have been
removed results in error.
To unload all the elements you use a For Next Loop as shown in listing 7.4
Listing 7.4: Unloading control array elements at runtime
Private Sub UnloadCommandButtons()
1:
Dim I as Integer
2:
For I = cmdNum.Lbound + 1 to cmdNum.Ubound
3:
Unload cmdNum(I)
4:
Next I
End Sub
307
in Listing 7.4, it was assumed that all the elements of the array were created at run time
apart from the first with index equal to the Lbound of the array
308
Figure 7.5
Output of listing 7.4.
You can choose to display your controls horizontally by changing the Left of the controls
as functions of Left of previous control and width of any element of the array. When line
6 is changed to the form
cmdNum(I).Left = cmdNum(I-1).Left + cmdNum(I).Left +200
then, the controls will be aligned horizontally instead of vertically
By suitably changing the Left and Top Simultaneously, you can create controls array
element in matrix form like the buttons of the calculator. The code for this is as shown in
Listing 7.6
Listing 7.6: Creating and aligning controls array elements in matrix form
Private Sub Form_Load()
1: Dim I as Integer, K as Integer
2: Dim NPC as Integer
NPC= Number per column
3: Dim N as Integer Count of buttons
4: NPC = 3
5: N = 8
6: For I = 1 to N
7:
Load cmdNum(I)
8:
cmdNum(I).Visible = True
9:
With cmdNum(I 1)
10:
If I mod NPC <> 0 then
309
11:
cmdNum(I).Left = .Left + .Width + 200
12:
cmdNum(I).Top = .Top
13:
Else
14:
cmdNum(I).Left = cmdNum(0).Left
15:
cmdNum(I).Top = cmdNum(I-1).Top + .Height + 200
16:
End if
17:
End with
18: Next I
End Sub
Run the program and observe that the array has been created and displayed as shown in
Figure 7.6. Line 4 sets the number of control wanted per column to 3. Line 5 sets the
upper bound of the array to be created. Line 6 and 18 are the Header and footer of the
Loop used to create and align the control. Line 10 is a header of the If then Else
statement used to confirm whether the control to be created should be align Left relative
to the previous controls Left or Top relative to the previous controls Top. Once the
index of the control to be created is not a multiple of three then it should be given the
new control a horizontal spacing of 200(line 11) from the previous control and the same
Top with the previous control(line 12). Otherwise if the index of the control to be created
is a multiple of 3 (line13) then it should have the same Left as the First element of the
control(Line 14) and the top should be spaced 200 twips from the previous.
NOTE
The twip is the default unit of measurement in Visual Basic. 1440 twip = 1 inch. You can
change the unit of measurement to inches or millimeter by changing the ScaleMode
property.
Figure 7.6
Aligning controls
array element
in Matrix Form using
code.
310
Listing 7.7 is a revised version of Listing 7.6. The output of Listing 7.7 is as shown in
Figure 7.7 . This alignment is akin to the alignment of the windows calculator.
Listing 7.7: Creating,aligning and labelling controls array elements in matrix form
Private Sub Form_Load()
1: Dim I as Integer, K as Integer
2: Dim NPC as Integer
NPC= Number per column
3: Dim N as Integer Count of buttons
4: NPC = 3
5: N = 9
6: For I = 1 to N
7:
Load cmdNum(I)
8:
cmdNum(I).Visible = True
9:
With cmdNum(I 1)
10:
If I mod NPC <> 0 then
11:
cmdNum(I).Left = .Left + .Width + 200
12:
cmdNum(I).Top = .Top
a12:
cmdNum(I).caption = Val(CmdNum(I-1).Caption) + 1
13:
Else
14:
cmdNum(I).Left = cmdNum(0).Left
15:
cmdNum(I).Top = cmdNum(I-1).Top + .Height + 200
a15:
cmdNum(I).caption = Val(CmdNum(I-NPC).Caption) NPC
16:
End if
17: End with
18: Next I
19: cmdNum(cmdnum.ubound).Caption = 0
End Sub
Listing 7.7 is same as Listing 7.6. the main difference lies in line 5 where the buttons to
be created have been increased to 9. Another significant difference is in line 12 used to
add to the caption of the ith element ith + 1 element for controls with same top( aligned
horizontally). However, for controls in the first column(array index multiple of 3(NPC))
you subtract three from the caption of the element in the kth - 1 row to obtain the caption
of the elements in the kth row(line a15). Line 19 sets the caption of the last element to 0.
NOTE
For the code in Listing 7.7 to work as expected, you have to give the first element of the
control array an index of 0 and a caption of 7
311
Figure 7.7
Aligning and labelling
controls array elements
in Matrix and Calculator
Form using code
Array of TextBoxes
Apart from configuring the calculator button, matrix representation of control array
elements is very important in algebraic manipulations of data and also as complement to
the non-editable grids. Data can be entered in matrix and vector orientation of array of
TextBoxes and transferred to any of the grid controls or ListBoxes as the case may be.
By changing the Line 4 and 5 of Listing 7.6 to m and n x m - 1, you can create an n by m
matrix orientation of an array of TextBoxes which can be used to sent data to grids.
Figure 7.8 shows a 5 by 6 matrix orientation of array of TextBoxes created by changing
NPC in line 4 to 4 and N in line 5 to 15 in listing 7.6.
Figure 7.8
Creating and
orienting array of
TextBoxes in
matrix Form using
code.
312
With the orientation shown in Figure 7.8, you can enter data and send to any data
structure(specifically List and Array) as shown in listing 7.7
Listing 7.8: Transferring Items from an array of TextBoxes to a data structure
1:
Dim A() as Variant,I As Integer
2:
ReDim A(txtData.Count 1)
3:
For I = txtData.Lbound to txtData.Ubound
4:
A(I) = txtData.Item(I).Text
5:
Next I
You can use a similar code to transfer to a grid. The likely problem is how to change a
one-dimensional array of TextBoxes displayed in two dimensional form to actual two
dimensional form! This is not two much of a problem when you know your operators
very well. With the modulus (mod) operator and the Integer Division operator (\), you
can achieve it. We illustrate this with an example.
Given a zero-based one dimensional array with 15 elements(i.e Ubound of 14), you can
convert the elements to a Zero-based two dimensional array of order 4 such that
B(0,0) = A(0)
B(0,1) = A(1)
B(0,2) = A(2)
B(1,0) = A(3)
B(1,1) = A(4)
B(1,2) = A(5)
B(2,0) = A(6)
Start of third cycle
:
:
B(4,2) =A(14)
Check the trend. It is obvious that the row index increases after each cycle ( one column
is a cycle). The index of the second element in the third cycle is B(2,1) which is equal to
A(3 * 2 + 1). Also, the first element in the fifth cycle is B(4, 0 ) = A(3*4 + 0). The next
element is B(4,1) = A(4 *3 + 1) and so on. With the trend we can generalize as follows:.
The array element A(n) when converted to a two dimensional matrix form with C
columns per Row is given as
B(n\c, n mod c) = A(n)
7.2
313
314
315
Figure 7.9
Transfering Items
from an array of
TextBoxes to a
grid
Control.
Array of ListBoxes
Since one of the most convenient methods of copying items from a ListBox to another
Data Structure is by using the List Array, it implies that an array of ListBoxes would be a
two dimensional array structure. Assuming 20 organic compounds are loaded in a
ListBox with style of 1(CheckBox List) and 6 physical properties of these compounds are
loaded in six other ListBoxes. By making these ListBoxes control array elements, you
can comfortably and conveniently manipulate the ListBoxes with only one event
procedure. We take an instance with an exercise to transfer all the selected Items in the
first ListBox as well as all their(selected Items) physical properties to a flexgrid. Listing
7.10 shows the code used for the implementation of this task.
Listing 7.10: Using Array of ListBoxes
1: Dim I As Integer, J As Integer, K As Integer
2: For I = lstOrganic.Lbound To lstOrganic.Ubound
3:
For J =0 To lstOrganic(I).ListCount 1
4:
If lstOrganic(I).Selected(J) =True Then
5:
K=K+1
6:
flexgrid.TextMatrix(K,I)=lstOrganic(I).List(J)
316
7:
8:
9:
10:
Endif
Next J
K=0
Next I
Listing 7.10 uses a nested control structure with line 3 as the major Loop header. I in this
Case starts from 0 to 6 which are respectively the lowest index of the ListBox List
array(Lbound) to the highest index of the ListBox List array(Ubound). Line 3 starts a
loop from 0 to the number of elements in each ListBox. Line 4 tests a condition whether
the jth item in the ith ListBox is selected or not. If it is selected, it increases k by 1 and
transfer the item which occupies this position to the kth row and ith column of the grid.
You might be wondering why k was not avoided and Line 6 written as
Flexgrid.TextMatrix(J,I) =lstOrganic(I).List(J)
The effect of the above code is that you would have gaps for elements not selected.
Figure 7.11a and 7.11b show the interfaces for these scenerio. Line 9 was used to reset k
to 0 to enable it start counting from 1 in the next column(or next ListBox)
The code in Listing 7.10 assumed that the ListBoxes are selected. The code used to select
all the ListBoxes once the first is selected is as shown in Listing 7.11
Listing 7.11: Selecting/Deselecting array of ListBoxes with a single Click
Private Sub lstOrganic_Click(Index As Integer)
1: Dim I As Integer : With lstOrganic(0)
2: For I = 1 To lstOrganic.Count - 1
3:
If .Selected(.ListIndex) = True Then
4:
lstOrganic(I).Selected(.ListIndex) = True
5:
Else
6:
lstOrganic(I).Selected(.ListIndex) = False
7:
End If
8: Next I
9: End With
10: For I = 0 To lstOrganic.Count - 1
11:
lstOrganic(I).Selected(0) = True
12: Next I
End Sub
Figure7.11a
Suppressing Gaps when
transferring Selected
Items from a
ListBox to a FlexGrid
Figure7.11b
Activating Gaps when
transferring Selected
Items from a
ListBox to a FlexGrid .
317
318
Array of Grids
Recall that in chapter two (page..) we mentioned that an array of grid is an example of a
three dimensional array. Before discussing array of grids, we should first of all ask
ourselves a question. Under what circumstances would we need array of grids. Because
you have thought of array of grids, it means that array of grids should have applications
in your world. As a simple example of array of grids we create an electronic conversion
table. In order to simplify our dscussion we make the following assumptions.
The conversion table in question has only 5 quantities(Length, mass, Time, Volume
and Pressure)
That each of these quantities have 6 units each( e,g 6 length units are inches, yards,
centimetres, feet, metres and millimetres)
That we are to interconvert from one unit to the other by multiplying by a constant
factor
That the constants are already known
Armed with the assumptions above, we can now implement the electronic conversion
table using array of grids. The following tasks are required to accomplish this:
Open the component dialog, add an instance of the msFlexGrid control to the form
From the toolbox, draw an instance of the MSFlexGrid control on the form
Set the name of the grid control to flexgrid
Copy and paste four instances of the grid control on the form
Get the conversion factors for each of the quantities and load it on the grid as shown
in Figure 7.12. Figure 7.12 is the conversion factor for Length. You should repeat
same for mass, time, density and volume.
Figure 7.12
Using Grid and Grid
array to implement
conversion problem.
This is another variant
of table look up
319
On Loading the other grids in the same way as the length factor was loaded, you can use
the code in Listing 7.12 to enjoy the electronic conversion table
Listing 7.12: Implementing Electronic conversion table using array of grids
Sub Convert()
1:
Dim X As Double, I as Integer
2:
Dim J As Integer, K as Integer
3:
K = lstQuantity.ListIndex
4:
I = lstInput.ListIndex
5:
J = lstOutput.ListIndex
6:
X = flexGrid(K).TextMatrix(I,J)
7:
lblResult.Caption = val(txtInput.Text) * X
End Sub
Notice how short the code is. This code would have been over 1000 Lines if written with
the conditional structure(i.e without array of grids). In Listing 7.12, Line 3 gets the
index of the Quantity selected, Lines 4 and 5 were used to get the indices of the input
and output unit selected respectively. Line 6 assigns the Conversion factor between the
selected input and the selected output for the quantity selected. This factor is used to
convert the Input Text to the desired output(Line 7). Test this program using the interface
of Figure Q5.10.
NOTE
In the Grid, the input units are kept horizontally while the output units are kept vertically.
For example, if the quantity selected is temperature with index of 0 and the selected input
and output units have indices of 0 and 2 respectively, then the factor to be used would be
12. Hence if Input text is 3 then the expected output would be 36.
Note also that the grids have to be kept invisible so that the job would be carried out
internally.
Array of PictureBoxes
Many persons have always wondered and argued whether the PictureBox has any other
application apart from displaying Pictures. Any programmer who engages his/herself in
this sort of argument is merely exposing his inexperience and lack of knowledge on Basic
use of default ActiveX controls. The PictureBox apart from being used to display
graphics is used as a container. it is used for Basic graphics as would be seen in chapter
11
Our interest in this section is the use of PictureBoxes as containers for a variety of
controls including other PictureBoxes. A control is said to be a container control if the
top and left of objects placed on it assume a left relative to its left. E.g of container
320
controls in Visual Basic are the PictureBox control, the frame control and SSTab control.
Figure 7.13 Shows a CommandButton on a PictureBox and the Form. The Left of
Command2 is greater than the Left of Command1 though command1 is further from the
left of the form than command2. This is because command1 assumes its left relative to
the left of the PictureBox unlike command2. This really prove that the pictureBox is a
container control.
Figure 7.13
Demonstrating Container
controls using Left Property
NOTE
Once an object is placed in container control. It can only be removed by cut and paste
operation and not by click and drag operation.
One handy application of the PictureBox control is in grouping OptionButtons together.
Another application is to change the view of the form using its visible or Left/Top
property. Figure 7.14a shows a form with the Tabstrip control on It. In the Tab strip
control, the Active Tab is Linear Equation Tabs. When the Matrices Tab is selected(i.e
becomes active) then a different view of the Form appears(Figure 7.14b). This is made
possible by array of PictureBoxes. Here the PictureBox array count is made to be equal
to the count of tabs in the TabStrip control. As a tab is selected, the corresponding
PictureBox shows with the controls drawn on it while or other PictureBoxes hide. This is
the basis of the multiple view of the Form. E.g of this behavior is found in the option
dialog of Microsoft Office applications as well as most other well meaning applications.
Figure 7.14a
321
322
Right click the Tabstrip control on the Form and select properties from the pop up
menu. The property Pages of the TabStrip control should appear as shown in figure
7.16
Figure 7.16
Property pages of the
TabStrip control. This is
used to Add Tabs,
Remove Tabs and give
Caption to Tabs among
other important uses
323
Use the property pages to insert two other Tabs and give the taps the following
captions. Unit Conversion, Base Conversion,Currency Conversion. Click OK to
effect your settings and close the dialog.
Place a PictureBox control on the Form
Size the PictureBox control to cover the TabStrip control properly.
Give the PictureBox a name of picDemo and index of 0 and Borderstyle of 0.
Design the conversion interface of Figure 1.34 . On the PictureBox.
Hide the PictureBox control by setting its Left property to 100000.
Place another PictureBox control on the form and give it a name of picDemo, index
of 1 and BorderStyle of 0
Resize the PictureBox as shown in fig
Create the number base interface on the PictureBox.
Give the PictureBox a left of 100000.
Create a third instance of picDemo and design any simple interface on it.
Place a command button at the extreme right hand side of the form as shown in
Figure 7.17.
Place the following codes in the click event of the TapStrip control.
Else
End if
Next I
End Sub
324
Array of Lines
The co-ordinate geometry of lines is slightly different from the co-ordinate geometry of
other controls. This is because the lines have the X1, X2, Y1 and Y2 properties which are
absent in all other controls. In order to manipulate each element of an array of lines using
code, we should review the X1, X2, Y1 and Y2 properties.
X1:
Abscissa of start point of line
X2:
Ordinate of the start point of line
Y1:
Abscissa of end point of line
Y2:
Ordinate of the end point.
A line can be figured to pass through the points (30,200) and (80,600) as follows
With Line1
.X1 = 30
.Y1 = 200
.X2 = 800
.Y2 = 600
End with
A line is horizontal if Y1 = Y2 and vertical if X1 = X2. Two lines are parallel if they
have equal slopes and perpendicular if slope of one is equal to the negative reciprocal of
the other. By using control array technique, you can make wonderful linear charts and
plots from it. Figure 7.18 shows a triangular chart designed with array of lines. The code
used to accomplish this is included in the CD Rom as Listing 7.13
Figure 7.18
Making charts
from Array of
Lines
325
326
Problem Set 7
Question 7.1
Write a program that determines the HCF or LCM of n numbers using controls array to
regulate the input.
Question 7.2
In problem set 4.1, Grid was used to implement the conversion problem, using array of
grids, implement a program to convert length, volume, mass, Time and Pressure using
array of grids.
Hints:All grids have to be created nad loaded with appropriate conversion Factors.
Question 7.3
a) Write a program to implement the interface shown in Figure Q7.3. The interface has
at least 30 textboxes such that only 7 can be displayed. The Vertical scroll bar helps the
user to scroll and access other textboxes. Implement this interface using array of
textboxes.
b)
Write a program which transfers all the data in the textboxes to a Grid control
resident in another Form.
327
Question 7.4
Implement the Windows Calculator using Visual Basic.
Hint: Use at least three controls array. One for the numbers, another for the operators
and the third for the functions.
Note:Because the Intrinsic command Buttons do not have the ForeColor property, you
have to use the Form object commandbuttons in order to change the Forecolor property.
The Form Object command button is part of the Form object Controls in the components
dialog.
Question 7.5
The Identification, Grade and Weight of 30 pipes were obtained using customized input
boxes and store in a grid in Form1. Form1 has among other menus an option menu with a
selection menu item under the option menu. When the Selection menu item is selected,
the dialog shown in Figure Q7.5 appears. The dialog Top(or Bottom) n pipes in
Ascending or descending order based of a specified sort key(which may be Weight,
Grade or ID No). Implement a simple program for this.
Figure Q7.5
Working with array of
Labels in a Selection program.
Question 7.6
A multiple choice quiz has 50 questions each with four possible answers of which only
one is correct. Given that a students answers is displayed in one ListBox and the correct
answers displayed in another ListBox. You are expected to
328
Figure Q7.8a
Hydrocarbon Gas Components
used in Question 7.1
329
Figure Q7.8b
Form displayinging components
selected from Figure Q7.8a
CHAPTER
8
Visual Basic for Applications
Overview of ms excel
VBA Functions
VBA Collections
VBA dialog Boxes
Macros
VBA and OLE automation
331
Most software developed today have macros which enable users to automate some
frequently performed tasks. The language used to write most of these macros is Visual
Basic for Applications (VBA). MS Excel and MS Project are the first applications that
featured Visual Basic for applications. Today, other applications like MS Word, MS
Power Point, Corel Draw, MS Access, Autocad etc. also incorporate Visual Basic for
application as their Macro language. VBA enables you use the VB familiar controls and
syntax to develop applications that can be used to enhance some features in application
For example., with VBA you can develop dialog boxes used for custom mathematical
and Engineering functions not supported or featured by an application.
In syntax, VBA is actually the same in all the applications that incoporates it. Once VBA
is mastered in one application, it is infact, very easy to use VBA in other applications.
For these reasons, we will limit our discussion to MS Excel only and urge you to extend
your knowledge and use VBA in other applications.
Overview of MS Excel
MS Excel is the most widely used spreadsheet application in the market today. It features
dialog boxes and functions that can be used to perform complex mathematical, statistical
as well as financial operations. Interaction with MS Excel is often done through the cells
in open and/or closed workbooks. Figure 8.1 shows the MS Excel window on start up.
MS Excel cells are similar to the TextMatrix in MS FlexGrid/MSHFlex Grid. The major
difference between them is that the cells of the former are editable unlike those of the
latter.
Figure 8.1
MS Excel MDI
Window showing Excel cells
A cell is the intersection of a row (labeled from 1 to 65536) and a column (labeled from
A to IV). A cell formed by the intersection of column C and row 4 is called cell C4
Instead of using addresses, the MS Excel name box permits you to give reasonable
332
names to cells. Figure 8.2 shows the MS Excel Name Box invoked by selecting names
from the Insert Menu of MS Excel.
Figure 8.2
MS Excel name box used
to give Cells or range of
cells names.
Names given to cells follow the Visual Basic/VBA variable naming rules. Infact, the
cells are thought to be physical representation of variables. For instance, you can assign
10 to a variable A3 as follows
A3 = 10
Equivalently, you can assign 10 to cell A3 by typing
= 10
in cell A3 and then press the Enter key(Return key). This means assign 10 to cell A3 (or
A3 = 10)
Just like with variables, you can express a variable C9 in terms of another variable A3
that must have been previously defined as follows:
C9 = A3 + 6
Since assignment to a cell name is implicit, you can also implement this in a cell by
typing
= A3 + 6
in cell C9. This should give you 16. (Assuming you have 10 in cell A3).
333
4212
............................................................................................................... 8.1
L
used to determine the natural frequency (Fn) of the fundamental drill string longtitudinal
mode of drill collars with length L. For 10 values of L, you can load these values from
cells A2 to A11 and then determine Fn for the first mode as follows
= 4212/A2
Subsequent results can be obtained by filling down(or selecting the output range and
pressing Ctrl + D ) or by double clicking the bottom left edge of the cell.
Programmatically, this is done using the For Next Loop as follows
For I = 1 To 10
FN(I) = 4212/L(I)
Next I
Plotting Graphs
Given the data displayed in the worksheet shown in Figure 8.3, we can make any kind of
plot with these data using the Excel chart wizard. In all, four steps are required. The steps
used in making a chart from MS Excel are enumerated below.are enumerated below:
1. Select the range containing the data and Click the chart wizard icon on the standard
ToolBar. This displays the chart wizard dialog shown in Figure 8.4
334
Figure 8.3
Excel MDI showing data
to be plotted.
2.
Select XY scatter from the chart type list and any chart sub type. Click Next> to
show the dialog needed to complete Step 2 of the four graph plotting steps(see Figure
8.5) . Here you specify the data range as well as the orientation of the series.
335
Figure 8.5
MS Excel Chart Source
Data Dialog.
3. Click Next> again to show the dialog needed to complete Step 3 of the four graph
ploting steps. See Figure 8.6.
Figure 8.6
MS Excel Chart Option
Dialog.
4.
Complete the Chart Title, X axis Title and Y axis title with appropriate titles. To
customize the plot, click the Axis, Gridlines, legend and data labels tabs and
complete the interface appropriately.
336
5.
Click Next to launch the dialog needed in the last step of the four graph plotting
steps. See Figure 8.7.
Figure 8.7
MS Excel Chart
Location Dialog.
6.
Activate the As New Sheet option to display the chart in a new chart sheet as
shown in Figure 8.8
Figure 8.8
Excel MDI showing
the Active Chart Sheet
337
After plotting the graph, you right click any of the axis and format it to your taste. For
example, to plot a Semi-Log graph, you right click the X axis and select Format Axis
from the pop up menu. This displays the dialog shown in Figure 8.9. From the scale tab
you convert the scale to log scale by placing a check mark on the Logarithmic Scale
CheckBox
Figure 8.9
Format Axis Dialog used
to format the plotted X or
Y axis
To plot on secondary axis(for cases where you have more than one series), you double
click the data series to display the Format Data Series dialog which among other
functions enables you to convert an axis to Secondary axis.
338
Figure 8.10
The MS Excel Paste
Function dialog.
The Paste Function dialog is similar to the Visual Basic object Browser. Once a function
is selected, the functions syntax is shown at the bottom of the dialog. For the sum
function selected in Figure 8.10 we see that it could be used with both range of cells,
enumerated cells and scalar values. Given the data 3, 4, 9, 6, 8 and 17 in cells A1 to A6,
you can obtain the sum by using any of the formulae
=
=
=
=
=
or by using the summation icon in the Standard Toolbar. Other functions like Average,
STDEV, MODE, MEDIAN, PERCENTILE etc are used in the same way like the sum
function .
339
X
Y
3
10
4
12
5
14
6
16
7
18
3 2 5
1 -1 0
is represented in a cells as
{2, 0,1;3,2,5;1,-1,0}
with the data in cell form, you can use spreadsheet functions to evaluate its Determinant,
Inverse, Transpose and also Multiply it with another matrix if and only if both are
conformable for multiplication. For e.g. the Inverse is obtained as
= MINVERSE({2,0,1;3,2,5;1,-1,0})
Since the results returned by MINVERSE is a two dimensional array, it is necessary to
select a 3 by 3 range before keying in the formula. Also note that for Excel to return a
matrix or a vector, you have to press Ctrl + Shift + Enter on completion.
When working with data in a range, it is better to use names instead of hard coding a list
of data into formulae. By giving the range A1:B3, the name, MatrixA you can also
implement the Matrix Inverse as
= MINVERSE(MatrixA)
Having being able to evaluate MINVERSE using spread sheet techniques, you can easily
solve a Simultaneous Linear Equation (SLE) of the form
x1 + 2x2 + x3 + 4x4 = 13
340
2
where A =
4
- 3
2 1 4
x1
13
0 4 3
x
28
B = and x = 2
2 2 1
x
20
3
1 3 2
6
x4
To evaluate the root, use the MINVERSE function to evaluate the matrix inverse and
then pre-multiply the result obtained by the answer vector B using the MMULT
function.
VBA Functions
Since MS Excel uses VBA as its macro language, it should come to our mind that
functions written in Excel should be similar to functions written with Visual Basic. By
careful inspection, this similarity tends to equality and hence we can make the following
pronouncement: Functions written with Visual Basic have exactly the same syntax as
functions written in Excel using VBA. We consider how to write functions by
implementing the Euclids HCF algorithm(Listing 6.13) with the following steps
Select Macros from the Macros Sub Menu. The Macro dialog should appear as
shown in Figure 8.11.
341
Figure 8.11
MS Excel Macro dialog
used to Create/Edit
functions, sub procedure
and macros.
VBA creates the Sub procedures Header and footer for the HCF function without
arguments.
Replace the sub with function and key in the code shown in Listing 8.1(see Listing
6.13)
as
Integer,
ByVal
As
Open the function dialog through the Insert menu and observe that your function is
now part of the Excels custom functions(see Figure 8.12). The implication is that
you can use the HCF function in the same way you use Excels functions.
342
Figure 8.12
The Excel Paste Function
Dialog showing the newly
written HCF function
in cell C5 and press Enter. It should give you 15 being the HCF of 50 and 45. Test the
function with other values and confirm that it is reliable.
Repeat the same procedure and test the LCM function(see Listing 5.). Note your
observation. It should be well behaved.
343
X = Application.Median (3,7,4,9,6,8)
NOTE
VBAs square root function is SQR while Excels square root function is SQRT.
VBA Collections
In addition to the Visual Basic collection, Excel VBA has other collections that are used
to manipulate Excel applications. These collections include but not limited to the
following; the workbook collection, the worksheet collection, the range collection etc.
The VBA WorkBooks collection comprises of all the open workbooks in an application
while the worksheets collection consist of all the worksheets in a workbook. With the
workbooks collection , the worksheets collection and the range object, you can write
VBA code to display the value 5 in cell A7 as follows:
Application.WorkBooks(Book1).WorkSheet(Sheet1).Range(A
7).Value = 5
344
The statement above was written with the full syntax of the Range object. Most times, the
application object is omitted. This simplifies the syntax to
WorkBooks(Book1).WorkSheet(Sheet1).Range(A7).Value
5
For VBA codes written in the active WorkBook comprising of only one sheet, we write
the code as
Range(A7).Value = 5
Having understood the hierarchy of VBA collection, we can use the For Each Loop as
follows.
For Each WorkBook In
.
.
.
Next WorkBook
WorkBook
Or with worksheet as
For Each WorkSheet in WorkSheets
.
.
.
Next WorkSheet
For the range collection use it as follows
For Each Item
.
.
.
Next Item
in Range
The Range collection is very important when dealing with functions because most of the
work sheet functions incorporate range as arguments and hence makes it very interesting.
When using functions, the TypeName function is used to determine the argument type
and necessary steps taken when its a Range. Before considering how this is used in
function, we consider some properties and methods of the range object.
345
346
End Function
This is a more fail safe version of the SumRange function. With the code above, if the
argument is not a range object, then VBA returns Null (default type for Variant Variable).
This makes sense rather than returning zero (if function was made to return a double).
With a knowledge of this, we can make our HCF function accept indefinite argument
which may be cell values or range or combination of cells and ranges.
Offset Method
FormulaR1C1
Cells
Selection Object
The selection object is somewhat related to the range object and is most times used
interchangeably. A selection in a worksheet is a range of cells. With a good
understanding of selection and range you can read and write to selections. VBA provides
347
a variety of methods that can be used to read and write to selection. Some of these
include
Offset method
Range method
Cells method
FormulaR1C1
Before discussing how to read or write to selection, you need to understand the Cell(or
Activecell) properties/methods
Used as a matrix
When used as a matrix, the first cell in the selection is Cells(1,1) and the cell to the right
of the first cell is cells(1,2) and the cell below the first cell is cells (2,1). You can use the
syntax of the cells property to read from a selection and store in a two dimensional array
as shown in Listing 8.4.
Listing 8.4: Reading from a Selection into a two dimensional array
1: Dim nRows As Integer, nCols As Integer
2: Dim A() As Variant, I As Integer, J as Integer
3: nRows = Selection.Rows.Count
4: nCols = Selection.Columns.Count
5: Redim A(1 To nRows, 1 To nCols) As Variant
6: For I = 1 to nRows
7:
For J = 1 To nCols
8:
A(I,J) = ActiveCell(I,J)
9:
Next J
10: Next I
In Listing 8.4, the number of rows in the selected range of cells is assigned to nRows in
Line 3 while Line 4 assigns the number of columns in the selected range of the active
worksheet to nCols. Line 5 redeclares the dynamic array using nCols and nRows as upper
bound of the two dimensional array. Lines 6 to 10 contain the nested For Next Loop
used to transfer data from each cell of the selected range to the two-dimensional array.
348
The cells property can only be used with the worksheet offset to read from any Row and
Column in any sheet as
Worksheets (sheets).Cells(2,4) = VB
Or inside a selection as
Activecell.Cells(14,5)
= Uniport
Or simply as
ActiveCell(14,5) = Uniport
NOTE
When working with selection, you may use the ActiveCell property directly instead of
invoking its cells property.
Used as a vector
The matrix form of the cells method is similar to the TextMatrix of Visual Basic grid
controls. Also, the vector form of the cells method is similar to the TextArray property of
the grid control. The choice of the syntax used depends on the manner of storage. If the
data are retrieved and stored in a one dimensional array (vector) the vector form should
be used otherwise, the matrix form should be used.
The cells method can be used as follows with a default object
Cells(6) = 7
Or relative to the Activecell as
ActiveCell.cells (5) = 27
You can use this syntax to read/write directly to (or from) a defined range as
Range (B10:F15).Cells(7) = 24
NOTE
Using the vector syntax of the cells method is only desirable with range because it refers
to the nth cell from the beginning of the range counting row wise.
349
For the worksheet, you determine the number of columns before you can determine the
actual cell being referred to. Since Range (B10:F15) has five columns, it implies that
cells(7) should be in the second Row and second column of the Range which is C11.
Also, cells(11) of Range (B10.F15) is B12. (see Chapter four for differences between
the TextMatrix and TextArray property)
Used as scalar
The third syntax of the cells method is used to collectively process a range. E.g.
ActiveCell.Cells.FillColour=xlBlue
Or
ActiveCell.Cells.ClearContents
This is similar to the Text property of the MS/MSH FlexGrid.
Offset Method
One of the advantages of using the offset method over cells method is that the offset
method can be used to read/write data to cells outside the reference range.
The syntax of the offset method is
Object.Offset(rowOffset,ColumnOffset).
Here, the indices RowOffset, ColumnOffset can take both negative and positive values
unlike the cells method. Consider the statements
ActiveCell.Cells(2,2) = 27
ActiveCell.Offset(2,2) = 27
Assuming the selection covers the range B3:D10. Then cells (2,2) refer to the Address
C4 while offset (2,2) refers to the Address D5. This will become clearer when you
remember that the first cell in the selection has an offset of offset (0,0). Therefore offset
(2,2) means the third row and the third column, hence third row from B3 is Row 5 while
third column from B3 is column D which makes offset (2,2) = D5.
Having understood how to read and write to selection, we can now write subroutines that
can be used to solve a simultaneous linear equation in N variables.
As a second application, we consider the behaviour of the sum function: as you select a
range, and click the summation icon in the standard toolbar, it gives you the sum
350
automatically. Wont you be happy filling n Rows and N + 1 columns with matrix
coefficient and solution vector and trigger an event to display the roots. Of course this
will gladden you because it makes you feel accomplished!. The implementation of this is
left as an Exercise.
To add UserForm(the Form is called UserForm in VBA), Select UserForm from the VBA
Insert Menu or from the VBA standard Toolbar. The Resulting interface should be as
shown in Figure 8.14
351
Figure 8.14
VBA
integrated
Development
Environment with user
form and ToolBox
window
As with Visual Basic, you activate the VBA properties window, ToolBox window or
Project Explorer by selecting properties window, ToolBox or Project Explorer from the
VBA View menu. Drawing controls on the form is done exactly as it is done with Visual
Basic. The Form module and Event procedures are created exactly as they are done in a
Standard Exe Visual Basic application. Observe that the VBA Project Explorer and
ToolBox have some features that seems different from those of Visual Basic. First the
alignment of the Project Explorer/properties is left by default instead of right. Also the
project Explorer contains some unfamiliar objects. This is OK, these seeming unfamiliar
objects are actually the worksheet objects. These objects(or components) are irremovable.
The UserForm and modules added to the project appear under this worksheet objects.
The VBA ToolBox window has fewer controls than the Visual Basic ToolBox. Figure
8.14 shows a well annotated VBA ToolBox consisting of the VBA standard controls
NOTE
VBA controls have the accelerator key property, which enable you to add accelerated key
to the Caption of your controls unlike in Visual Basic where the ampersand is used. Note
that the VBA controls are like the Form Object controls used for the Calculator Design in
Problem Set 7.4
352
Figure 8.14
VBA ToolBox window
showing Standard controls
Observe that some controls not found by default in the Visual Basic ToolBox are default
controls in the VBA ToolBox. Other ActiveX controls can also be added in to the
ToolBox from the VBA component dialog(you get the component dialog by selecting
AddControls from the Tools menu) . This makes VBA dialog driven programs exactly
like the Visual Basic Standard Exe programs in terms of interface outlook. We
demostrate how VBA programs work with a few examples.
Example Programs
Program #1
This example uses the interface shown in Figure 8.15 to find the final velocity using
conventional equations of motion. The result from the program is displayed on an output
label and also sent to the ActiveCell of the active worksheet.
Figure 8.15
Simple Input output dialog
created
with
VBA
353
Listing 8.5: VBA code used to Drive the interface of figure 8.15
Option Explicit
Dim V As Double
Private Sub UserForm_Initialize()
4: Me.txtInitialVelocity.Text = ActiveCell.Offset(0, 0)
5: Me.txtAcceleration.Text = ActiveCell.Offset(0, 1)
6: Me.txtTime.Text = ActiveCell.Offset(0, 2)
End Sub
Private Sub cmdExecute_Click()
9:
Dim U As Double
10:
Dim A As Double, T As Double
11:
U = txtInitialVelocity.Text
12:
A = txtAcceleration.Text
13:
T = txtTime.Text
14:
V = U + A * T
15:
lblFinalVelocity.Caption = V & " Seconds"
End Sub
Private Sub cmdSend_Click()
18: ActiveCell.Value = V & " Seconds"
End Sub
Private Sub cmdClose_Click()
21: End
End Sub
Listing 8.5 is a simple VBA program written to enable users interact with VBA controls.
Line 1 is the Option Explicit statement used to enforce variable declaration. Line 2
declares a module level variable V. This is important because V is to be shared by two
procedures. Lines 3 and 7 are the header and footer of the userform initialize event. This
is the event used instead of the Load event because the VBA userform does not have a
load event. The aim of the code in Lines 4,5 and 6 are used to initialize the TextBoxes
with data entered in the activecell and two other cells to the right of the activecell. With
the statements in Lines 4 to 6 , once the program is run, it initializes the TextBoxes with
default values. Lines 9 to 12 is the main code used to calculate and display the final
velocity on the output label. Line 18 sends results to the ActiveForm while Line 21
unloads the application.
354
Program #2
This example uses the interface shown in Figure 8.16 to write a program that accepts
functions at runtime in a TextBox and displays results for a range of values of x in a
worksheet.
Figure 8.16
Evaluating functions at runtime
using the MS Excel application
Evaluate methods with VBA
controls.
355
The high point of Listing 8.6 is the MS Excel Application Evaluate method used to
evaluate a function entered in a TextBox. The Function is accepted and stored as a
string(Line 6). Lines 7,8 and 9 accept the Xvalues(initial,final and increment). Line 11
has a For Next Loop used to generate all the values of X. Line 12 used the VB/VBA
replace function to replace "x" in string S with the value of " I". The last parameter in the
string was used to make the function case insensitive(see Chapter 5). The resulting
replaced function is now sent as a parameter to the Evaluate method. The result of the
evaluation is assigned to y which is then displayed in the worksheet( horizontally or
vertically depending on the state of the display CheckBox) via the offset method of the
Activecell property. The loop is then continued in Line 20 until all the values of I have
been considered.
Macros
One of the easiest ways that beginners can understand VBA is by recording macros
using the macro recorder command in the Macro submenu of the Tools Menu. The
Macro Recorder translates keyboard and mouse actions into VBA Code. When these
codes are fired, the actions performed by the user are re-produced. This is more or less
like a playback.
An example will help us understand how macros work. Start the macro recorder as
follows:
Select record macros submenu item from macros menu item of the Tools Menu
Figure 8.17
Excel Record Macro dialog used
to assign macros name,
shortcutkey and Scope.
356
Assign any un- assigned short cut key say Ctrl + /(slash)
Click OK. Any action performed from this time Onward is being recorded. Your
Excel MDI should be as shown in Figure 8.18 at this time.
Figure 8.18
Microsoft Excel MDI
with the macro
recorder in progress
Select the Macros Submenu Item from the Macros MenuItem of the Tools menu. The
Macro dialog appears as shown in Figure 8.19.
Figure 8.19
Excel Macro Dialog.
357
Select the name of the Macros(TestMacro) from the List and click Edit, the code
generated by the Macro recorder is as shown in Listing 8.7(Its presented here with
line numbers for the purpose of analysis)
FormulaR1C1 is like the offset method used in reading and writing to a selection.
FormulaRIC1 means write to the Activecell. FormulaR1C2 means write to the cell next
and to the right of the active cell while FormulaR2C1 write to the cell immediately below
the active cell. If m and n are Integers greater than 0, FormulaRmCn means the cell at
m 1 rows from the ActiveCell and n 1 columns from the ActiveCell.
358
359
Excel calls the x-axis category axis(xlCategory) and the y-axis the value axis (xlValue).
Since there could be a primary and secondary x and y-axis, each of these are well
differentiated.
To change a scale to log scale you need to add the code shown in Listing 8.9 to the code
in Listing 8.8.
Listing 8.9: Code segment used to change the x-axis scale to Logarithmic
14: With ActiveChart.Axes(xlCategory)
15:
.MinimumScale = 0.1
16:
.MaximumScaleIsAuto = True
17:
.MinorUnitIsAuto = True
18:
.MajorUnitIsAuto = True
19:
.Crosses = xlAutomatic
20:
.ReversePlotOrder = False
21:
.ScaleType = xlLogarithmic
22:End With
360
The code is obviously OK. Line 14 opens the ActiveChart Axes object With block with
xlCategory as argument meaning that our interest is on the x-axis. When our interest is
on the y-axis we have to replace the xlCategory with xlValue
Line 15 sets the MinimumScale to 0.1. You can set this to any positive or negative
exponent of 10( i.e 0.01,0.001,0.0001,1,10,100, etc). Dont accept the default because it
could be zero or negative and negative values can not be plotted on logarithmic scale.
Line 21 sets the scale to xlLogarithmic(i.e log scale), the default is xlLinear. In Line 16,
VBA asks Excel to assume an authomatic Maximum scale. If this was not assumed Line
16 would have been written as
. MaximumScale = n
where n is the specified maximum scale value which should always be a logarithmic
multiple of 10. This discussion also applies to Lines 17 to 19.
Having discussed the graph macro, we now write a simple VBA application using
dialogBoxes to demostrate the importance of stored macros. The interface needed for this
application is as shown in Figure 8.19. The code needed to drive this interface is as
shown in Listing 8.10
Figure 8.19
Plotting graph with
VBA and Macro.
361
362
35:.Axes(xlCategory,xlPrimary).AxisTitle.Characters.Text="x
"
36: .Axes(xlValue, xlPrimary).HasTitle = True
37:
.Axes(xlValue,xlPrimary).AxisTitle.Characters.Text
="y"
38: End With
End Sub
The high points of Listing 8.10 are the lines used to transfer the data in the MS Flexgrid
to Excel worksheet.(Lines 3 to 7). Line 8 sets the data range to be plotted which is then
passed as parameter to the xygraphmacro in Line 9. Lines 16 to 22 invoke the InputBox
function on double clicking the FlexGrid control. This is the technique used to enter data
to be ploted into the cells of the flexgrid. In the graph plotting macro, the range in Line
29 used the DataRange parameter thus making the macro very versatile. To make your
macro capable of handling x and y axes title, add two other parameters to the
XYGraphMacro in Line 25 and replace the x and y (shown in boldface) with these
parameters.
NOTE
The Log scale was not accounted for in Listing 8.10. To account for this you need to call
two other sub procedures for the x and y-axes scales. Try this as an exrcise, you will
surely enjoy it.
363
Figure 8.20.
Visual Basic
Reference
Dialog.
NOTE
The Excel object exposed by your system may not be Excel 9.0. You find Excel 9.0 if
you have Microsoft Excel 2000 . Microsoft Excel XP exposes Excel 10.0 while Excel 97
exposes Excel 8.0 object. No matter your object, you still have the same effect.
After creating references to Excel object, you can now declare an Excel object that has
properties and methods that will enable you communicate with Excel from within your
Visual Basic application. To open an Excel workbook with 1 one sheet you invoke the
code shown in Listing 8.11
Listing 8.11: Opening Excel through Automation
' References to the Excel object must be set before using
'this code
1: Dim objExcel As Excel.Application
2: Set objExcel = New Excel.Application
3: objExcel.Workbooks.Add
4: objExcel.SheetsInNewWorkbook = 1
5: objExcel.Visible = True
6: set objExcel = Nothing
on placing the code above in an event procedure, we observe that Excel is automatically
opened. Line 1 of Listing 8.11 declares an Excel object variable while Line 2 sets this
364
variable with a new instance of the Excel object. Line 3 adds a new workbook to the
excel object. Line 4 sets the number of sheets in the new Workbook to 1. You can set
this to any number as far as your memory can handle it. Line 5 sets the Visible property
of the Excel object to True. This enables you to set the newly created excel object. Line 6
sets the excel object to nothing so that memory "consumed" by the object is released.
After creating an instance of Excel and adding a workbook and a worksheet, you can use
your VBA knowledge to interact with Excel spreadsheet the same way you interact with
Excel VBA. For example to write the text How are we to cell B3 you add the code
objExcel.Cells(3,2).Value = "How are we"
between Lines 4 and 5 of Listing 8.11.
To transfer the whole content of a ListBox to a newly created Excel application you add
the code
For I = 0 To list1.ListCount-1
ObjExcel.Cells(I+1,1) = List1.List(i)
Next I
between Lines 4 and 5 of Listing 8.11. Apart from just exchanging data in Excel, you can
also write codes to perform such complex operation as plotting any form of graph. We
test this with a code used to plot a graph from Visual Basic using the interface shown in
Figure 8.21
Figure 8.21
Sending data to be Plotted to
Excel.
365
366
41:
42:
43:
44
End
Sub
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
End
With txtydata(I - 1)
txtydata(I).Top = txtydata(I - 1).Top + .Height _
+ 100
End With
Next I
Sub
XYGraphMacro(DataRange As String)
With objExcel
.Charts.Add
.ActiveChart.ChartType = xlXYScatterSmooth
.ActiveChart.SetSourceData Source:= _
.Sheets("Sheet1").Range(Datarange), PlotBy:= _
xlColumns
.ActiveChart.Location Where:=xlLocationAsNewSheet
End With
With objExcel.ActiveChart
.HasTitle = True
.ChartTitle.Characters.Text = _
"Correlating Y and X"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory,xlPrimary).AxisTitle.Characters. _
Text = "x"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text _
= "y"
End With
Sub
Listing 8.12 seems to be too long!. However, if we consider each of the event
procedures, we realize that it is OK and familiar . Line 1 declares an Excel object
module level variable (objExcel). Lines 2 to 10 are the familiar code used to create
Excel, Add workbook and WorkSheets. Line 8 calls the Sub procedure responsible for
sending data to Excel.. Lines 12 to 20 send data to Excel and call the familiar
xyGraphMacro. The array of TextBoxes were created between Lines 26 and 45 but
called in Lines 23 and 24. the Graph plotting macro starts from Line 46. This code is
similar to the code in the Listing 8.10. The only difference is that Excel object is used to
access the ActiveChart object(Line 47 and Line 54). The rest of the code is same as that
of Listing 8.10
367
Figure 8.22
Visual Basic Form showing
OLE control.
Figure 8.23
Visual Basic OLE
Insert Object.
368
Figure 8.24
Embedding Plotted
graph in a Visual
Basic Form using
OLE control
Listing 8.13. Creating and embedding an Excel Object Inside a Visual Basic Application
Dim objExcel As Excel.Application
Private Sub cmdPlot_Click()
3: ' References to the Excel object must be set before
4: 'using this code
5: Set objExcel = New Excel.Application
6: objExcel.Workbooks.Add
7: objExcel.SheetsInNewWorkbook = 1
8: Call TransferDataToExcel
9: objExcel.Visible = True
End Sub
Private Sub TransferDataToExcel()
12: Dim I As Integer, Datarange As String
13: objExcel.Cells(1, 1) = "X-Values"
14: objExcel.Cells(1, 2) = "Y-Values"
15: For I = txtxData.LBound To txtxData.UBound
16:
objExcel.Cells(I + 2, 1) = txtxData(I).Text
369
17:
objExcel.Cells(I + 2, 2) = txtydata(I).Text
18: Next I
19: Datarange = "A1:B" & CStr(I)
20: Call XYGraphMacro(Datarange)
End Sub
Private Sub Form_Load()
23:
CreateXDataTextBoxes(6)
24:
CreateYDataTextBoxes(6)
End Sub
Private Sub CreatexDataTextBoxes(ByVal N)
27:
Dim I As Integer, K As Integer
28:
For I = 1 To N
29:
Load txtxData(I)
30:
txtxData(I).Visible = True
31:
With txtxData(I - 1)
32:
txtxData(I).Top = txtxData(I - 1).Top + .Height _
+ 100
33:
End With
34:
Next I
End Sub
Private Sub CreateyDataTextBoxes(ByVal N)
37: Dim I As Integer
38: For I = 1 To N
39:
Load txtydata(I)
40:
txtydata(I).Visible = True
41:
With txtydata(I - 1)
42:
txtydata(I).Top = txtydata(I - 1).Top + .Height _
+ 100
43:
End With
44
Next I
End Sub
Sub XYGraphMacro(DataRange As String)
47:
With objExcel
48:
.Charts.Add
49:
.ActiveChart.ChartType = xlXYScatterSmooth
50:
.ActiveChart.SetSourceData Source:= _
51:
.Sheets("Sheet1").Range(Datarange), PlotBy:= _
xlColumns
52:
.ActiveChart.Location Where:=xlLocationAsNewSheet
53:
End With
54:
With objExcel.ActiveChart
55:
.HasTitle = True
56:
.ChartTitle.Characters.Text = _
370
57:
58:
59:
60:
61:
62:
63:
64:
End
The code in listing 8.13. is exactly the same code used in Listing 8.12 . The only
difference is that Three lines of code were added. Lines 62 Saves the Ploted graph in a
file. Line 63 embeds the newly created object and Line 64 sets the size mode to 1 to
ensure that the size of the graph exactly fits the OLE container.
Problem Set 8
Question 8.1
The Euclidean HCF function b defined as
HCF(A,B) =
B ,
A mod
B = 0
HCF(B, A mod B)
A mod
B 0
LCM ( A, B) =
A B
HCF ( A, B)
371
a11 x1
a21 x2
a31 x1
.
.
.
an1 x1
+
+
+
.
.
.
+
a12 x2
a22 x2
a32 x2
.
.
.
an 2 x2
+
+
+
.
.
.
+
a13 x3
a23 x3
a33 x3
.
.
.
an3 x3
+
+
+
.
.
.
+
...
...
...
.
.
.
...
+
+
+
.
.
.
+
a1n xn
a2 n xn
a3n xn
.
.
.
ann
= a1, n +1
= a2, n +1
= a3, n +1
.
.
.
.
.
.
= an , n + a
Write a VBA spreadsheet function which accept an N by N+1 matrix coefficient and
answer vector and return an array of the roots.
Question 8.4
Repeat Exercise 8.3 using VBA functions and dialogs instead of spread sheets. Your
program should be able to communicate with the spreadsheet.
Question 8.5
The dialog shown in Figure Q8.5 is used to solve a Linear Programming problem. Using
MS Excel optimization tool(Solver), implement the interface shown in Figure Q8.5. The
output from the optimization should be displayed in another Form. To remove a
constraint from the List Box, your user should hold down Ctrl +Shift and Click the
constraint. To Edit a constraint, the user should double click the contraint so that it
appears on the constraint TextBox. The Edited constraint is added to the ListBox by
holding down Shift or Ctrl while the Add Button is Clicked. Add Button ordinary
without any of the Shift keys adds the constraint as a new constraint.
a)
Implement the interface shown in Figure Q8.5 using VBA
b)
Implement the interface shown in Figure Q8.5 using Visual Basic
372
Figure Q8.5
Linear programming
problem.
Question 8.6
X and Y data points are obtained from a researcher and displayed in adjacent columns of
a spread sheet. Using a VBA dialog, write a program which displays the relationship
between X and Y in a chart sheet. Your dialog should trigger the plot, display the
cofficient of multiple determination and the value of the F and T test parameters at
adjustable level of significance. Implement this in Visual Basic and Excel.
Question 8.7
Using OLE control, design and implement a Visual Basic program which accepts a
function in a TextBox and graph the function for specified range of values of the
independent variable(s).
CHAPTER
9
Numerical Applications
Evaluations of functions at run time
Non Linear Equations
Numerical Differentiation
Numerical Integration
Polynomial Interpolation
Introduction to Matrix Algebra
Problem Set
374
string
Numerical Applications
375
376
Figure 9.1
Accepting and Evaluating
Function at
Runtime
377
Numerical Applications
NOTE
Note
One of the limitations of this method is that you or your user must have a copy of Excel
before this technique can be applied. Also, because of the time it takes to open Excel,
this method is rather slow. You can improve on speed with higher system configuration.
The limitation of speed is not quite a problem if you realize that you have the whole
Excel function at your disposal. To keep your users informed, use the progress bar
control to specify the percentage completion.
string
Cos(x) LOG(x) + x
378
Figure 9.2
Controls component
Showing the Microsoft Script control
On clicking OK, the Script Control is added to the toolbox. Draw an instance of it on the
form to enable you reference it in code.
NOTE
Like the Timer Control, the Script Control is invisible at run time
With an instance of the Microsoft Script Control on the form, Listing 9.1 takes the form
shown in Listing 9.2 written with the script control instead of the Excel application
object.
Listing 9.2:Evaluating function at run time using ScriptControl
Private Sub cmdExecute_Click()
1:
Draw an instance of the script control on the form
2:
Dim x As Double
3:
Dim fx As String, y As Double
4:
x = txtxvalue.Text
5:
fx = txtfunction.Text
6:
fx = Replace(fx, "x", x)
7:
y = ScriptControl1.Eval(fx)
8:
lblOutput.Caption = y
End Sub
Numerical Applications
379
Notice how short and simple this technique is. You can also replace the statement in
boldface with the statement
y = ScriptControl1.Executestatement x = & x
Both perform the same function, to replace the variable x with its value x
The limitation of the Script control is that it uses Visual Basic functions which are
limited in number. For you to enjoy the utility of the Script control, you have to create
user-defined functions not provided by Visual Basic. See Chapter 6 and Appendix C
NOTE
When replacing X in the given string, be very careful because the X in the EXP function
might equally be replaced. You need to customize the replace function to be able to
handle this problem.
380
Bisection method
Regula Falsi(or False Position) method.
Having being able to write codes that will accept functions at runtime, we can easily
write codes to implement a solution for non-linear problems.
Consider the problem
F(x) = Sin(x) 2 x
With a specified value of initial guess, the Newton Raphson method can be used to find
an approximate root to the problem using the following relationship
xi +1 = xi
f ( xi )
f ' ( xi )
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.1
The problem above shows that we need two functions f(x) and f(x) ( or fp(x)) where
f(x) is the supplied function and fp(x) is the derivative of the function. Usually, in the
Newton Raphson method, the initial guess is provided which is recursively used to
generate other values until the difference between the ith and the ith + 1 iterates satisfy the
tolerance.
NOTE
In iterative problems, the tolerance is the error limit beyond which an iterate can not be
accepted as a root to an iterative problem. The error can simply be calculated as
Error = |xi xi-1| If this Error is greater than the specified tolerance, then iteration has
not converged and hence has to be repeated until error satisfies tolerance OR number of
iterations reaches a specified Upper Bound.
A simple Visual Basic Function for implementation of the Newton Raphson method is
given in Listing 9.3.
Listing 9.3: Subroutine for the implementation of the Newton Raphson method
Sub NewRaph(ByVal XA As Double,ByVal Tol As Double,ByVal _
Max As Double, Status As Boolean,Root As Variant)
1: Dim I As Integer,Error As Double1,X() As Double
2: ReDim X(i) As Double: X(0) = XA
3: Do
4:
i=i+1 : Redim Preserve X(i) As Double
5:
x(i) =x(I-1) F(x(I-1))/FP(x(I-1))
6:
Error = abs(x(i) x(I-1))
7: Loop Until Error < Tol OR i > Max
8: IF Error < Tol Then
381
Numerical Applications
9:
Root =
10:
Status
11: Else
12:
Root =
13:
Status
14: End IF
End Sub
X(I)
=True
No convergence
= False
The initial guess, tolerance and maximum iterations were passed as parameters to the
subroutine. The initial guess was specified before the header of the Do Loop. The Post
check form of the Do loop was used so that atleast one iteration can be performed
before checking for error at the footer of the loop structure (Line 6). The Loop iteratively
evaluates x(i) until the condition stated at the bottom of the loop is satisfied. Line 8 tests
a condition to ascertain what condition terminated the loop. Lines 9 and 10 are evaluated
if error is less than tolerance. Status is set to True signifying that iteration converged.
Lines 12 and 13 are evaluated if maximum number of iterations is exceeded. Here a
message is assigned to the root parameter and status is set to False signifying that
iteration did not converge.
When writing an executable program for the Newton Raphson problem as well as other
iterative problems, we use dynamic array to store the ith iterates because the number of
times this loop executes is always unknown until convergence. This was done in line 4.
The interface in Figure 9.3 is used to completely implement the Newton-Raphson
Technique in Visual Basic. This interface was driven with the code in Listing 9.4 which
is an event procedure version of Listing 9.3
Listing 9.4 :Implementation of Newton Raphson problem
Private Sub cmdExecute_Click()
1: Dim I As Integer, Error As Variant
2: Dim x() As Double
3: Dim XA As Double, Tol As Double, Max As Double
4: XA = txtGuess.Text
5: Tol = txtTolerance.Text
6: Max = Me.txtMaxIteration.Text
7: ReDim x(I) As Double
8: x(0) = XA
9: With Me.FlexGrid1
10: Do
11:
.TextMatrix(I + 1, 0) = I
12:
.TextMatrix(I + 1, 1) = Format(x(I), "#.00000")
13:
.TextMatrix(I + 1, 2) = Format(Error, "#.00000")
382
14:
15:
16:
17:
18:
19:
20:
21:
22:
I = I + 1
ReDim Preserve x(I) As Double
x(I) = x(I - 1) - f(x(I - 1)) / fp(x(I - 1))
Error = Abs(x(I) - x(I - 1))
Loop While (Error - Tol > 0) And I < Max
If (Error - Tol) < 0 Then
StatusBar1.Panels(1).Text = "Iteration Converged"
Else
StatusBar1.Panels(1).Text="No Convergence after " & _
CStr(Max) & " iterations "
23: End If
24: End With
End Sub
Function f(x) As Double
27:
ScriptControl1.ExecuteStatement "x = " & x
28:
f = ScriptControl1.Eval(txtFunction.Text)
End Function
Function fp(x) As Double
31:
With ScriptControl1
32:
.ExecuteStatement "X = " & x
33:
fp = .Eval(txtDerivative.Text)
34:
End With
End Function
Private Sub Form_Load()
37: With FlexGrid1
38:
.TextMatrix(0, 0) = "i"
39:
.TextMatrix(0, 1) = "X value"
40:
.TextMatrix(0, 2) = "Error"
41: End With
End Sub
Private Sub cmdClear_Click()
44: FlexGrid1.Clear
45: Call Form_Load
End Sub
Private Sub cmdClose_Click()
46: End
End Sub
Numerical Applications
383
Figure 9.3
Implementing the
Newton Raphson
problem using a
Visual Basic form.
Listing 9.4 is similar to Listing 9.3. The parameters XA, Tol and Max were passed to the
subroutine ByVal in Listing 9.3. However, in Listing 9.4 three text boxes were used to
accept these parameters. The other textboxes were used to accept the function and its
derivative which were evaluated using the scripting function in Lines 27 - 28 and Lines
31 to 34 respectively. Lines 11 to 13 are used to assign the values of I, X(i) and Error to
the FlexGrid. The Rest of the code is similar to the code in Listing 9.3. The Form Load
event was used to write to the header of the grid(Lines 37 to 41) while the cmdClear
event procedure is used to clear the grid and then call the Form Load to rewrite to the
header of the grid.
384
Numerical Differentiation
The Newton -Raphson technique implemented in the previous section required the use of
derivative which was obtained manually. This contradicts an important principle in
software engineering; secondary input should be calculated instead of being read. If the
Derivative of the function were known, the Newton Raphson technique should have been
very welcoming in roots finding. Formulas used to obtain numerical derivatives of a
function are derived from the Taylor series. The Taylor series representation of the
function f(x) is given by
f(x+h) = f(x) + hf(x) +
h 2f(x)
h 3f' ' ' (x)
+
+ ...
2!
3!
f ' ( x) =
f ( x + h) f ( x )
-.......................................................................................... - 9.2
h
with optimal(or small) values of the step size ,h; derivatives obtained from Equation 9.2
approximates the actual derivative of f(x). Equation 9.2 is called the forward difference
approximation. You can derive the backward difference and central difference
approximation in much the same way. This should give
f ' ( x) =
f ( x) f ( x h)
........................................................................................... 9.3
h
f ' ( x) =
f ( x + h) f ( x h )
....................................................................................
2h
9.4
Analytically, the central difference approximation is more or less like the average of the
backward and forward difference. It has a better precision than the Forward and
Backward difference.
Figure 9.4 was created to visually explain the difference between the three methods in
terms of accuracy, The code in Listing 9.5 is used to drive the interface
Numerical Applications
Figure 9.5
Implementing numerical
Differentiation
385
386
End Function
Function fp_b(x) As Double
21:
Dim h As Double
22:
h = 0.001 'Using backward difference of order h*h
23:
fp_b = (f(x) - f(x - h)) / h
End Function
Function fp_f(x) As Double
24:
Dim h As Double
25:
h = 0.001 'Using forward difference of order h*h
26:
fp = (f(x + h) - f(x)) / h
End Function
Observe that the step size used is h = 0.001. This is OK for this problem and most other
problems. In practice, it is advisable that you use formula to determine the optimum step
size for any problem since the function is known. Check literature on how to determine
the optimum step size for numerical differentiation problems.
x
2.1
2.2
2.3
2.4
2.5
2.6
2.7
f(x)
0.8632
0.8085
0.7457
0.6755
0.5985
0.5155
0.4274
The difference method discussed earlier still applies here and gives a better result since
the step size is accurately known. Using central difference, the derivative at x = 2.5 is
obtained as
F(2.5) =(F(2.5 + h) F(2.5 h))/(2*h)
Numerical Applications
387
From the table, it is clear that h is 0.1, therefore the derivative using central difference is
obtained as
f(2.5) =(f(2.7) f(2.3))/(2 * 0.1)
this should give -1.5916
Though this looks simple, however, the problem with it is that you have to use the
method of Binary or Linear search to locate the value of the function in the table. The
step is easily obtained by the absolute value of the difference between two consecutive x
values. This discussion is illustrated programmatically using Figure 9.5a and 9.5b and
Listing 9.6
Figure 9.5 a
Evaluating numerical
derivatives of discrete
data points with data
loaded using control
array in Figure 9.5 b.
Figure 9.5 b
Form used to Load
data to be
differentiated.
388
Numerical Applications
389
Numerical Integration
When analytical solutions to integration problems seem difficult or not possible,
numerical solutions are always sought for. Numerical integration is seen as the problem
of evaluating the area under a curve. Consider the function represented by the curve in
Figure 9.6. The area under the curve can be obtained by dividing the curve into
n(trapeziums) such that this area is approximately equal to the sum of areas of the
n(trapeziums) See Figure 9.7.
390
Figure 9.6
Problem of evaluating Area
under a curve as an indirect method of
Integrating the function
Represented by that curve
This method of approximating the area under a curve by sum of area of trapeziums is
called the Trapezoidal rule. The Integral of a function using the trapezoidal rule is given
by
I=
n 1
h
Where n is the number of trapeziums used and a,b,h are as defined in figure 9.6. The
constants, h, n, a and b are related by the formula
h=
ba
........................................................................................................................ 9.6
n
Figure 9.7
Splitting a curve into n(4) trapeziums
to improve accuracy of numerical
integration. Higher values of n may give
better results.
Numerical Applications
391
A more accurate technique used to evaluate the area under a curve is to approximate the
function with represented by that curve with an n degree polynomial. This method is
called the Simpsons rule. Two forms of the Simpsons rule exist. These are the Simpson
1/3 rule and the Simpson 3/8 rule. The 1/3 rule results if a polynomial of degree 2 is used
as the approximating polynomial and 3/8 results if a third degree polynomial is used as
the approximating polynomial. Simpson 1/3 rule is stated as
I=
n 1
n 1
h
f (a) + 4 f ( xi ) + 2 f ( xi ) + f (b) ..................................................... 9.7
3
i =1, 3,5
i = 2,4,6
The parameters h, n , a and b used in equation 9.7 are as defined in equation 9.5 and 9.6
A functional implementation of Simpsons 1/3 rule is as shown in Listing 9. 7
Listing 9.7 : Implementation of numerical Integration
Option Explicit
Function Fsimpson13(ByVal textfunction As String, Lb As _ Integer,ub As
Integer,optional h As Double,optional n as _ integer) As Double
1: Dim I As Integer, SumOdd As Double, sumeven As Double
2: Dim x() As Double, y() As Double
3: Dim n As Integer
4: If IsMissing(h) Then
5:
h = (Ub - Lb) / n
6: ElseIf IsMissing(n) Then
7:
n = (Ub - Lb) / h
8: ElseIf n < 0 Or h < 0 Then
9:
Exit Function strange situation exit function
10: End If
11: ReDim x(n) As Double
12: ReDim y(n) As Double
13: x(0) = Lb
14: y(0) = f(textfunction, x(0))
15: Generating x and y array
16: For I = 1 To n
17: x(I) = x(I - 1) + h
18: y(I) = f(textfunction, x(I))
19: Next I
20: SumOdd = SumArray(y, 1, n - 1, 2)
21: sumeven = SumArray(y, 2, n - 1, 2)
22: Fsimpson13=h / 3 * (y(0) + 4 * SumOdd + 2 * sumeven + _
y(n))
392
End Function
Function SumArray(y() As Double, Optional ini As Integer, _ Optional lim As Integer,
Optional inc As Integer = 1) As _ Double
25: Dim I As Integer
26: If IsMissing(ini) Then ini = LBound(y)
27: If IsMissing(lim) Then lim = UBound(y)
28: SumArray = 0
29: For I = ini To lim Step inc
30: SumArray = SumArray + y(I)
31: Next I
End Function
Function f(textfunction As String, x As Double) As Double
34: Dim fx As String
35: fx = textfunction
36:
With ScriptControl1
37: ' .ExecuteStatement "X = " & x
38:
fx = Replace(fx, "x", x)
39:
f = .Eval(fx)
40:
End With
End Function
In Listing 9.7, three functions were used to implement the Simpsons 1/3 rule
numerically. These functions are in lines 0, 24 and 33. The first function is the function
used to implement the numerical integration of a function using simpsons 1/3 rule. The
function requires five arguments, the first is a string containing the translated form of the
function to be integrated. The other arguments are the Lower limits of integration , the
upper limit of integration, the strip width and the number of strips to be used
respectively. Line 5 calculates h if h is not given(i.e if it is missing) from equation 9.6
while Line 7 calculates n if n is not specified also using equation 9.6 . Line 9 exits the
function if h or n is zero or less. Lines 11 and 12 re-dimension x and y based on the
new value of n. Line 13 to 17 generates the array x from Lbound to Ubound step H and
evaluates the corresponding value of f using the TextFunction and the values of x(these
functions values are stored in dynamic array y). Line 20 and 21 used the SumArray
function to evaluate the sum of odd strip and sum of even strips respectively. Line 22
used equation 9.7 to evaluate the integral and returned to the Fsimpson13 function. The
other functions in listing 9.7 are the SumArray function(lines 25 to 31) and function
F(lines 34 to 40). The SumArray function is an example of a function which accepts
array as argument. Function F used the Script control to evaluate user function accepted
at runtime.
Numerical Applications
393
Figure 9.8 is the form used to implement the code in Listing 9.7 while the code in Listing
9.8 is the event procedure used for complete evaluation of Simpsons 1/3 rule using the
interface of Figure 9.8.
Figure 9.8
Visual interface used to
perform numerical
Integration
NOTE
You add the integral sign to the Form by drawing an instance of the Equation object on
the Form. You add the equation object to the form through the Insertable objects Tab of
the component dialog. See Figure 9.9
Figure 9.9
Adding the Equation
object to the Form.
394
Multiple Integrals
Integrals of the form
f ( x, y )dxdy
And
f ( x, y, z )dxdydz
are called multiple integrals. Specifically, the former is called double integral while the
latter is called triple integral. The techniques discussed in the last section can also be
used to implement multiple integral of any dimension. As the name implies, application
of the integration rule twice gives the result for double integral. However, for triple
integral, the rule of integration has to be applied three times.
Numerical Applications
395
I xy =
(x
0 2
2 x + xy )dxdy
I x = ( x 2 2 x + xy )dx
2
Hence,
1
I xy = I x dy
0
Using Simpsons 1/3 rule with n = 10 , the table for the evaluation of the integral Ix is as
shown in table 12. 1
Table 12.1: First evaluation of a multiple integral
N
X
F(x)
0
2.0
2y
1
2.1 0.21+2.1y
2
2.2 0.44+2.2y
3
2.3 0.69+2.3y
4
2.4 0.96+2.4y
5
2.5 1.25+2.5y
6
2.6 1.66+2.6y
7
2.7 1.89+2.7y
8
2.8 2.24+2.8y
9
2.9 2.66+2.9y
10
2.10 3.00+3.0y
Using Simpson 1/3 rule the major components are given as
n 1
Sumodd =
f ( y)
i =1, 3,5
= 6.7 + 12.5y
396
f ( y)
Sumeven =
i = 2, 4, 6
=5.3 + 10y
Hence the integral, Ix by Simpson 1/3 rule using equation 9.7 is given as
=8y + 27
Hence the double integral simplifies to
1
I xy = 8 y + 27dy
0
The result for the double integral is obtained by integrating Ixy using the Simpsons 1/3
rule. Programmatically, the problem inherent in the evaluation of Ixy is the problem of
carrying out string addition. Once this is done ,you can perform any dimension of
multiple integral without worry. Apart from the string addition technique, one can write
code to evaluate the integral as sum of the terms. For example to evaluate Ixy we can
split it to n terms as follows
1 3
I xy =
1 3
1 3
0 2
0 2
0 2
with the form shown above, any multiple integral can be evaluated without the stress of
string addition. The code in Listing 9.9. is a function used to implement double integral
for any polynomial function consisting of n terms while Listing 9.10 is the code used to
split a polynomial to n terms so that the terms can be successively sent to Listing 9. 9 for
evaluation.
Listing 9.9:Multple integral of polynomial function
Function DoubleIntegral(a As String, Lb1 As Integer, ub1 As Integer, Lb2 As Integer,
ub2 As Integer, h As Double, n As Integer)
1: Dim TermArray() As String, k, p,
2: Dim q, i, j, b, Eval() As Double, r() As String
3: a = LCase(a)
4: TermArray = SplitPoly(a)
5: ReDim r(k) As String
6: ReDim Eval(UBound(TermArray))
7: For i = 0 To UBound(TermArray)
8:
b = Split(TermArray(i), "*")
9:
k = 0
10:
For j = 0 To UBound(b)
11:
p = InStr(b(j), "y")
12:
If p > 0 Then
13:
k = k + 1
Numerical Applications
397
14:
ReDim Preserve r(k)
15:
r(k) = b(j)
16:
End If
17:
Next j
18:
TermArray(i) = Replace(TermArray(i), "y", "1")
19:
r(0) = Fsimpson13(TermArray(i), Lb1, ub1, h, n)
20:
a = Join(r, "*")
21:
a = Replace(a, "y", "x")
22:
Eval(i) = Fsimpson13(a, Lb2, ub2, h, n)
23:
DoubleIntegral = DoubleIntegral + Eval(i)
24: Next i
End Function
Listing 9.9. uses the Fsimpson13 function and the splitpoly function(Listing 9.10). Line
3 converts the string to lowercase while line 4 splits the polynomial into n terms by
calling the splitpoly function. Lines 7 to 24 evaluate each of the term in the polynomial
function. Line 18 replaces all the ys in the function with 1 and calls Fsimpson13 on the
resulting term in Line 19. Line 20 joins all the ys discarded with result of the evaluation
of the Fsimpson13 rule. Line 21 re-places all the y with x to enable it use the
Fsimpson13 wrt to y. Line 22 calls the Fsimpson rule with the second upper and lower
limits of integration. Line 23 adds the result of the term by term evaluation of the double
integral.
Listing 9. 10:Spliting a polynomial into n terms using string
Function SplitPoly(A As String) As String()
1: Dim K As Integer, TermArray() As String
2: Dim P As Integer, Q As Integer
3: Do
4:
ReDim Preserve TermArray(K) As String
5:
P = InStr(2, A, "+")
6:
Q = InStr(2, A, "-")
7:
If P > 0 And (P < Q Or Q = 0) Then
8:
TermArray(K) = Left(A, P - 1)
9:
A = Mid(A, P)
10:
ElseIf Q > 0 And (Q < P Or P = 0) Then
11:
TermArray(K) = Left(A, Q - 1)
12:
A = Mid(A, Q)
13:
Else
14:
TermArray(K) = A
15:
Exit Do
16:
End If
17: K = K + 1
18: Loop While (P > 0 Or Q > 0)
398
Figure 9.10
Polynomial Interpolation
Given N+1 points (xk, yk) for k=0,1,N . The problem of estimating a missing value of y
for a specified value of x (which must be between x0 and xN) is called an interpolation
problem. This is done by taking a weighted average of known function values (y-values)
at neighboring points. Polynomial interpolation is the process of approximating the
tabulated function with a polynomial. The missing y values can then be estimated using
this interpolating polynomial.
Two common polynomial interpolation techniques are
(a)
(b)
399
Numerical Applications
Lagrange Interpolation
The French mathematician, Joseph Louis Lagrange showed that a polynomial fw(x) of
degree N that passes through the N+1 points (x0,y0), (x1,y1), (x2,y2)(xN,yN) has the
form
N
FN ( x ) = y K L K ( x ) .................................................................................... 9.8
k =0
where
LK is the Lagrange Coefficient polynomial defined as
N
L K (x) =
j =0
jK
(P x )
................................................................................... 9.9
(x x )
j
f N (2.3) = y k L k ( x )
k =0
A typical visual interface which can be used for Lagrange interpolation is as shown in
figure 9.11. Listing 9. 11 has the code used to drive the interface.
400
Figure 9.11
Visual Interface for the
Lagrange interpolation
Problem.
In Figure 9. 11 The Add X and Add Y buttons are used to Add the values of X and Y to
the X and Y data list respectively. Also, the RemoveX and RemoveY buttons are used to
remove selected X and Y list items from the X and Y data list respectively. The Execute
button executes the code used for the polynomial interpolation using lagrange
interpolation technique.
Listing 9.11: Program implementation of the Lagrange visual interface (Figure 9.11)
Option Explicit
Option Base 0
Private Sub cmdAddX_Click()
1: lstXdata.AddItem txtXdata.Text
2: txtXdata.Text = ""
3: txtXdata.SetFocus
End Sub
Private Sub cmdAddY_Click()
6: lstYdata.AddItem txtYData.Text
7: txtYData.Text = ""
8: txtYData.SetFocus
End Sub
Private Sub cmdExecute_Click()
11: Dim N As Integer, X() As Double, Y() As Double
Numerical Applications
12:
13:
14:
15:
401
402
In Listing 9.11, the first two event procedures are used to Add the X and Y values to the
list boxes from the x and y data text boxes. The event procedure for the execute buttons
from line 10. Lines 14 to 7 were used to ensure that the x and y data list boxes have equal
number of items. Line 18 obtains the value of N as the list count 1 since our counting
is zero based. Lines 19 to 21 redeclare the array having known n. Lines 22 to 25 were
used to populate the x and y array with data from the x and y data list respectively. Line
26 assigns the point of interpolation to P. Lines 27 to 34 were used to evaluate L(K) using
equation 9.9. Lines 35 to 38 were used to implement equation 9.8. Line 39 was used to
display the result in the result label. Lines 41 to 50 contain the event procedure used to
remove x and y values from the list boxes
F[x k ] = f(x k )
F[x k -1 , x K ] =
F [xk ] F [xk 1 ]
xk xk 1
F [xk 2 , xk 1 , xk ] =
F [xk 1 , xk ] F [xk 2 , xk 1 ]
xk xk 2
F [xk 3 , xk 2 , xk 1 , xk ] =
...................... 9.10
F ( xk 2 , xk 1 , xk ) F ( xk 3 , xk 2 , xk 1 )
xk xk 3
F xx j , xk j +1 ,..., xk =
] [
F xk j + +1 ,..., xk F xk j ,..., xk 1
xk xk j
] ........................... 9.11
F[,,,]
F[,,,,]
F[x0,x1,x2,x3]
F[x1,x2,x3,x4]
F[x0,x1,x2,x3,x4]
403
Numerical Applications
As an example, we show how to construct the difference based on the data point (1, 2 ),
(2, ) , (4, ), (5, ), (7, ). This is as shown in table
Table 9.4:Divided difference for f(x) = cos(x) x/10
K
F[xk]
F[x]
xx
0
2
3
4
2
3.5
3
4
4
6
For computation purposes, the divided differences in Table 9.3, need to be stored in an
array. For convenience, we use D(k,j) and make the correspondence
D(k,j) = F[xk-j,xk-j+1,,xk]
From 9.12 and 9.10, one can show that D(k,j) is recursively defined as
D( k , j ) =
D(k, j - 1) D(k 1, j 1)
xk xk j
k = 1 to n, J = 1 to n ............. 9.13a
404
Figure 9.12 a
Visual interface for
the divided difference
interpolation problem.
Numerical Applications
405
406
33:
Next J
34:
Sum = D(0, 0)
35:
For K = 1 To N
36:
Prod = 1
37:
For J = 0 To K - 1
38:
Prod = Prod * (P - X(J))
39:
Next J
40:
Sum = Sum + Prod * D(K, K)
41:
Next K
'Send to difference table in Form2 with name frmDivide
42:
43:
44:
45:
46:
47:
48:
49:
End
For I = 0 To N
frmDivide.grdDivide.TextMatrix(I + 1, 0) = I + 1
frmDivide.grdDivide.TextMatrix(I + 1, 1) = X(I)
For J = 0 To N
frmDivide.grdDivide.TextMatrix(I + 1, J + 2) = _
D(I, J)
Next J
Next I
lblResult.Caption = Sum
Sub
Numerical Applications
407
Lines 1 to 25 of Listing 9.12 is similar to Lines 1 to 26 of Listing 9.11 used for Lagrange
interpolation. Lines 26 to 28 implement equation 9.13 b while lines 29 to 33 implements
equation 9.13b. The actual interpolation is performed in lines 34 to 41 using equation
9.14. Lines 42 to 48 were used to send the generated divided difference to the grid in
form 2(frmDivide). The rest of the code consist of three event procedures with the first
two similar to those in listing 12.11. The last event procedure is used to show the divided
difference form.
3 5 8
A = 9 3 2
2 4 7
408
409
Numerical Applications
Problem Set 9
Question 9.1
Implement the Simpsons 1/3 rule using the interface shown in Figure 9.8. Note that on
clicking option, a form displaying the analysis of Simpsons rule in tabular form should
show. Your analysis should be displayed in tabular form as shown in table Q9.1 using
a) Grid control
b) Array of labels
c) Using OLE automation so that the table is created and displayed in MS Excel
d) Using OLE automation so that the table is created and displayed in MS Word
Table Q9.1
S/N
1
2
3
4
5
.
.
.
.
N
Total
X values
1.0
1.1
1.2
1.3
1.4
.
.
.
.
3
Y values
7.0
7.2
7.4
7.6
7.8
.
.
.
.
11
Odd Values
Even Values
7.2
7.4
7.6
7.8
.
.
.
.
Sum of odd
Values
Sum of Even
Values
Question 9.2
a) Repeat program 9.1 of double Integral
b) Repeat problem 9.2 for triple Integral
Note that the analysis of successive integration should be displayed in different forms or
tables or worksheet as the case may be.
410
Question 3:
Implement a solution capable of integrating both continuous(using functions) and
discrete data using simpsons 1/3 rule. Discrete data should be stored in list boxes
Question 4:
Using the interface shown in Figure below, write code to drive the interface using
a) Excel functions
b) Two conventional matrix technique
Figure Q 9.4
Note: the labels and text boxes are all elements of control array created using the
txtOrder
Question 5
Using an interface similar to Figure Q9. implement a program capable of solving
Simultaneous linear equation in n variables using
a) Excel functions.
b) Conventional analytical technique
c) Iterative technique such that results of iterations are displayed in a well formatted
grid.(see Literatures for help)
Numerical Applications
411
Question 6
Implement a solution that solves and display the iteration results for non linear
problem using the Newton Raphson technique. Note that all the functions have to be
accepted at run time and derivative obtained automatically using numerical
differentiation technique.
Question 8
Write a recursive function for the Divided difference interpolation technique.
Question 9
Write a Visual Basic function that accepts a mathematical function in a textbox , an initial
guess and a tolerance and a maximum iterate. Your function should return an array
consisting of all the iterations performed until max iteration or convergence using
Newton Raphson technique.
412
CHAPTER
10
Database Access
Data Control
The Recordset Object
The Visual Data Manager
Structured Query Language
Visual Basic Data Applications
414
Database is a tool for storing and manipulating information. Models used to accomplish
these tasks include the relational model, the network model, hierarchical model and star
model. By far the relational model is the most popular. This model was developed from
set theory and predicate logic by Dr. E. F. Codd in the late sixties. The relational model
defines the way data can be represented(data structure), protected(data integrity) and the
operations to be performed on data(data manipulation). It was developed based on the
following assumptions (now regarded as the characteristics of the relational model)
All data are conceptually represented as an orderly arrangement of data in rows and
columns.
At any given row and column position, there is only one value(values are scalar)
All operations are performed on an entire relation and result in an entire relation. This
is the principle of closure.
From Codds Rule all data are conceptually represented as a relation. The Structure in
Table 10.1 is an example of a relation.
Table 10.1 DataBase Relation
WellNAME
DailyRate
BeanSize
Choba34
500
32/64
Choba78
800
16/64
Abuja24
1000
48/64
Delta11
850
32/64
The relation shown in Table 10.1 has three columns(i.e WellName, DailyRate and
BeanSize) and four rows. Using conceptual relational terminology, a row is called a tuple
while a column is called an Attribute. The number of tuples in a relation is called the
cardinality of the relation while the count of attributes in a relation is called the degree of
the relation
NOTE
A table with no duplicate row qualifies to be a relation if it has a unique column header.
In Microsoft Jet database management system(Microsoft Access) , a relation becomes a
recordset once it is instanciated in a physical database. This makes sence because the
database relation is actually a set(or collection) of records(rows). The other conceptual
relational terminologies are also addressed differently in physical databases. For
example, the tupple(rows) and attribute (column) are called the records and fields
respectively. Also, the cardinality and degree are called recordCount and Count of fields
respectively.
Using object oriented technique, we obtain the number of records and fields in a database
as
415
Database Access
data1.Recordset.RecordCount
data1.Recordset.Fields.Count
The recordset should be looked as a matrix with the recordcount and fields count as the
dimension. In the code above, data1 is the object that provides the connection to the
database. It is an intrinsic Visual Basic control used to provide access to databases.
Data Control
The data control is an intrinsic control used to provide a link between bound controls and
a
database. Figure 10.1 shows the
data control and some bound
controls on the form.
Figure 10.1
Form Showing the Data
Control and some Bound
Controls
The data control acts as a middle man between the database and the bound controls.
The mechanism of operation of the data control is as shown in Figure 10.2.
NOTE
Controls with DataSource property are called bound controls or data-aware controls
Figure 10.2
Mechanism of
operation of the
data control.
DataBase
Data Control
Bound Controls
To connect the data control to the data base you specify two properties. These are:
416
DatabaseName
Recordset
DataSource Property
DataField property
The DataSource property enables the bound control to know the DataControl used to
establish connection. This is because you can have more than one data control on the
Form with each providing connection to different database files. Setting this property
requires that you select the data control from the datasource property value list.
After setting the datasource property, you have to specify the name of the field you want
the control to bound. The property needed for this is called the datafield property. Like
the datasource property, the datafield property is set by selecting the name of the field
from the datafield property value list.
417
Database Access
Using five TextBoxes,five labels and a data control, design the form as shown in
Figure 10.3.
Give the TextBoxes names related to their use(. E.g the First TextBox should be
given the name txtTitle and the second the name txtAuthors and so on).
Figure 10.3
Creating an application with
the data control.
MoveFirst
MovePrevious
MoveNext MoveLast
Set the data base same property of the data control to Nwind( see Figure 10.4)
Figure 10.4
Setting the DatabaseName
property of that Data control.
On clicking the ellipsis in the
DatabaseName property
value,this dialog appears.
418
After setting the DataBase name, you set the recordsource property to All Titles. This
connects the data control to the All Titles Table in the BIBLIO database file.
Set the DataSource property of each TextBox on the form to Data1. This indirectly
connects each of the TextBoxes to the All Titles Table in the BIBLIO database file.
Select an appropriate ListItem in the DataField property value list of each of the
TextBoxes.( For example the first TextBox should have a DataField property of Title
and second should have a data field property of Author). Figure 10.5 shows the
DataField property value list in its opened form.
Figure 10.5
DataField property List
exposing all the Files in the
All Titles Table of the Biblio
DataBase File
After setting these properties you run the program by pressing F5. This should show the
first record though it waste some pretty long time. Click movenext to move to the next
record, and movelast to move the last record. Also, click move previous to the previous
record and move first to move to the First record. Note that the MoveNext, the
MovePrevious, MoveLast and MoveFirst keys are called the navigation keys.
To view the record shown in Figure 10.3 you press the MoveNext button consecutively
for 38 times. To view the 50th record you click the MoveNext button 49 times!. The
question is, is there no way we can jump to the nth record without clicking the MoveNext
nth 1 times when the current record is the first. Visual Basic actually provides an easy
way to move the record set pointer n records from the current record using code. This is
done simply as
Data1.Recordset.Move n
To give the recordset pointer a positive displacement of 37 from the current record you
use the command
Data1.Recordset.Move 37
To give the recordset pointer a negative displacement, you give the recordset move
method parameter a negative number. For example to move the recordset pointer 10
places backward you use the command
Database Access
419
Data1.Recordset.Move 10
NOTE
When the move method is used to move to a record that does not exist, then a blank
record is displayed. Trying to move the recordset pointer again invokes Visual Basic
Error 3021(No current record).
Apart from the move method, the RecordSet object also has other navigational methods.
These are used programmatically as follows:
Data1.Recordset.MoveNext
Data1.Recordset.MovePrevious
Data1.Recordset.MoveLast
Data1.Recordset.MoveFirst
NOTE
When a parameter of 1 and 1 is supplied in the move method of the recordset object, it
has the same function as the MoveNext and MovePrevious buttons of the data control or
the MoveNext or MovePrevious method of the RecordSet
DataBoundList(DBList)
DataBoundCombo(DBCombo)
DataBoundGrid(DBGrid)
MSHFlexGrid
MSFlexGrid
To illustrate how to display multiple records we use the MSHFlexGrid control and the
data control as follows:
420
Draw an instance of the MSHFlexGrid and the Data Control on a blank form. Set
the DatabaseName and the recordsource properties of the Data control to BIBLIO
and All Titles respectively.
Run the program by pressing F5 function key. This should display all the 16057
records in the All Titles table of the BIBLIO database file as shown in Figure 10.6
NOTE
It takes a considerably long time to display the records in the grid. This is because of the
volume of records to be displayed. With a Pentium III 500 MHZ, it took more than 15
seconds to display the records shown in Figure 10.6.
The records displayed in Figure 10.5 are not editable. To display editable records, you
need to use the DataBoundGrid control.
NOTE
The databound grid control is not available in the working model edition of Visual Basic
Figure 10.6
Grid control
Displaying multiple
records from the
BIBLIO database
AllTitles Tables
421
Database Access
QUERY
Using the RecordSet object and the Data Control as case study, what is the difference
between an object and a control.?
Find Methods
The find methods are used to locate a specific record in a RecordSet. These methods are
FindFirst : Used to locate the first record that meets a specified criteria
FindNext : Used to locate the Next record that meets a specified criteria
FindPrevious : Used to locate the previous record that meets a specified criteria
FindLast : Used to locate the last record that meets a specified criteria
strCriteria
Where x is any postfix of the find methods and criteria is a string expression used to
match field values with constant. For example to find the first record in the All Title
RecordSet
With title containing the text C++ . When the code
Data1.Recordset.FindFirst
[Title]
Like *C++*
is placed in an event procedure and fired, the record shown in Figure 10.7 is displayed.
422
Figure 10.7
Finding record using the
FindFirst Method.
Test this code by placing the code in the click event of the Form as shown in Listing 10.1
Listing 10.1: Using the RecordSet FindFirst method in and Event Procedure
Private Sub Form_Click()
1:
Dim strCriteria As String
2:
strCriteria = "[Title] Like '*C++*' "
3:
Data1.Recordset.FindFirst strCriteria
End Sub
Line 1 of Listing 10.1 declares a string variable . This variable would be used as the
Parameter of the FindFirst Method. Line 2 assigns the Search criteria to the string
variable. Notice the presence of the wildcat character * before and after the word C++.
This means that it should Find and display any book whose title has the text C++. It is
necessary that we put the wildcat character before and after the SearchKey otherwise a
different output may be displayed. For example if line 2 is written as
strCriteria = "[Title]
423
Database Access
Figure 10.8
Effect of the Wildcat
character on the find method.
This means any book whose title begins with the word C++. If Line 2 is written as
strCriteria = "[Title]
It means it should find and reposition the recordset pointer to display any book whose
title ends with C++. However, omitting the wildcat character means it should find and
display any book whose title is C++. Because no book has a title of C++, it means the
RecordSet pointer would not move and the current record remains the current record.
Also in Line 2 , the single quote is part of the syntax when Text(or string) fields are
being compared. However, if date fields are being compared, the hash sign(#) is used. For
example to find the first book in a recordset published after 1st October 1990 you use the
code
Data1.Recordset.FindFirst
Omitting the quote or hash sign in the query expression when comparing string and date
fields respectively invoke a syntax error with message Missing operator in expression
When using the Find method, we should remember that at times the record being sought
for might not be found in the recordset. In this case we use a message box to display the
message: Record not in the Recordset the NoMatch property of the RecordSet is a
Boolean property that is True when any Find Method finds the record being sought for
and False if the record being sought for is not found in the RecordSet.
424
Types of RecordSet
Visual Basic allows us to use any of the following types of RecordSet
Dynaset
Snapshot
Tables
The Table and Dynaset recordset types are updateable while the snapshot is not editable.
You specify the recordset type through the RecordsetType property of the Data control. If
the RecordsetType property is not specified, the default(dynaset is assumed). This will be
okay for most of our discussion. Complete treatment of the key differences between the
three RecordsetType is treated in Volume 2 of this Text.
425
Database Access
transaction. The properties of the chemicals will be stored in another table. Lets call this
table the Demulsifiers Table(tblDemulsifier) and the table used to store the supplier
information the Manufacturer profile table(tblManufacturer). The Fields in these tables as
well as the data types and some validation are shown in Table 10.2 and 10.3 .
Table 10.2: Demulsifier Manufacturer Information Database table
Field Name
Field Type
Validation Rule Validation text
Manufacturer Name Text
Like [A-Za-z]* First Character must be
alphabetic.
Incorporation Date Date/Time
<Date()
Incorporation date must be
less than today.
Location
Text
Address
Text
Phone number
String
Like [0-9]*
Accreditation Date Date
<Date ()
Accreditation date must be
less than today.
Manufacturer ID
Currency
Like [a-zA-Z]* Must begin with an
Alphabetic character.
Email Address
Text
Table 10.3: Demulsifier Information Database table
Field Type
Validation Rule
Field Name
Manufacturer ID
Text
Like [a-zA-Z]*
Tag
PH
Text/String
Single
HLB
Dielectric
Permitivity(X)
Date
Manufactured
Price per Drum
Double
Double
1< = PH < =
14
>0
>0
Date
<Date ()
Currency
>0
Validation text
Must begin with an
Alphabetic character.
PH must be between 1 and
14.
HLB must be a real number
Dielectric constant must be
greater than zero.
Date supplied must not be
less than today.
Currency must be positive.
Relationships
In databases, a relationship is a link that is created and enforced between two or more
tables that enables data to be retrieved, accessed or manipulated from these tables. The
relationship between two or more tables in a multi-table database must be understood
before attempting to design the database. By Inspection of Table 10.2 and 10.3 we notice
426
that the tables are related by the manufacturer ID Fields. Figure 10.9 shows a schema
Name
Incorporation Date
Location
Address
Phone number
Accreditation Date
Manufacturer ID
Manufacturer ID
Tag
PH
HLB
Dielectric Constant
Date Manufactured
Price per Drum
A part from the relationship, it is necessary that we understand the keys associated with
each table. From experience we know that no two Manufacturers can be given the same
ID, hence the manufacturer ID is unique in Table 10.2. This does not apply to
Table 10.3. In Table 10.3, the Manufacturer ID is not unique because a manufacturer can
have more than one chemical she is advertising. The only key that is unique in the
demulsifier table is the Tag. Each demulsifier has a Tag used to uniquely identify the
demulsifier. Hence the unique field in Table 10.3 is the Tag field. In database parlance,
the unique fields are called the Primary Keys. It is important that you set a primary key
for each table created in a database. Therefore, the primary key in Table 10.2 is the
Manufacturer ID while the primary key in Table 10.3 is the Tag. The field that stores a
copy of another tables primary key is called the foreign key. Hence the Manufacturer ID
field is the Foreign key in Table 10.3.
Having understood some of the terminologies used in data base design, we start our
exercise on how to create the database file using the Visual data manager.
Take the following steps to open the Visual Data manager.
Click the save project icon on the standard toolbar. This opens the Save As dialog as
shown in Figure 10.10
Click Open
Database Access
427
Figure 10.10
Creating a folder for a
database application
from The Save file As
dialog.
NOTE
It is always important that you create a folder before creating a database file using the
Visual Data Manager. This makes it very easy to copy your work from one system to the
other by drag drop operation.
After saving your project, you can now create your database using the Visual Data
Manager . To do this, follow the steps outlined below.
Select Visual Data Manager from the Add-Ins menu. The Visual Data manager
MDI form appears as shown in Figure 10.11
From the Visdata , select File New Microsoft Access Version 7.0 MDB
The Select Microsoft Access Database to create appears.
Open the Folder(Chemical Data Folder) and save the File as Chemicals. Your dialog
should look like that shown in Figure 10.12.
428
Figure 10.11
The Visual Data(VisData)
MDI appears on selecting
Visual Data manager from
the Add Ins Menu
Figure 10.12
The Select Microsoft
Access Database to Create
Dialog appears after
selecting Access Version
7.0MDB from the
VisData New item of the
File Menu. Open your
Folder and save the project
in side your folder.
On closing the dialog, the VisData takes the look of Figure 10.13. At this time you have
created a database file. What is left is for you to add tables and fields to the database.
To create a table, right click properties in the Visdata database window and select New
Table from the pop up menu. This action loads the Table structure dialog shown in
Figure 10.14. To Create the database table represented in Table 10.2, you need the
following steps.
In the table name field of the table structure dialog type tblManufacturers
Click the Add Fields CommandButton to add the List of fields in Table 10.2 On
clicking this Button, the Add Field dialog appears as shown in Figure 10.15
Database Access
429
Figure 10.13
Visdata showing Database
Window and the SQL
structure window. You right
click the Database Window
to add new table
Figure 10.14
Table Structure Dialog used
to add Fields and indices to
tables
On the Name TextBox of the AddField Dialog shown in Figure 10.15, Type the field
name Manufacturer name.
430
On the Validation Text TextBox, type Manufacturer name must begin with an
alphabetic character.
Figure 10.15
The Add Field dialog
appears on Clicking
the Add Field
CommandButton of
the table structure
dialog
On clicking OK, the Add Field dialog appears as shown in Figure 10.15.
Follow the previously outlined steps to add the other fields in Table 10.2 to
tblManufacturer.
After adding all the fields, click Close to close the Add Field dialog. By this time
your table structure dialog should be as shown in Figure 10.16 with all the fields
showing in the Fields List.
Figure 10.16
Table Structure dialog
showing all the fields in
tblManufacturer
Database Access
431
Click the Add Index to add the primary key index to this table. This shows the Add
Index to dialog shown in Figure 10.17(The Name TextBox and Indexed Fields
TextBox would be empty)
Figure 10.17
The Add Index To
dialog use to Add
primary keys and indices
to tables
Double click Manufacturer name in the list of available fields. This Adds this field to
the Indexed fields. You can also use drag drop to add a field from the list of available
field to the Indexed Field Box.
Make sure the unique and primary CheckBoxes are selected.( your design should be
exactly as shown in Figure 10.17).
Click Close to close the Add Index to dialog and return to the Table Structure
dialog which now takes the form shown in Figure 10.18.
NOTE
You remove fields and indices added to tables by clicking the Remove Fields and
Remove Index buttons respectively. However, it is erroneous to remove indexed fields
without removing index
432
Figure 10.18
Table structure
showing Fields in
the Fields List and
Index in the index
List
To create the Table, click the Build the Table button. In the absence of errors, the
Table structure dialog closes and the Table built and added to the VisData Database
window as shown in Figure 10.19.
CAUTION
If any error or power interruption occurs before building the table, you have to start all
over to add fields and indices the next time you open VisData
Figure 10.19
VisData showing
newly created table in
the database window.
Database Access
433
To create the second table (tblDemulsifier) follow the steps outlined below which is
almost the same as the steps used to create the first table:
Right click anywhere in the database window and select new table from the pop up
menu that appears. This should open the table structure dialog shown in Figure 10.14
Type the table name tblDemulsifier in the Name TextBox of the table structure dialog
Click the Add Fields Buttons to show the Add Fields dialog.
Use the Fields and attributes shown in Table 10.3 to create the fields needed in this
table.
Close the Add Fields dialog to return to the table structure dialog which now takes
the form shown in Figure 10.20.
CAUTION
Make sure the required CheckBox is selected as each field is added. This is necessary
because each Chemical manufacturing firm must provide all the information stated in
Table 10.3
Table 10.20
Table structure showing
list of fields in
tblDemulsifier.
At this stage we are now ready to add indices to our table. Here we have two keys, the
primary Key which is the Tag field and the foreign key which is the Manufacturer ID
Field. To add the indices follow the steps outlined below
434
Click the Add Index button to show the Add Index to dialog.
Double click the DemulsifierTag in the List of available fields. The DemulsifierTag
should now appear in the indexed fields MultiLine TextBox
Click OK making sure that the unique and primary CheckBoxes are selected. This
adds the first index being the primary key index to the index ListBox of the table
structure dialog.
Double click the manufacturer ID fields in the available field List to add it to the
Index fields multi-line TextBox.
Click OK and then Close. This closes the Add Index to dialog and return to the
table structure dialog which now take the look shown in Figure 10.21.
Figure 10.21
Table structure
showing List of
tables in
tblDemulsifier.
Click the Build the Table button to create the Table. In the absence of errors, the
Table structure dialog closes and the Table built and added to the VisData Database
window as shown in Figure 10.22.
Since the tables have been created, you now add records or Exit VisData and add
records later in code. To close VisData, choose Exit from the VisData File menu. To Add
records see the section under adding records to tables.
Database Access
435
Figure 10.22
VisData showing
created tables in the
database window.
Right Click tblManufacturer in the VisData Database window and select Open from
the pop up menu(see Figure 10.23). This should show the window shown in
Figure 10.24
Figure 10.23
VisData showing
pop up menu used to
Open table for
records addition.
436
Figure 10.24
Table manipulation window
opened as dynaset recordset
type.
Click the Add Button to start adding records. On clicking add, the window in
Figure 10.24 closes and that shown in Figure 10.25 opens.
Populate the Fields with the first record and click update. On clicking update, the
Window in Figure 10.25 closes and that shown in Figure 10.24 opens.(At times you
can do in-place manipulation with only Figure 10.24)
Repeat the previous two steps until all your records are added
NOTE
Though the recordset type created here is dynaset, you can create table or snapshot by
selecting the appropriate recordset type from the VisData toolbar.
Figure 10.25
Window used to Add/Edit
records in a database table.
Database Access
437
To obtain the data used in this exercise, check the accompanying CD ROM. Other wise
you can load your own data(your data must satisfy the constraint stated in Tables 10.2
and 10.3).
Select Data Form Designer from the Utility menu. This opens the interface shown
in Figure 10.26
Figure 10.26
VisData Data Form
Designer. This is used
to design simple data
driven interfaces with
array of Textboxes and
code used to drive the
interface.
In the Form name TextBox type the name of the form you want VisData to create(Do
not include the prefix(.i.e frm) because Data Form Designer adds the prefix for you.
For our purpose, we want Visdata to create frmManufacturersProfile so we type
ManufacturerProfile in the Form Name TextBox.
438
Figure 10.27
Data Form designer with
the available field list
populated with
Available fields names
Use the First two Arrows - captioned standard CommandButtons to move field(s)
from the Available field List to the Included Fields List. To move a field or fields
from the included Fields List to the Available fields list use the last two arrow
captioned standard command buttons. The Fields in the Included fields are the fields
that will be included when a Form is designed. For our purpose, include all the fields.
Note that the two graphical command buttons are used to adjust the sequence in
which the fields are created.
Click the Build the Form button and wait while VisData builds the form.
Activate your Visual Basic Application from the windows TaskBar and view the
created form which should look like the interface shown in Figure 10.28
Figure 10.28
Form Interface built
by Data Form
Designer.
Database Access
439
Click the Add button to enable you Add records and the update button to update the
database with the recently added record. The Delete button enables you to delete the
current record while the Refresh buttons displays the first record
QUIZ
How is the Refresh button different from the MoveFirst button?
End the program and view the code generated by the VisData Data Form Designer.
Listing 10.2 reproduces this code for the purpose of analysis
440
Queries used to retrieve and manipulate records in existing fields and tables. These
queries are called Data Manipulation Language(DML) queries (or Command)
Queries used to create database components like fields, tables and index. These
queries are called Data Definition Language(DDL) queries (or Command)
Queries used to manipulate and administer permissions and securities. These queries
are called Data Control Language(DCL) queries (or Command)
The DDL and DCL commands are somewhat advanced and will be considered in
Volume 2 of this text under DAO queries. We now consider the syntax of the DML
commands
NOTE
In the SQL commands, fields names without spaces(CHR(32)) can be written without the
square brackets.
To retrieve all the records in all the fields in a database table, you use the syntax given
below
Database Access
441
Add the MSflexgrid control and the data controls to the form
Set the DatabaseName property of the data control to the name of the database file.
For our case the database has the following path Chemical Data Project/Chemicals
located in the VB98 folder. Specify your own path if your path is different.
Unlike in the previous section, we are going to set the RecordSource using an SQL
SELECT statement as shown in Listing 10.3
442
assign the SQL statement to a string variable and then assign the variable to the
RecordSource property. Line 2 has the Refresh method. This method is used to refresh
the data structure of the data control to enable it to display the updated Recordset. On
implementing this with the database included in the CDROM that accompany this book
you should have the output shown in Figure 10.29.
Figure 10.29
MSFlexgrid control
displaying all the
records in a
database. This was
implemented using
codes.
NOTE
When using the MSflexgrid control to display data, the column width do not adjust
themselves automatically. You would need to set the AutoResize property to
vbResizeColumns to enable you resize the columns. To display records in grids that can
automatically resize itself use the dbGrid control.
Database Access
443
Apart from the greater than operator, the SQL SELECT statement uses other comparison
operators to limit the ResultSet produced by the SQL SELECT statement. These
operators are as shown in Table 10.4
Table 10.4 operators used with the SQL WHERE clause
S/No Operator
Function
1
<
Used to retrieve records Less than a specified value
2
<=
Used to retrieve records Less than or equal to a specified value
3
=
Used to retrieve records equal to a specified value
4
>
Used to retrieve records greater than a specified value
5
>=
Used to retrieve records greater than or equal to a specified value
6
<>
Used to retrieve records Not Equal to a specified value
7
Between
Used to retrieve records within a specified range of values
8
IN
Used to retrieve records contained in a range of values
9
LIKE
Used to retrieve records that match a specified pattern
It is worthwhile to note that the first 6 operators in Table 10.4 can be used in both the
mathematical, string or date sense. For example in the date sense, the following dates
#12/01/02#, #2/02/03# and #11/09/02# are all greater than #10/29/02#. This is true
because today is considered greater than yesterday in date arithmetic. Likewise, today is
less than tomorrow. In the string( or text) sense, a string is said to be less than another
string if the ASCII of first character is less than the corresponding ASCII of the other
string. For cases where the first character are equal, the next character are compared until
two different ASCII characters are found.
NOTE
When comparing text values with values in date and text fields you must enclose the test
values in hash and single quote respectively.
The BETWEEN operator is more or less used with date and numeric fields while the
LIKE operator is used only with text fields. The LIKE operator works very much like the
LIKE operator discussed in Chapter 5. The IN operator on the other hand works with any
data type. Functionally, It is similar to the BETWEEN operator. The difference being that
the BETWEEN operator works with range of continuous values while the IN operators
work with a range of discrete values. This is exemplified as follows.
SELECT
Here the IN operator was used with numbers, you can also use the IN operators to limit
string fields as well as date fields once they are enclosed with quotes for string fields and
hashes for date fields. For example to retrieve all the demulsifier supplied by the
444
manufacturers with Manufacturers ID ; A01, E05, B03 and Q08 set the RecordSource
property of the data control with the SQL statement
SELECT
* FROM tblDemulsifier WHERE [Manufacturer ID] IN
(A01, E05 , B03, Q08)
Figure 10.30 shows the records displayed by the Query above
Figure 10.30
Restricted Records
displayed by
invoking the SQL
where clause.
Some SQL statements written using the operators in Table 10.4 are as shown below
SELECT * FROM tblDemulsifier WHERE
BETWEEN #10/2/02# AND #11/02/02#
[Date
Manufactured]
Observe that the AND logical operator is always used with the BETWEEN operator. An
example showing how the like operator is used is as follows
SELECT * FROM tblDemulsifier WHERE [Demulsifier Tag] LIKE
[A*]
Here the like operator was used in its usual string sense. Setting the RecordSource
property with this SQL statement retrieves all the Records whose Tag starts with the
letter A. See Chapter 5 for details on how to use the LIKE operator to manipulate
strings(texts)
Database Access
445
compared fields. For example to display all the records with HLB greater than 3 and pH
between 6.5 and 9 you invoke the SQL statement as follows.
SELECT * FROM tblDemulsifier WHERE HLB < = 3 AND Ph >= 8
The OR operator can also be used instead of the AND operator though it has its own
implication.
[Date Manufactured]
446
observe how the hashes and quotes were used in the SQL statements. This syntax is the
same as the syntax where constants were used as test values.
A simple application used for single field screening is implemented with the interface
shown in Figure 10.31
Figure 10.31
Window for
dynamic
specification of the
SQL WHERE
Clause condition at
run time
The interface shown in Figure 10.31 actually explains itself. A Screening criteria is
selected and the limiting operator and value specified. As the Screen button is clicked, the
data control is refreshed thus displaying the new ResultSet in the grid control.. The code
for the implementation of the interface is as shown in Listing 10.6
Listing 10.6: Dynamically specifying The SQL where clause condition at runtime
Private Sub Form_Load()
1: Data1.Visible = False
2: With cboscreening
3: .AddItem "pH"
4: .AddItem "HLB"
5: .AddItem "Dielectric Constant"
6: .AddItem "Demulsifier Cost"
7: .ListIndex = 2
8: End With
Database Access
447
9: With Me.cbolimitingcondition
10:
.AddItem ">"
11:
.AddItem ">="
12:
.AddItem "<="
13:
.AddItem "<"
14:
.AddItem "="
15:
.AddItem "<>"
16:
.ListIndex = 1
17: End With
18: cmdScreen.Value = True
End Sub
Private Sub cmdScreen_Click()
21: Dim X1 As String
22: Dim X2 As String
23: Dim X3 As Double
24: X1 = Me.cboscreening.Text
25: X2 = Me.cbolimitingcondition.Text
26: X3 = Me.txtLimitingValue.Text
27:
Data1.RecordSource =Select * From tblDemulsifier &_
Where [" & X1 & "] " & X2 & " " & cstr(X3)
28: Data1.Refresh
End Sub
In Listing 10.6, Line 1 is used to set the visible property of the data control to False. This
is important because it is not useful at runtime. Always set the Visible property of data
controls to False when they are not useful at runtime. However, the data control is useful
at design time to establish the connection to the database file. Lines 2 to 8 were used to
AddItems to the Criteria ComboBox while Lines 9 to 17 are used to add operators to the
operators Combo. Line 20 starts the event procedure used for the actual screening. In this
event procedure, Lines 21,22 and 23 declare three variables while Lines 24,25 and 26
assign the texts in the ComboBoxes/TextBoxes to the variables. The SQL statement is
written in Line 27 in terms of X1,X2 and X3. Notice how the WHERE part of the SQL
was written. The brackets were systematically used to enclose the fields used as the
screening criteria. Other parameters needed are concatenated to the Where part
appropriately with provisions for spaces otherwise a syntax error results.
NOTE
It is always necessary to assign contents of numeric fields to numeric variables and then
concatenate it directly to the SQL expression or convert it to string before concatenation.
The fact that the variable is converted to string before concatenation does not translate to
448
mean that the variable could have been declared as string. Doing otherwise could at times
invoke a runtime error due to incorrect SQL syntax.
you can also specify more than one field to break tie in a case where there is a tie in the
First field. For example, the SQL statement in Line 27 of Listing 13.6 can be written as
"Select * From tblDemulsifier Where [" & X1 & "] " & _
X2 & " " & X3 & " ORDER BY [pH] ASC,[HLB] DESC"
Here the sort was based on the [pH] in ascending order and then the HLB field in
descending order. SQL permits you to specify as many sort keys as desired.
NOTE
The DESC keyword is optional when the sort order is descending. However it still
doesnt hurt to include it.
Database Access
449
Another use of the SQL As clause is to perform simple arithmetic on existing fields to
produce other fields. For example to calculate a field defined as
Eo =
3 [ DielectricCons tan t ]
...................................................................................... 1
HLB
450
NOTE
The HAVING Clause is used with SQL Aggregate function to limit records just as the
WHERE clause is used in conventional SQL statement
Problem Set 10
Question 10.1
Add the between operators to Listing 10.6 and modify Figure 10.31 such when the
between operator is selected is selected the width of the Form increase to display two
textboxes used to specify the lower and upper bound needed by the between operator.
Question 10.2
Modify the query in Line 27 of listing 10.6 so that Manufacturers name, Address, Email
and Demulsifiers Tag, Price per Drum for the best 3 Demulsifiers are selected and
displayed. Criteria for Screeening should be Dielectric constant of Demulsifier > a Order
By Efficiency Ratio defined as
E=
P
XD
Database Access
451
Question 10.5
a) A multiple Choice quiz has 50 questions each with four possible answers of which
only one is the correct answer. Design and implement a database program that will accept
students answers and display all the students with Score above the average Score.
Hint: Store students answers on one table and correct answers to that questions on
another table.
b)Repeat Question 10.5a such that three tables are used with students particulars on one
table, students answers on another table and correct answers on the third table.
Appendix A
ASCII Character Codes Chart
Character Set (0 127)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
**
**
**
**
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[space]
!
"
#
$
%
&
'
(
)
*
+
,
.
/
0
1
2
3
4
5
6
7
8
9
:
;
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
`
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
453
Database Access
28
29
30
31
60
61
62
63
<
=
>
?
92
93
94
95
\
]
^
_
124
125
126
127
|
}
~
128
129
130
131
132
133
134
135
136
137
138
139
140
141
160
161
162
163
164
165
166
167
168
169
170
171
172
173
[space]
192
193
194
195
196
197
198
199
200
201
202
203
204
205
224
225
226
227
228
229
230
231
232
233
234
235
236
237
142
143
144
145
146
147
148
149
150
151
152
174
175
176
177
178
179
180
181
182
183
184
206
207
208
209
210
211
212
213
214
215
216
238
239
240
241
242
243
244
245
246
247
248
454
153
154
155
156
157
158
159
128
129
130
185
186
187
188
189
190
191
160
161
162
[space]
217
218
219
220
221
222
223
192
193
194
249
250
251
252
253
254
255
224
225
226
Database Access
455
456
Appendix B
Key Code Constants
Key Codes
Constant
vbKeyLButton
vbKeyRButton
vbKeyCancel
vbKeyMButton
vbKeyBack
vbKeyTab
vbKeyClear
vbKeyReturn
vbKeyShift
vbKeyControl
vbKeyMenu
vbKeyPause
vbKeyCapital
vbKeyEscape
vbKeySpace
vbKeyPageUp
vbKeyPageDown
vbKeyEnd
vbKeyHome
vbKeyLeft
vbKeyUp
vbKeyRight
vbKeyDown
vbKeySelect
vbKeyPrint
vbKeyExecute
vbKeySnapshot
vbKeyInsert
vbKeyDelete
vbKeyHelp
vbKeyNumlock
Value
1
2
3
4
8
9
12
13
16
17
18
19
20
27
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
144
Description
Left mouse button
Right mouse button
CANCEL key
Middle mouse button
BACKSPACE key
TAB key
CLEAR key
ENTER key
SHIFT key
CTRL key
MENU key
PAUSE key
CAPS LOCK key
ESC key
SPACEBAR key
PAGE UP key
PAGE DOWN key
END key
HOME key
LEFT ARROW key
UP ARROW key
RIGHT ARROW key
DOWN ARROW key
SELECT key
PRINT SCREEN key
EXECUTE key
SNAPSHOT key
INS key
DEL key
HELP key
NUM LOCK key
457
Database Access
Constant
vbKeyA
vbKeyB
vbKeyC
vbKeyD
vbKeyE
vbKeyF
vbKeyG
vbKeyH
vbKeyI
vbKeyJ
vbKeyK
vbKeyL
vbKeyM
vbKeyN
vbKeyO
vbKeyP
vbKeyQ
vbKeyR
vbKeyS
vbKeyT
vbKeyU
vbKeyV
vbKeyW
vbKeyX
vbKeyY
vbKeyZ
Constant
vbKeyA
vbKeyB
vbKeyC
vbKeyD
Value
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
Value
65
66
67
68
Value
Description
vbKeyLButton
vbKeyRButton
Constant
Description
A key
B key
C key
D key
E key
F key
G key
H key
I key
J key
K key
L key
M key
N key
O key
P key
Q key
R key
S key
T key
U key
V key
W key
X key
Y key
Z key
Description
A key
B key
C key
D key
458
vbKeyCancel
CANCEL key
vbKeyMButton
vbKeyBack
BACKSPACE key
vbKeyTab
TAB key
vbKeyClear
12
CLEAR key
vbKeyReturn
13
ENTER key
vbKeyShift
16
SHIFT key
vbKeyControl
17
CTRL key
vbKeyMenu
18
MENU key
vbKeyPause
19
PAUSE key
vbKeyCapital
20
vbKeyEscape
27
ESC key
vbKeySpace
32
SPACEBAR key
vbKeyPageUp
33
PAGE UP key
vbKeyPageDown 34
vbKeyEnd
35
END key
vbKeyHome
36
HOME key
vbKeyLeft
37
vbKeyUp
38
UP ARROW key
vbKeyRight
39
vbKeyDown
40
vbKeySelect
41
SELECT key
459
Database Access
vbKeyPrint
42
vbKeyExecute
43
EXECUTE key
vbKeySnapshot
44
SNAPSHOT key
vbKeyInsert
45
INS key
vbKeyDelete
46
DEL key
vbKeyHelp
47
HELP key
vbKeyNumlock
144
Value Description
vbKeyA
65
A key
vbKeyB
66
B key
vbKeyC
67
C key
vbKeyD
68
D key
vbKeyE
69
E key
vbKeyF
70
F key
vbKeyG
71
G key
vbKeyH
72
H key
vbKeyI
73
I key
vbKeyJ
74
J key
vbKeyK
75
K key
460
vbKeyL
76
L key
vbKeyM
77
M key
vbKeyN
78
N key
vbKeyO
79
O key
vbKeyP
80
P key
vbKeyQ
81
Q key
vbKeyR
82
R key
vbKeyS
83
S key
vbKeyT
84
T key
vbKeyU
85
U key
vbKeyV
86
V key
vbKeyW
87
W key
vbKeyX
88
X key
vbKeyY
89
Y key
vbKeyZ
90
Z key
Value Description
vbKey0
48
0 key
vbKey1
49
1 key
vbKey2
50
2 key
vbKey3
51
3 key
461
Database Access
vbKey4
52
4 key
vbKey5
53
5 key
vbKey6
54
6 key
vbKey7
55
7 key
vbKey8
56
8 key
vbKey9
57
9 key
Value
Description
vbKeyNumpad0
96
0 key
vbKeyNumpad1
97
1 key
vbKeyNumpad2
98
2 key
vbKeyNumpad3
99
3 key
vbKeyNumpad4
100
4 key
vbKeyNumpad5
101
5 key
vbKeyNumpad6
102
6 key
vbKeyNumpad7
103
7 key
vbKeyNumpad8
104
8 key
vbKeyNumpad9
105
9 key
vbKeyMultiply
106
vbKeyAdd
107
vbKeySeparator
108
462
vbKeySubtract
109
vbKeyDecimal
110
vbKeyDivide
111
Function Keys
Constant
Value Description
vbKeyF1
112
F1 key
vbKeyF2
113
F2 key
vbKeyF3
114
F3 key
vbKeyF4
115
F4 key
vbKeyF5
116
F5 key
vbKeyF6
117
F6 key
vbKeyF7
118
F7 key
vbKeyF8
119
F8 key
vbKeyF9
120
F9 key
vbKeyF10
121
F10 key
vbKeyF11
122
F11 key
vbKeyF12
123
F12 key
vbKeyF13
124
F13 key
vbKeyF14
125
F14 key
vbKeyF15
126
F15 key
vbKeyF16
127
F16 key
463
Database Access
Appendix C
Derived Math Functions
The following is a list of nonintrinsic math functions that can be derived from the
intrinsic math functions:
Derived equivalents
Function
Secant
Sec(X) = 1 / Cos(X)
Cosecant
Cosec(X) = 1 / Sin(X)
Cotangent
Cotan(X) = 1 / Tan(X)
Inverse Sine
Arcsin(X) = Atn(X / Sqr(-X * X + 1))
Inverse Cosine
Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 *
464
Inverse Secant
Inverse Cosecant
Inverse Cotangent
Hyperbolic Sine
Hyperbolic Cosine
Hyperbolic Tangent
Hyperbolic Secant
Hyperbolic Cosecant
Hyperbolic Cotangent
Inverse Hyperbolic Sine
Inverse Hyperbolic Cosine
Inverse Hyperbolic Tangent
Inverse Hyperbolic Secant
Inverse Hyperbolic Cosecant
Inverse Hyperbolic Cotangent
Logarithm to base N
Atn(1)
Arcsec(X) = Atn(X / Sqr(X * X 1)) + Sgn((X)
1) * (2 * Atn(1))
Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X)
1) * (2 * Atn(1))
Arccotan(X) = Atn(X) + 2 * Atn(1)
HSin(X) = (Exp(X) Exp(-X)) / 2
HCos(X) = (Exp(X) + Exp(-X)) / 2
HTan(X) = (Exp(X) Exp(-X)) / (Exp(X) + Exp(X))
HSec(X) = 2 / (Exp(X) + Exp(-X))
HCosec(X) = 2 / (Exp(X) Exp(-X))
HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X)
Exp(-X))
HArcsin(X) = Log(X + Sqr(X * X + 1))
HArccos(X) = Log(X + Sqr(X * X 1))
HArctan(X) = Log((1 + X) / (1 X)) / 2
HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)
HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +
1) / X)
HArccotan(X) = Log((X + 1) / (X 1)) / 2
LogN(X) = Log(X) / Log(N)
Index
Bold, 245
A
ABS, 90
Abscissa, 397
Absolute, 47, 90
Ackerman, 177
Add Procedure dialog, 333
Addition, 84, 85, 88
Align, 22, 122
Alignment, 76, 246
ANSI, 275, 554
Appearance, 12, 76
Arrays, iv, v, 199, 200, 201, 202,
214, 254
ASC, 275, 276, 278, 288, 290, 291,
539, 547
ASC function, 275, 276, 278, 288,
291
ASCII, vi, xi, 100, 241, 275, 276,
277, 278, 279, 288, 290, 291, 296,
314, 316, 322, 542, 552, 559, 561
ASCII Code, xi, 276, 278
Associativity, 88
atm, 47, 109
ATN, 90
Attribute, 505
Automation, ix, 439, 441, 446, 455
B
BEDMAS, 88
466
467
Database Access
Dates, 79
Day, 92
Debug, 13
Decision Statement, iv, 155
Default, vii, 18, 19, 27, 41, 72, 77,
468
469
Database Access
548
File, 20, 43, 195, 196, 259, 365, 509,
522, 523, 531
Find, xi, 43, 297, 513, 514, 516
FIX, 90
Flow chart, 129, 131, 134, 152, 167,
169, 171, 172
Folder, 20, 522, 523
Font, v, 12, 105, 245
For Loop, 164
Foreign key, 521
Form Window, 4, 9, 166
Format Currency, vi, 301
Formatting, i, v, vi, 22, 245, 247, 248,
301
Frame, i, 16, 23, 24
G
Gas, 47, 72, 109, 193, 243, 401, 402
GotFocus, 100, 122, 269, 270
Graphics, 20, 25
Greater Than, 87
Grid, v, 17, 42, 82, 237, 239, 240,
Icon, 227
George Bool, 68
Join function, 282, 288, 289
K
470
471
Database Access
Metafiles, 20
Method, v, ix, 108, 109, 241, 330,
O
Object, ii, iii, vii, viii, ix, xi, 61, 62,
472
PlaceHolder, 41
Polynomial Interpolation, ix, 454,
486
Precedence, 87
Pressure, 47, 55, 56, 109, 191, 192,
257, 258, 261, 368, 390, 399, 401
Primary Key, 521
principle, 56, 59, 188, 211, 288, 350,
377, 468, 476, 498, 505
Print, ii, 23, 24, 82, 346
Processing, iii, 61, 84
Project, i, 7, 13, 14, 34, 58, 93, 95,
Qbasic, 79
Quadratic, 115, 149, 185, 362, 363
Quadratic Equation, 185
Quarter, 92
Queries, 538
Query, 309, 504, 538, 542
473
Database Access
R
R, 47, 109, 110, 125, 175, 177, 179,
368, 383
Select case, iv, 147, 150, 152, 153,
154
Selected Property, v, 231
Selection, v, viii, ix, 231, 400, 420,
474
V
Validate, vii, 100, 122, 319, 320
Validate Event, vii, 122, 319
Validation, 262, 314, 402, 519, 525
value, 4, 11, 26, 27, 28, 34, 45, 48,
475
Database Access
X
XY Scatter, 435
Y
Year, 92, 516