You are on page 1of 503

Visual Basic 6.

0
For
Engineers and Scientists

Visual Basic 6.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

This book is dedicated to


My Father
Mr. Thompson Itua Egbe
and my Mothers
Mrs. Mary T.I.Egbe
And
Mrs. Elizabeth T.I.Egbe

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

1. Elements of User Interface Design

2. Visual Basic Programming Fundamentals

48

3. Control Structures

96

4. Data Structures

155

5. String Arithmetic

211

6. Functions and Sub Procedure

265

7. Controls Array

300

8. Visual Basic for Applications

330

9. Numerical Applications

374

10.

414

Database Access

Appendix A KeyAscii and KeyCode Constants

453

Appendix B Derived Maths Functions

463

Appendix C Saving and Opening Visual Projects

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Changing Object Properties in Event Procedure .......................................... 78


Read Only Properties .................................................................................... 80
Modifying the Caption and Text Properties in Event Procedures using
Variables ....................................................................................................... 80
Scope of Variables ............................................................................................ 84
Procedure Level Variables ............................................................................ 84
Static Variables ............................................................................................. 84
Module Level Variable ................................................................................. 85
Public Variables ............................................................................................ 86
Programming Accessories ............................................................................... 87
Comments ..................................................................................................... 87
Line Continuation ......................................................................................... 87
Line Termination .......................................................................................... 88
Line Numbers/Label ..................................................................................... 88
With Block .................................................................................................... 89
Multiple Forms Applications ........................................................................... 89
Problem Set 2 ................................................................................................... 93
3.

Control Structures ....................................................................................... 97


Decision Structures .......................................................................................... 98
IF Then Else Structure .................................................................................. 98
The Else If Statement .................................................................................. 100
Constructing Boolean Expressions .................................................................. 105
Nested If Structure ...................................................................................... 108
If Then End If Structure .............................................................................. 110
Select Case Structure .................................................................................. 112
Nested Select case Structure ....................................................................... 116
Decision Statements ....................................................................................... 118
If Then Statement. ....................................................................................... 119
If Then Else Statement ................................................................................ 119
Decision Functions...................................................................................... 119
IIF Function ................................................................................................ 120
Switch Function .......................................................................................... 120
Choose Function ......................................................................................... 121
For Next Loops ....................................................................................... 123
Do Loops ................................................................................................... 127
Pre-checked Do Loop .................................................................................... 127
Post Checked Do Loop .............................................................................. 130
Solving Problems with Do Loops ............................................................... 132

iv

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Recursive problems ..................................................................................... 132


Number Base Conversions .......................................................................... 135
The Exit Statement...................................................................................... 137
The Go To Statement .................................................................................. 138
Nested Loops .............................................................................................. 138
Dynamic Interface Design .......................................................................... 139
Problems Set 3 ................................................................................................ 146
4.

Data Structures .......................................................................................... 155


Arrays ............................................................................................................. 156
Declaring an Array...................................................................................... 157
Declaring Dynamic Arrays ......................................................................... 157
Array Transfer ............................................................................................. 158
Transfer to a scalar variant variable using the Array Function .................. 160
Array Arithmetic ......................................................................................... 161
Array and Summation ................................................................................. 162
Sorting an Array.......................................................................................... 163
Bubble Sort ................................................................................................. 163
Searching an Array ..................................................................................... 165
Ranking an array ......................................................................................... 166
Lists ................................................................................................................. 168
Inserting Items into a List at Design time Using the Properties Window .. 169
Inserting Items into a List at Run time Using the AddItem method ........... 169
Inserting Items into a List at Run Time Using the ...................................... 170
Working with the ListItems using the ListIndex Property ......................... 171
Copying Items from a ListBox Using Drag-Drop ...................................... 179
Sorting Data in a List using the Sorted Property ........................................ 180
Synchronising a Sorted List Using The ItemData Property....................... 180
Selecting Multiple Items from a list............................................................ 182
Manipulating Multiple Selection Using the Selected Property................... 183
Grids ............................................................................................................... 186
Adding the FlexGrid controls to the ToolBox. ........................................... 188
Understanding Basic Properties of the Grid ............................................... 189
Entering and Retrieving Data in Grids........................................................ 189
Using the TextMatrix Property ................................................................... 190
Using the Text Property .............................................................................. 191
Using the AddItem Method ........................................................................ 192
Using the TextArray Property..................................................................... 193
Using the ClipBoard/Clip Property............................................................. 195

Contents

Formatting Cells.......................................................................................... 197


Changing the Font Properties...................................................................... 197
Cell Alignment ............................................................................................ 198
Formatting a range of cells ......................................................................... 199
Merging cells .............................................................................................. 200
Sorting Data in Grids .................................................................................. 202
Data Files ....................................................................................................... 203
Writing /Reading Arrays/ListItem To files. ................................................ 205
Problem Set 4 ................................................................................................. 206
5.

Strings Arithmetic ..................................................................................... 212


String Operators ............................................................................................. 213
Concatenation Operator .............................................................................. 213
Like Operator .............................................................................................. 214
Option Compare Statement............................................................................ 216
Option Compare Text ................................................................................. 217
Option Compare Binary .............................................................................. 217
String Functions ............................................................................................ 217
Val Function............................................................................................... 217
Cstr, Str, Str$ Functions .............................................................................. 218
Len Function ............................................................................................... 218
Ltrim, Rtrim and Trim Functions................................................................ 219
Rtrim Function ............................................................................................ 220
Trim Function ............................................................................................. 220
Simple Application ..................................................................................... 220
UCase, LCase and StrConv Functions ........................................................ 222
ASCII Functions ........................................................................................ 222
The KeyPress Event .................................................................................... 224
String function ............................................................................................ 226
Split and Join Functions .............................................................................. 227
The Mid Function ....................................................................................... 229
Converting Numbers to Base 10 ................................................................. 230
Hexadecimal Numbers ................................................................................ 232
StrReverse Function .................................................................................... 232
Private Sub cmdExecute_Click() .................................................................... 233
The Mid Statement ...................................................................................... 234
Encryption and Decryption ......................................................................... 234
Instr and InstrRev Function ....................................................................... 236
The InstrRev Function ................................................................................ 237

vi

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Left and Right Function .............................................................................. 240


Converting Numbers with Decimal Part to Fraction .................................. 242
Replace function ......................................................................................... 242
Working with fractions ............................................................................... 243
Decimal and Binary Shifting ...................................................................... 243
Scientific Notation ...................................................................................... 244
Formatting Output ......................................................................................... 244
Format Currency Function .......................................................................... 245
Format Percent Function ............................................................................. 246
FormatNumber Function ............................................................................. 246
FormatDate Time Function ......................................................................... 247
Round Function ........................................................................................... 248
Format Function .......................................................................................... 248
Customizing The Format Function ............................................................. 249
Message Box ................................................................................................... 250
Message Box Buttons ................................................................................. 251
Message Box Icons ..................................................................................... 251
Using the Message Box as a Function ........................................................ 252
Controlling The Default Button .................................................................. 254
Message Box with Optional Arguments .................................................... 254
String Functions and the Message Box Message........................................ 255
Input Validation and Errors .......................................................................... 255
Data Inspection Functions........................................................................... 257
Input Validation using the Validate Event .................................................. 260
Problem Set 5 ................................................................................................. 261
6.

Functions and Sub Procedures ................................................................. 266


Creating Functions ........................................................................................ 267
Function Definition .................................................................................... 268
Implementation of Function in Visual Basic .............................................. 269
Writing Programs with User Defined Functions ........................................ 272
Using the ByVal and ByRef Keyword........................................................ 273
Functions With No Argument ..................................................................... 275
Functions With One Argument ................................................................... 275
Functions with two Argument .................................................................... 276
Functions with three Arguments ................................................................. 278
Functions With Indefinite Arguments ........................................................ 278
Functions with Optional arguments ............................................................ 279
Functions with Array As Argument ............................................................ 282

Contents

vii

Functions Which Return Array ................................................................... 283


Functions with Object as Argument/Return Type ...................................... 284
Recursive Functions .................................................................................... 288
Sub Procedures .............................................................................................. 290
Passing Objects To Sub Procedure ............................................................. 292
Returning Multiple Values From A Sub Procedure.................................... 293
Event Sub Procedure ..................................................................................... 295
Sub Main ..................................................................................................... 295
Problem Set 6 ................................................................................................. 298
7.

Controls Array .......................................................................................... 300


Creating Controls Array ................................................................................ 301
Creating controls array using copy and paste method ................................ 301
Creating controls array using the Index property ....................................... 302
Creating controls array using the Name property ....................................... 302
Event Procedures of Controls Array ........................................................... 302
Properties of Controls Array ....................................................................... 304
Creating Elements of Controls Array at Runtime ....................................... 305
Unloading controls array Elements at runtime ........................................... 306
Giving Controls Array Element Equal Spacing .......................................... 307
Array of TextBoxes ........................................................................................ 311
Array of ListBoxes ........................................................................................ 315
Array of Grids................................................................................................. 318
Array of PictureBoxes ................................................................................... 319
Array of Lines................................................................................................. 324
Problem Set 7 ................................................................................................. 326

8.

Visual Basic for Applications ................................................................... 330


VBA Functions ........................................................................................... 330
VBA and OLE automation.......................................................................... 330
Overview of MS Excel .................................................................................... 331
Window showing Excel cells ...................................................................... 331
Filling formulae in cells .............................................................................. 333
Plotting Graphs ........................................................................................... 333
Using Excels Functions ............................................................................. 337
Working with Array Functions ................................................................... 338
VBA Functions............................................................................................... 340
Worksheet and VBA Functions ..................................................................... 342
Writing VBA Functions with Indefinite Arguments .................................. 343

viii

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

VBA Collections ............................................................................................. 343


Methods of the Range/Selection Object ..................................................... 345
The Selection Object ............................................................................. 346
Reading and Writing from Selections ......................................................... 346
Selection Object .......................................................................................... 346
The Cells Property ...................................................................................... 347
Offset Method ............................................................................................. 349
VBA Dialog Boxes ......................................................................................... 350
Figure 8.14.................................................................................................... 352
Figure 8.16.................................................................................................... 354
Listing 8.6: Evaluating Functions at runtime.................................................... 354
Macros ............................................................................................................ 355
Using Recorded Macros .............................................................................. 358
Recording a Graph Macro ........................................................................... 358
VBA and OLE Automation ............................................................................ 362
Visual Basic, VBA , OLE Automation and OLE Control ........................ 367
Adding the OLE Control to the Form ......................................................... 367
Problem Set 8 ................................................................................................ 370
9.

Numerical Applications ............................................................................ 373


Evaluation of Functions at Runtime ............................................................. 374
Evaluating Functions at Runtime using Strings .......................................... 374
Excel Application object ............................................................................. 374
Using Script Control ................................................................................... 377
Using Function Box .................................................................................... 379
Non Linear Equations. .................................................................................. 379
Numerical Differentiation ............................................................................. 384
Numerical Differentiation with Discrete points .......................................... 386
Numerical Integration ................................................................................... 389
Multiple Integrals ........................................................................................ 394
Polynomial Interpolation ............................................................................... 398
Lagrange Interpolation.......................................................................... 399
Divided Difference Interpolation ................................................................ 402
Introduction to Matrix Algebra ..................................................................... 407
Using Excel Functions to Evaluate Matrices .............................................. 407
Problem Set 9 ................................................................................................. 409

Contents

ix

10. Database Access ......................................................................................... 413


Data Control ................................................................................................... 415
Creating a Simple Database Application .................................................... 416
Displaying Multiple Records In Bound Controls ...................................... 419
The Recordset Object ..................................................................................... 421
Find Methods .............................................................................................. 421
Types of RecordSet ..................................................................................... 424
The Visual Data Manager ............................................................................. 424
Relationships ............................................................................................... 425
Adding Records to Tables Using Visdata ................................................... 435
Manipulating Records in Visual Basic with Visdata Data Form Designer 437
Structured Query Language .......................................................................... 440
Data Manipulation Language Queries ........................................................ 440
Using the Select and From clauses to designate a Recordsource in code ... 441
Using the SQL Where Clause ............................................................. 442
Specifying Multiple Criteria With the Where Clause ................................ 444
Visual Basic Data Applications ..................................................................... 445
Using the SQL Order By Clause................................................................. 448
Using the SQL As Clause ........................................................................... 448
Using the SQL Aggregate Functions .......................................................... 449
Problem Set 10 ............................................................................................... 450
Appendix A: ASCII Code Constant ................................................................ 452
Appendix B: Key Code Constant..................................................................... 456
Appendix C: Derived Maths Functions .......................................................... 463

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Visual Basic Controls In Windows Applications


One of the most familiar windows in the system is the shut down windows of windows
98. The shut down window is shown in Figure 1.1

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Height: The vertical height of the object


Width:

The width or breadth of the object

Left:

The horizontal distance from the left edge of the form to the left edge of the
object.

Design Fundamentals

VISUAL BASIC IDE


Its high time we started using Visual Basic so that we can see the object physically and
visualize their properties. We will take the next few steps and show us how to launch the
Visual Basic Integrated Development Environment(IDE)

FIGURE 1.3
Visual Basic
Project dialog

new

1.

After installing Visual Basic in your system, you open it as follows:


Select Start Menu, Programs, Microsoft Visual Studio, Microsoft Visual Basic (or
select the Visual Basic icon from the desktop or office shortcut if you have created
it)

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

FIGURE 1.4
Visual Basic
Integrated
Development
Environment

Menu
Bar

Tool Bar
Tool Box

Form Layout Window


Project Explorer Window

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Properties in the properties windows are arranged either alphabetically or in categories.


Figure 1.6 shows the properties windows with form properties arranged alphabetically.
You change a property by selecting the property and modifying the default(or present)
value at the right hand side of the property(property value). Property values can be
changed in one of four ways. These are discussed below
1. By selecting the property and then typing the property value yourself with the
keyboard. A typical property that is changed in this manner is the height property.

2. By selecting the property and modifying the property by selecting an applicable


named constant from the drop down list of the property value region. A typical
property that can be changed in this manner is the border style 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

Common categories are: Appearance, Behavior, Data, DDE, Font, Miscellaneous,


Position and Scale. Some of these categories are absent in some controls. E.g for the
intrinsic controls only the Picture Box has the scale category. Properties in this category
are scaleheight, scaleleft, scalemode, scaletop and scalewidth. The font category has
only one property which has other properties and is set using the font dialog.

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.

Debug tool bar

4.

Form Editor Toolbar

10

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Naming Visual Basic Controls.


Before designing program interfaces with Visual Basic controls, it is important that we
know the convention used to name Visual Basic controls. The name of a control is what
Visual Basic uses to interact with the control. The name of a control is not always visible
to the user like the caption or the text, it is used internally to manipulate a control. The
prefixes used to name some of the Visual Basic controls are as shown in Table 1.1
Table 1.1 Prefixes used in naming Visual Basic controls.
S/No

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

Vertical Scroll Bar

vsb

27

UpDown Control

upd

13

Horizontal Scroll Bar

hsb

28

Slider

sld

14

OLE

ole

29

Script Control

sct

15

ComboBox

cbo

30

Grid Control

grd

Valid control names using these prefixes are cmdExecute,sctFunction, chkIgnoreError,


optKelvin, txtInput. Others are mnuFile,frmMain,lblResults.

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

Visual Basic Units Of Measurement


The importance of units in science and engineering can not be over emphasized. A
length measured as two(2) makes no sense becomes it is meaningless. It could be 2 cm or
2 km or even 2 miles. For this reason, it is important that we understand the various unit
systems used to measure length and how to set these unit systems using the properties
window. To change a unit system, we use the scale mode property of the form. The
various settings for the scale mode property is as shown in Table 1.2.
Table 1.2: Setting for the Scale mode property
Constant
Setting
0
vbUser

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Designing program interface.


In order to get used to Visual Basic controls and of course their names , we will take
some time and design some of the windows found in common windows applications
We will start with the shut down window of Figure 1.1
To design the shut down window, follow the steps outlined below.
1. Start a new Visual Basic Standard Exe project and arrange your windows as shown in
Figure 1.4
2. Use the properties window to change the following properties of the form

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.

Bring three command buttons and arrange them as in Figure 1


Command Button 1: Name cmdOK, Caption OK , Default True
Command Button 2: Name cmdCancel, Caption Cancel , Cancel True
Command Button 3: Name cmdHelp, Caption - &Help

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

Visual Basic load


picture dialog used
to assign bitmap to
controls with
picture and icon
properties

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Designing Windows Interface Using Visual Basic


Controls
We are going to continue our exercise on user interface design by designing some of the
dialog boxes used in Microsoft application and other software developed by third parties.
This will help to introduce the controls step by step and also get us used to how to name
the controls and functions of the controls.

Introducing the Combo Box And Frame


FIGURE 1.12
Visual Basic Print
Setup Dialog Box

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

9. Press F5, your Design is now being viewed at Run Time

Design Fundamentals

19

Introducing The Line control, Checkbox control and


Picture box control
We are going to introduce three new controls from the toolbox. These are controls in the
Paste Special dialog box of Microsoft Excel. The Controls on the Paste Special Dialog
box are Line control, Label control, option button control , command button control and
Check Box control. The New controls on the form are the Checkbox Control, the Line
control and the Picture box control. See Figure 1.13

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Name: chkSkipBlank Caption : Skip Blank


Name: chkTranspose Caption: Transpose

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.

Introducing The Text Box and the Vertical Scroll Bar


The text box control is one of the most important controls in the tool box. The text box is
used to display textual information just like the label control. However, unlike the label,
the information displayed by the textbox can be edited. This makes the textbox a general
purpose input/output control. In most applications you find the textbox as the input
control with the label at the left hand side of the textbox describing the input expected
from the user. Figure 1.14 shows a data form dialog box from Microsoft Excel with five
text boxes and one vertical scroll Bar. Other controls on the form are the seven command
button controls and one label. The vertical scroll bar is also used to display information to
the user but this information are usually pre-programmed information and can not be
edited. Most times the vertical scroll bar is used to enter input in text boxes and labels.
Some important properties of the vertical scroll bar are the value property, the
Minchange, the Maxchange, min and max properties. Use the tool tip to identify the
vertical scrollbar in the tool box and draw an instance of it on the form. Use the format
menu to configure your interface as in Figure 1.14

21

Design Fundamentals

FIGURE 1.14
Visual Basic controls
used in MS Excel
Data Form dialog

Introducing the horizontal scroll bar


Instances of the horizontal scroll bar in office applications are not common. However,
an instance of it was used in MS Office format picture dialog (See Figure Q1.4b )

Introducing the list box


The list box is a general-purpose control used in windows application. It is similar to the
combo box in that it holds a list of options. Unlike, the combo box the list box shows the
items in the list. If the items in the list are more than the height of the list, a scrollbar
comes up which is used to scroll up or down the list so that selection can be made. Figure
1.15a and b show the list box control. The scroll bar can be horizontal or vertical
depending on the setting of the column property. If it is set to 0 it means you want the
scroll bar to be vertical and if it is set to 1 you want the scroll bar to be horizontal.
Generally, setting the column property to n (where n >=1) causes the scroll bar to be
horizontal with the items in n columns. The load picture dialog shown in Figure 1.15a
contains a list box with columns > 0.

FIGURE 1.15 (a)


MS Excel Date and
Time dialog showing
an instance of the list
box control
(unchecked style)

(a)

22

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

FIGURE 1.15 (b)


MS Excel Add-Ins
Dialogue showing
another instance of a
list box control
(checked style)

(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

Introducing the Data Control


Figure 1.17 shows a Visual Basic form showing the data control. This control is only
common in MS Access application.

FIGURE 1.17
User application
showing the Visual
Basic data control

Data control

Other intrinsic controls


So far we have considered thirteen out of the twenty intrinsic controls found in the tool
box. Controls that have not been considered are the horizontal scroll bar, timer, shape,
OLE, and the file controls(DirListBox,FileListBox and DriveListBox). This controls are
as shown in Figure 1.18

24

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

DriveListBox

FIGURE 1.18
User form showing
other intrinsic
controls

FileListBox

DirListBox

Shape Control

HorizontalScrollBar

OLE (Object Linking


and Embedding)

Interface Design with Windows Common


Controls.

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.

Adding the Microsoft Windows Common Control to the


ToolBox.
The steps used to add the Microsoft windows common controls to the toolbox are as
follows
1. Select [Components] from the [Project] menu. The component dialog box appears
as shown in Figure 1.20

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Configuring the Tabstrip Control


Figure 1.22a and b show the tab strip control on the Form. In Figure 1.22a the tab strip
control is smaller while it was adjusted to get the orientation of Figure 1.22b. Usually, we
use the property pages to change the properties of windows common controls instead of
using properties window.

FIGURE 1.22 (a)


User form showing
the tap strip control

(c)

FIGURE 1.21 (b)


User form showing
the tap strip control in
expanded form

(b)

Design Fundamentals

27

The Property Pages


Properties of windows common controls are usually changed using property pages. To
activate the property pages, right click anywhere on the tab strip control and select
properties from the pop up menu. This opens the property pages of the tab strip control as
shown in Figure 1.23. To add tabs to the tab strip control , activate the tabs tab and type
View in caption text box and click Apply. Insert more tabs and give the created tabs
appropriate captions. Click OK when done.

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.

Configuring the UpDown Control


The Updown control is part of the Microsoft windows common controls. Configuring the
updown control for use is simple relative to the tab strip control and other windows
common control. It is commonly used to increment values in text boxes but could be
used in other controls apart from the text box. Using the Updown control involves
drawing the control on the form and setting the following properties

28

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Configuring the Toolbar Control


The tool bar control is very common in windows applications and is used to provide
quick access to the commonly used functions in a program. Most applications developed
today have the standard toolbar with familiar images used for related functions. Figure
1.24 shows the standard toolbar of Visual Basic.
Figure 1.24
Visual Basic standard
Tool bar

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

Adding Images to the Toolbar Control.


Images are added to the tool bar control using the image list control. This control is
invisible at run time and is a repository for the tool bar images. The image list control is
part of the windows common control group. You add the windows common control to
your application by drawing an instance of it on the form. Images are added to the image
list control the same way buttons are added to the tool bar control or tabs are added to the
tab strip control. As usual, open the image list property pages by right clicking the image
list control and selecting properties from the pop up menu. Use the path used to add
images to the image control to add images to the image list control.
Close the property pages of the image list control and then open that of a toolbar control
on the form. Under the General tab, select the image list combo and set Buttons tab, type
1 on the image textbox and click apply so that image #1 in the image list control would
be added to the present tool bar button. Click the index up down control to move to the
next(or previous) button so that you can assign appropriate images to the button. Repeat
this until you have added images to all the buttons.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

A Closer Look at the Toolbar Buttons


You configure the tool bar by manipulating the property pages of the tool bar control.
Essential properties of the buttons are the key property, caption property, image
property, tag property and the style property . The key property is used to specify the
name of each button while the image property is used to retrieve an image from the image
list control associated with the tool bar control. The style of a tool bar button defines the
appearance and behavior of the button. Generally, in all tool bar controls, there are six
styles supported by the buttons. These include
1. Default
2. Check
3. Button-Group
4. Separator
5. PlaceHolder
6. DropDown
Default: This is the standard style for most buttons in the tool bar control. They are used
to launch tasks like opening dialog boxes and executing actions. Examples of buttons
with default buttons style are the save button, open button, cut, copy etc.(see Figure 1.26)
Check: The check style is like an on/off style used to turn a feature(or option) on or off.
Examples of the check button style are the bold, underline and italics buttons in the
formatting tool bar of MS Word. Here, a buttons appearance indicates the status of the
option. The status of the bold button is used to indicate whether bold option has been
turned on or not. This also applies to the underline and italics buttons.(see Figure 1.26)
PlaceHolder: Buttons with this style are commonly used to host other controls like
command buttons and combo boxes. Example is the font Size and font name button of the
formatting tool bar in MS office applications.
ButtonGroup: This is similar to the check style in that it indicates the status of an
option. However, it applies to more than two options unlike the check style. Here the
options are in a mutually exclusive group. An example is the alignment and
bullets/numbering buttons.
Separator: Buttons with separator style are used to separate one button(usually of
another style) from the other.

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

Other Controls from Components


Visual Basic ships with scores of controls for developers to use in application
development. Some of these controls include the chart control, the grid controls and
calendar/date controls. Others include the slider, the common dialog and the Kodak
imaging controls. Many others exist and will be mentioned in subsequent chapters of this
book. Some of these controls are drawn in Figure 1.27
These controls are basically input/output controls. Figure 1.27 shows some of these
controls. The controls on the form are the chart control, the Grid control, the Slider
control the month view and the Status bar control.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

FIGURE 1.27

MS flex grid

User form showing


other controls from
components

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

FIGURE 1.28 (a)


Visual Basic Menu
Editor used in
creating menus and
popup menus

FIGURE 1.28 (b)


Menu created by the
menu editor of Figure
1.28 (a).

Notes on Menus/Menu Editor


1. Menus created must have a Name and a Caption
2. No two menu items must have the same name( exceptions will be discussed
subsequently)
3. You can assign short cut keys to menu items using the short cut keys combo box.
4. Short cut keys must not be assigned to top level menus.
5. Menu item can be made checked/unchecked, visible/invisible, enabled/disabled by
toggling the state(value) of the applicable check boxes.
6. The first two arrow command buttons are used to convert top level menu items to
sub menu or vice versa.
7. The last two arrow command buttons are used to move menu item up/down.

34

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Designing Your Own Application.


Most applications written by beginners in Visual Basic must require input from users
and must produce output based on the users input and programmers instructions.
Input/Output programs are relatively easy to implement using Visual Basic. As you must
have learnt, text boxes are used as the general purpose input controls while the labels are
used to annotate text boxes and to display results from calculations(or input processing).
Command buttons are also used in input/output programs to trigger actions such as
Calculate, Execute, Convert, Clear, Exit etc.
We now demonstrate how to use instances of the text box, the label and the command
buttons to implement a simple input/output program. Our example will be to design a
user interface that will be used to determine the number of moles of an ideal gas given its
pressure, volume and temperature (PVT properties) using the Van-der Waal equation of
state. This is defined mathematically as

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

User Interface for


the Van Der Waal
prob lem

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Final user interface


for the Van Der
Waal Problem with
controls annotated
and units specified

Other Input Controls


You have designed windows interfaces with option buttons and combo boxes and
probably you are not aware that they are input controls. The option buttons and combo
boxes are used as input controls when users input can be anticipated or when the
programmer wants to restrict users input to only those considered by his application. We
demonstrate the advantages of the option buttons over the text boxes with a simple
program for temperature conversion. The application involves four units of temperature;
Kelvin, Fahrenheit, Rankine and Celsius. A user is expected to input the value to be
converted, the input unit and the output unit. He then clicks convert so that the input will
be converted from the unit specified to the desired output unit. An interface for this
problem is as shown in Figure 1.32

Design Fundamentals

37

FIGURE 1.32

User interface for a


temperature
conversion problem

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Occupies so much space on the form

The Combo Box


The combo box or drop down box serves the same purpose as the option buttons. It is
used to select an option from a list. It has an advantage over the option button in that it
can handle more units and yet occupy much less space on the form than the option
buttons. It displays items in the box in three styles. These include

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

FIGURE 1.35 (a)


User friendly
interface for
temperature
conversion using
simple combo boxes
as input control for
temperature units.

FIGURE 1.35 (b)


User friendly
interface for
temperature
conversion using
dropdown combo
boxes as input control
for temperature units.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Enhancing the Van Der Waal Problem.


In the Van Der Waal problem of Figure 1.31, suppose a user(say Mr. A) wants to
calculate n (number of moles) and has pressure in kpa, volume in cubic centimetres and
temperature in fahrenheit. Also another user ( say Mr. B) wants to calculate n with
pressure in mmH2O, volume in cubic decimetres and temperature in Rankine (oR), can
your program handle this? Of course no!. Your users have to run to their bags and get
their calculators and conversion tables to change their pressures to Pascal, volumes to
cubic metres and temperatures to Kelvin. Imagine that this task could be more difficult
than getting n. So if your user could do their conversions themselves they could as well
calculate n (number of moles) and hence avoid using your program.
To develop a good program, you have to be open to every body, your program should
satisfy any user irrespective of his situation. You have to include controls that will enable
your program change face based on the requirements of different users. One of such
controls is the combo box. For our program to handle the scenario above, we need three
combo boxes, one that will contain all the commonly used units of volume and the other
two for temperature and pressure. The user can at run time drop the combos and select
his/her units for volume, pressure and temperature and then calculate n without external
dependencies. An improved design for this problem is as shown in Figure 1.36

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.

Generalized Conversion Program


You can create a generalized conversion program consisting of several quantities
like volume, pressure, mass, time etc. The same interface as that of Figure 1.35 is
required but in addition we need to introduce toolbars or menus to handle the other
quantities. The tab strips and combo boxes can also be used to handle the program. The
execute command can be assigned to tool bars in addition to other formatting options.
Figure 1.36 shows a simple application with the menus and toolbars

FIGURE 1.37
User interface for
conversion problem
using standard
controls and
Windows common
menu and toolbars

42

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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)

Design the format picture dialog shown below.

Figure Q1.4b

46

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Body starts from rest

Assume S.I. Unit system only


b) Extend the capabilities of questions 1.9 by including combo boxes so that units
difference could be handled.
Question 1.10
The friction factor for single phase Laminar flow in pipe is evaluated using the
following relationship
f=16/Re
for laminar flow
Using as many controls as possible, design the interface needed for this problem.
Hint; Re = ud/. Consider navigational design.
Question 1.11
Given the design shown in Figure Q1.11 used for number base conversion
(a)
Comment critically on the design
(b)
Discuss ways in which the design could be improved.
(c)
Based on your points in a above, implement an improved design of the interface
Figure Q1.11

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.

Setting Objects Property Using Code


At design time, properties of objects are set using the Properties Window. To set an
objects width to 1000 at design time, you select the object in question, and scroll to its
width property and change (over write) its width property value to 1000. However, in
code, you can accomplish the
above task with the assignment statement
frmmain.txtResults.Width=1000.
The statement above means you should change the width property of txtResults in
frmMain to 1000. Table 2.1 summarizes the similarities of the two methods.(setting
object properties with code and with the properties window)
Table 2.1: Properties window versus code
Design time

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

Select (or type) the designed object


and press dot. On pressing dot, you
observe that all the properties of the
object appear.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic Data Types


Typically, computers are defined as electronic machines that accept and process data
according to some embedded instructions and subsequently output data. This definition
underscores the importance of data in the computer world. Instructions used to process
data vary with the type of data. For example, the data 2 and 3 when added gives 5.
However, at times the result might be 23. The result actually depends on how the data 2
and 3 are stored. This actually shows that data are not limited to the numeric types in
Visual Basic as well as other programming languages. Figure 2. 2 shows the available
data types supported by Visual Basic

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Byte Data Type

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

Integer Data Type


In Visual Basic context, a data is said to be an Integer if it is a whole number within the
range of 32768 to 32768 . Integer data occupy two bytes of memory resource

Long Data Type


These are Long Integers and hence have wider range. Long data types are whole
numbers which fall within the range 2147483648 to 2147483647. Like the Byte and
Integer data types, floating and exponential numbers can not as a rule be long data type.

Single Data Type


Floating numbers of the form 2.3, 6.8, -3.4256 and Exponential numbers of the form
2.3E02, 6.4E-03, -4.6E34 are regarded as single data types. The range of single data type
is -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to
3.402823E38 for positive values. The implication of the range specification is that,
floating or exponential numbers greater that 7 decimal places and above the bounds
specified above can not be regarded as single data types.

Double Data Type


Double data type is usually regarded as the super set of the Single data type in that all
single data are also double data. However, Double can take numbers up to 15 decimal
places and has the range -1.79769313486232E308 to -4.94065645841247E-324 for
negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive
numbers.

Currency Data Type


All the numeric data types mentioned earlier have at most 10 digits to the left of the
decimal point. This is actually a big constraint when dealing with money. For e.g. the
data 21489219861894.25 can not be stored as it is as single or double, hence, they will be
converted to scientific notation(Exponential point number) before storage which is an

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

String Data Type


Figure 2.2 clearly shows that strings are non-numeric data types. Names of persons,
places, texts, units of measurement etc are all examples of string data types. String data
are always written between quotes as follows: Ugep, Ikwerre, m/s, Kelvin,
200. Given the data
(a) 1274936
(b) 1274936
(a) is a number (long data type) while (b) is a string.

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.

Date Data Type


Date values can range from 1/1/100 to 12/31/9999. Usually, Visual Basic requires that
date values be placed between hashes (#). E.g of dates are #2/3/2000#, # 12/29/1980#.
When date values are expressed as fractions, the values to the left of the decimal
represent the dates while the values to the right represent the time.

54

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Boolean Data Type


This data type was named after James Bool, father of Boolean Algebra. Boolean values
are basically True/False values; 1/0; Yes/No, On/Off. They are actually two state values.

Variant Data Type


This data type is locally called all weather. All the preceding data can also be regarded
as variant data types. They can be numeric or non numeric. This data type has great
applications when working with arrays and strings.

Object Data Type

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.

Other Data Types


The data types discussed above are not exhaustive. Other data types like user defined
types and Object types exposed by other application also exist. These would be
mentioned at the appropriate time.

Variables And Constants


We have taken time to discuss data types because they are actually very important in
effective program management. Usually, data passed to the system are stored in variables
or constants before being processed. Variables are named area in the memory where data
that can be modified during program execution are stored. On the other hand, Constants
are named area in the memory where data that can not be modified during program
execution are stored. There are as many types of Variables/Constants as there are data
types. Integer data are stored in integer variables, while double data are stored in double
variables. This also applies to constants

55

Programming Fundamentals

Storing Data In Variables/Constants


Before any data can be stored in a variable/Constant, Visual Basic requires that the
variable/Constant be explicitly declared. Declaring a variable means specifying the
variable name and the variable type. A typical variable declaration takes the form.
Dim strGrade As String
When the statement is written in Visual Basic Form module, three of the four words that
make up the declaration would be Blue(This depends on the setting on the option dialog).
These coloured words are called keyword that are used in variable declarations and are
shown in bold face. The Dim keyword is used to inform Visual Basic that what follows is
a variable while the As keyword tells Visual Basic that what follows is the variable type.
In the declaration strGrade is the variables name. Visual Basic often flag errors when the
data type specified is different from those stated in Figure 2.2 (or other user defined types
and instances of known classes). Constants are also declared in much the same way. A
typical constant declaration takes the form
Const Pi As Double = 22 / 7
Or simply as
Const Pi = 22 / 7
The variable/constant names must obey some set of rules. These are
(a) Must begin with an alphabetic character
(b) Must not be any visual Basic Keyword( or reserved word)
(c) Must not exceed 255 characters in length
(d) Must be Unique in scope
(e) Must not contain any special characters except underscore(s). However special
characters like !,@,#,$,% and & can be accepted in variable names if they are used as
the last character in the variable name. e.g Kedei@ is Valid while Ita@m is invalid
Variable names may be prefixed with a three letter character used conventionally to
indicate its type. These are as shown in Table 2.2 . E.g. the variable Results should be
prefixed with str as in strResults if it is a string, int as in intResults if it is an integer.
Table 2.2: Conventional three letter prefixes for Visual Basic variable names
Variable type

Prefix

Examples

Byte

byt

bytWest, bytNum

Integer

int

intResult, intCount

Long

lng

lngPlate,lngGas

56

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Table 2.4: Standard Postfixes used to identify variable names


Variable type
Postfix
Example
Integer
%
Result%, Count%
Long
&
Plate&, Gas&
Single
!
Kell!, Lenght!
Double
#
Pie#, Limit#
Currency
@
Total@, Income@
String
$
Name$, Class$
The other data types do not have any PostFixes used to identify them

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

All Numeric Types

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Error Due to Data


type Mismatch

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

Defining Variables Using Objects properties

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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:

Dim lngLength As Long

3:

Dim blnState As Boolean

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Defining Variables Using the InputBox Function

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

for users Input

Defining Variable using Files

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Viewing the Content of Variables


Visual Basic provides a couple of techniques used to view data in variables. Three of the
most commonly used methods are discussed next

Viewing Variables Value using objects properties


This is the most popular technique used to display data stored in variables. This is done
as follows
txtResult.Text= dblSum
The implication is that the content of the variable dblSum should be assigned to the Text
property of the TextBox with name, txtResult in the current Form. After invoking the
statement, any text displayed in the TextBox represents the value stored in dblSum.
Usually, the Text and Caption properties are the most often used properties used to output
data. Since the Caption property cant be edited at run time, it is generally a more
preferred medium to display data. Other properties like Height, Left, Value, and Top can
also be used. For example, the Value property of an OptionButton can be used to display
Boolean Data types because the state of the OptionButton reflects its value which may be
True or False. The Value properties of HorizontalScrollBar and Sliders can also be used
to output data with a limited range. However, it could be very difficult to read the value
since it is relative to the Max and Min properties of the control

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Given the statements


Dim strResult As String
Dim lngResult As Long
strResult= 8 + 25
lngResult= 8 + 25
debug.print lngResult
debug.Print strResult

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.

Viewing the content of variables using message box


Repeat the example above and replace statement 5 and 6 with the statements
5: MsgBox strresults
6: MsgBox lngResults
The output should appear as shown in Figure 2.10

Figure 2.10
Using the MessageBox to
display Results

A more descriptive output should take the form.


MsgBox Result = & strResult
On invoking this code, the output appear as shown in Figure 2.11

Figure 2.11
displaying descriptive result
in a MessageBox

Programming Fundamentals

67

Using the Local and Watch Window


The local window is used to view the content of variables though it is not a conventional
output technique. This method is often used when troubleshooting programs for bugs by
exposing each variables content. To view the Local/Watch window, you put a program
in break mode and then view the Local/Watch window using the View menu. (Alt + V +
L ) Figure 2.12 shows the local window displaying a variable name, its type and value.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

A mod B ; 48 mod 5 = 3 Remainder when A is


45 mod 10 = 5, 56 mod 7 = 0 divided by B

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 or equal

<=

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 of Arithmetic Operators


If more than one mathematical operator occurs in an expression, Visual Basic processes
the expression according to the order of operator precedence shown in Table 2.9.
Table 2.9: Precedence of mathematical operators
Operator

Precedence order

Exponentiation

Division

Multiplication

Addition

Subtraction

For example, the assignment statement


2 + 3 * 4

70

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

16 mod 2 mod 5 = (16 mod 2) mod 5

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

Table 2.11 Visual Basic intrinsic Mathematical/Trigonometric functions


Function
ABS
ATN
COS
EXP
FIX
INT
LOG
RND
SGN
SIN
SQR
TAN

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

DateAdd(interval, number, Returns a Date containing a date to


date)*
which a specified time interval has been
added.
DateDiff(interval, date1, Returns a Variant (Long) specifying the
date2)
number of time intervals between two
specified dates.
WeekDay(date)
Returns a Variant (Integer) containing a
whole number representing the day of
the week.
WeekDayName(weekday) Returns a string indicating the specified
day of the week

72

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Month

Month (Date)

Returns a whole number between 1 and


12 inclusive representing the month of
the year

MonthName

MonthName(Month)

Returns a string indicating the specified


month

The Interval argument in this function is a String with settings as shown in


Table 2.13

Table 2.13:Setting for the DateAdd Interval parameter


Setting
Description Setting
Description

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.

Events and Event Procedures


All Input/Output programs implemented in Visual Basic are written in event procedures.
An Event procedure is a sub routine called when a user performs an expected action on
an application. Things happen only when codes embedded in event procedures are
executed. Each object has a set of events it responds to and Visual Basic Programs are
written as subroutines (or procedures) in these objects. These object dependent

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:

Turning on the on/off switch

Turning on the switch of another bulb.

Touching the bulb.

Joining two wires

Waiting for some seconds

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) :

Clicking the mouse on the execute button

Double clicking the form.

Clicking any other control.

Shifting focus from any control.

Waiting for some time after making the input.

The Form Module and Event Procedures

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 2.13
Form Module
Showing object
list and Procedure
list combo boxes.

Procedure List
Object List
Edit Box

The major parts of the code window are

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.

Creating the Click Event Procedure of a


CommandButton
Almost all controls that are visible at runtime have the Click Event. This event is
triggered when a user clicks the mouse on the control. We now consider how to create the
click event procedure of CommandButton (cmdCalculate). The following steps are
required to create the click event of cmdcalculate or any CommandButton
Step 1: Using the View menu or Project Explorer click the View Code icon. This opens
the code window.
Step 2: You will see the Option Explicit statement(If it does not exist, please type it
yourself ) as shown in Figure 2.13: Open the object list Combo Box(see Figure 2.13 ) and
select the object in Question (in this case cmdCalculate).
Step 3: Observe that the header and footer of the event procedure are created
automatically as shown in Figure 2.14

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

Creating click Event procedure of a TextBox


Step1: Click the View Code button to open the Code window
Step 2: Open the Object List ComboBox and select the TextBox(txtInput) or anyTextBox
Step 3: The header and footer of the change event procedure of the TextBox appears.
Since our event of interest is the click event, we have to open the procedure list and select
change from the list of events of txtinput. On selecting change from the procedure list,
the header and footer of the change event procedure is created above the click event
procedure.(see Figure 2.15) This is the method that will be used to create the non default
event procedures of object.

76

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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:

Selected Visual Basic events

Event
Click

Description
This event fires whenever an object which respond to a click event
is clicked directly or indirectly

Change

Occurs automatically whenever the content of a TextBox or Label is


changed as a result of any Edit feature caused by printable ASCII
keys.

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

Occurs when a form loads. It is Used to initialize property setting


and variables.

Unload

Occurs when a form is unloaded.

Timer

Occurs as a specified number of time interval is fired. It is a system


controlled event.

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

Used to make sure that a user responds properly to a control before


shifting focus to another control. It works in tandem with the causes
validation property of another control

Unloadquery

Used to determine how a user exits and application and to take


necessary steps depending on the unload mode. The argument is of
Boolean type and is True if we dont want the application to be
unloaded.

LostFocus

Activated when Focus is shifted from a control

GotFocus

Activated when focus is Given to a control

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

Activated when any key is pressed.

MouseMove

Activated when the mouse is moved over a control.

78

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Changing Object Properties in Event Procedure

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

4. Save the program


5. Run the Program by Pressing F5 and then Click the Execute Button. Observe that
Hello World appears on the TextBox.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Read Only Properties


Though all properties available at design time can be changed with appropriate data using
the properties window, this is not the same with code. An attempt to assign data to some
objects properties results in an error of the form shown in Figure 2.18
Figure 2.18
Error due to assignment
to ReadOnly properties

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

Modifying the Caption and Text Properties in Event


Procedures using Variables
Instead of assigning a string expression to the Text/Caption property, we can assign a
variable to it. This makes it very flexible and dynamic since different data can be stored
in this variable and hence different data is displayed by the control on each call to the
event procedure. We will consider two examples on how to manipulate objects captions
and Texts at runtime using variables

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

Click Event of the Double Button


Listing 2.5a: Doubling and Input in a Click Event Procedure
Private Sub cmdDouble_Click()
1:
Dim X as Double,Y as Double
2:
X = txtInput.Text
3:
Y = 2 * X

82

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Click Event of the Clear Button


Listing 2.5b: Clearing Data in a TextBox and Label at Runtime
Pivate Sub cmdClear_Click()
1:
txtInput.Text = ""
2:
lblResult.Caption = ""
3:
txtInput.SetFocus
End Sub
The code in Listing 2.5b sets the text and caption properties of the TextBox and Label
with an empty string. This has the effect of clearing the data displayed by these controls.
Line 3 sets the cursor blinking on the TextBox after the entry has been cleared. It is called
a Method of 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.

Click Event of the Close Button


Listing 2.5c: Unloading a program at runtime in an Event procedure
Pivate Sub cmdClear_Click()
1:
End
End Sub
The End statement is simply used to unload a program. The Unload Me statement can
equally be used.

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

In S.I. units, P is the Pressure,atm;V the Volume;dm3;T is the Temperature in K while R


is a constant called the Universal Gas Constant with S.I. Value of 0.0802atm dm3K-1mol-1
An interface for this problem is as shown in Figure 2.21. Observe here that each
TextBox is annotated with both quantity and unit. It is very important that we add the
units to each TextBox(if any) we create so that our program can make sense to our users.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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).

Procedure level Variables


Static Variable

3).

Module level Variables

4).

Public Variables

Procedure Level Variables


Any variable declared within an Event procedure(or other procedures) is said to be a
procedure level variable. Once a variable is declared as a procedure level variable, it
means it cannot be accessed in other procedures within or outside the module because it
is only available within the procedure. The implication here is that you can declare two
variables with the same name in different procedures. Each variable is declared and
defined with its data when the procedure is called and lost when the procedure ends.
These procedure level variables are most times called Local Variables because their
scope starts and ends in the procedure.

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

Module Level Variable


A variable is said to be a Module Levels Variable if it is declared outside a procedure
block. Such variables are everywhere visible within the module and should not be redeclared within the module. Module level variables are declared with the Dim or
Private/Public keyword. E.g
Private X1 As Double
Dim X1 As Double
Any of the two statements above can be used to declare a module level variable. With a
module level variable, a variable in a procedure can see and use the data stored in it
from another procedure. Figure 2.22 shows the code window showing the declaration of
a module level variable and procedure level variable.
In Figure 2.22 variables X and Pi are module level variable while variable T is a
procedure level variable. Hence value of Pi and X are available to all the procedures
while T is local to each procedure. The T in cmdShow is different from the T in
cmdCalculate because they were declared in two different procedures

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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 Standard Public Variable


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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Multiple Forms Applications


An application with more than one Form is called a Multi - Form Application. You create
a multiple Form application by adding Form(s) to the project at design time and
decorating the forms with appropriate controls. When working with multiple Form
applications, it is important that you note the following:
(a)
By default all Standard Exe Visual Basic projects starts with a single form
(b)
You add other Forms to the project by selecting Add Form from the project
menu. This opens the Add Form dialog. Click open to add the default(blank
Form) to the project
(c)
View the project explorer and notice that the application actually has more than
one form. Add other forms to the project by repeating step b
(d)
To work with a specific form, double click the form on the project explorer
window. This makes the form the active form at design time. You decorate the
form with control before activating others until all the forms in the project have
been decorated.
(e)
When running a multiple form application, use the project properties dialog to
choose the start up Form. Figure 2.23 shows the project properties dialog, you

90

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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)

Private Sub cmdBack_Click()


Form1.show
Form2.Hide
End Sub
The show method is used to show a specific Form while the Hide method is used
to hide the present Form. The implication of this is that you want to remove the
present Form from view and show another Form.
At times, you might need to show another Form while the present Form is still
visible. In this case you show the second Form as a modal Form as follows

Programming Fundamentals

91

Private Sub cmdOption_Click()


Form2.show vbmodal
End Sub
When a Form shows modally, you would not be able to interact with other forms in the
application except you close the Modal Form. Modal Forms are often used for dialog
boxes that you want to have user complete before proceeding with the processing of
information in the mother Form
(i)
When coding multiple Form application, it is good practice to specify the name
of the container (Form) for the Form you are reading or writing to. As an
example, consider the code shown in Listing 2.8
Listing 2.8: Working with information from multiple Forms
Private Sub cmdExecute_Click()
1:
Dim X As Double, Y as Double
2:
X=form2.txtDecimal.Text
3:
C=form1.txtInput.Text
4:
F=9*C/5+32
5:
lblResults.caption=Round(F,X)
End Sub
In the code in Listing 2.8, cmdExecute is in Form1 and hence the code has to be activated
in Form1. Form2 contains a text box used to set number of decimal places. Data is read
from Form 1 and stored in variable X. Also Form 1 contains a text box used to input data
and transferred to variable C in line 3. Line 4 used operators to manipulate C and store
results in variable F. Line 5 used the Round Function to round F to X decimal places and
transfer result to the caption of the label, lblresults in the active Form. Note that in line 5,
the name of the Form was not used to qualify the label lblresults. Here, because the name
of the form was not specified, the active Form is assumed to be the container Form. This
has the same effect as the statement
Me.lblResults.Caption = Round(F,X)
(j)

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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)

Option Explicit statement

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)

Give them same and Height

b)

Align them Right

94

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

c)

Give them equal vertical spacing

Using the First TextBox as standard


Figure Q2.6

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

where NRe is the reynolds number defined as

Programming Fundamentals

N Re =

95

ud

and = Density of fluid , Kg/m3


u = velocity of fluid, m/s
d = diameter of pipe, m

= Vis cos ity of Fluid, Pa S


Design and implement a program for the determination of friction factor. Also
make provision for users to adjust output decimal places.
Note: you have to Display both Friction factor and Reynolds number.
Comment on your choice of control
Question 2.10
The interface shown in Q2.10 was designed by a budding programmer to evaluate
the LCM/HCF of two numbers. Outline the shortcomings of the interface and
hence or other wise redesigned an improve interface for the problem. Also write
codes in suitable event procedure to give life to the interface

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

IF Then Else Structure


Consider the function defined as

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

The Else If Statement


Listing 3.1 can be written so that the Else statement carries a condition thus eliminating
the default block. This Form is presented as Listing 3.2 with an analysis underneath.
Listing 3.2: Decision Structure Without a Default block
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:
ElseIf X <= 3 Then
6:
G = X ^ 2-1
7:
End If
8:
MsgBox "Value of G is " & G
End Sub

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:

ElseIf X > 3 Then

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

Flow chart showing

Input x

the ElseIf structure the


and the Else block

Else

x > =3

Then

g = SQR( X 3)

X< 3
g=X^2-1

Print g
Stop

102

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Listing 3.3: Using Else If and Else statements


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 If X > 3 THEN
6:
G = X^ 2-1
7:
Else
8:
G = 2*X-9
9:
End If
10:
MsgBox "G = " & G
End Sub
In Listing 3.3, Line 5 and 7 have the Else and Else If statements, line 5 is tested only
when Line 3 evaluates to False. The Else block is evaluated unconditionally when lines 3
and 5 evaluate to False. In Listing 3.3, Line 7 could just have been written with the ElseIf
statement only. The implication is that the last block header is tested before evaluating it.
Choosing between the Else and Else If statement is actually a matter of style and
preference. However, it is better to state all conditions explicitly with the Else If
statement because it makes the code more readable and traceable. The Else statement
should only be used when specifying a default used to handle problems which may arise

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Listing 3.4: Using object properties in conditional statements


Option Explicit
Private Sub cmdCalculate_Clicked
1:
Dim X As Double, Y As Double
2:
X = txtInput.Text
3:
If optCelsius.Value = True then
4:
Y = X + 273
5:
ElseIf optRankine. Value = True then
6:
Y = 5/9*X
7:
ElseIf optFahrenheit. Value = True Then
8:
Y = 5/9 * (X+460)
9:
End If
10
lblOutput.Caption = Y
End Sub
In Listing 3.4, two variables X and Y are declared in Line 1 while Line 2 assigns the
text in txtInput to X. Lines 3 to 9 are more or less like Lines 3 to 9 of Listing 3.3. The
major difference between Listing 3.3 and Listing 3.4 is that Listing 3.3 used variable
entirely while Listing 3.4 uses object properties. The Statement
If optcelsius. Value = True
evaluates to True if optCelsius is the selected option(see Figure 3.5). Hence if this
statement evaluates to true, then Line 4 is executed. However, if Line 3 evaluates to
False Line 5 is tested. When Rankine is selected, then Line 5 evaluates to True and hence
line 6 is used to convert the input from Rankine to Kelvin. If Lines 3 and 5 both evaluate
to False and Line 7 evaluates to True then the input is converted from Fahrenheit to
Kelvin in Line 8. To test the program, follow the steps outlined below

Control Structures

105

Design the interface in a New Standard Exe application


Give the controls the names used in Listing 3.4
Place the code in the appropriate event procedure.
Fire it by pressing F5
Enter known values of temperature and click convert. It should give you expected
output

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Table 3.2: Table of Factors for Temperature conversion


Input(x)
Output(y)
Relationship, y = f(x)
Celsius
Celsius
y=x
""
Kelvin
y = x + 273
""
Fahrenheit
y = 9x/5 + 32
""
Rankine
y=9x/5 + 492
Kelvin
Celsius
y = x - 273
""
Kelvin
y=x
""
Fahrenheit
y = 9x/5-460
""
Rankine
y = 9x /5
Fahrenheit
Celsius
y = 5/9(x-32)
""
Kelvin
y = 5/9(x+460)
""
Fahrenheit
y=x
""
Rankine
y = x + 460
Rankine
Celsius
y = 5/9(x-492)
""
Kelvin
y = 5x/9
""
Fahrenheit
y = x - 492
""
Rankine
y=x
From the table, the IF Then/Else If statements are used directly with logical operators to
code the interface of Figure 3.5 using Listing 3.5
Listing 3.5: Using Compound Conditional Statement
Option Explicit
Private Sub cmdConvert_Click()
1:
Dim X As Double, Y As Double
2:
X=txtInput.Text
3:
If optC1.Value = True And optC2.Value = True Then
4:
Y=X
5:
ElseIf optC1.Value = True And optK2.Value = True Then
6:
Y=X-273
7:
ElseIf optC1.Value = True And optF2.Value = True Then
8:
y=5/9*(x-32)
9:
ElseIf optC1.Value = True And optR2.Value = True Then
10:
Y=5/9*(x-492)
11: ElseIf optK1.Value = True And optC2.Value = True Then
12:
Y=x+273
13: ElseIf optK1.value = True And optK2.Value = True Then
14:
Y=X
15: ElseIf optK1.Value = True And optF2.Value = True Then
16:
Y=9/5*(X+460)

108

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

17: ElseIf optK1.Value = True


18:
Y=9/5*X
19: ElseIf optF1.Value = True
20:
Y=5/9*X+32
21: ElseIf optF1.Value = True
22:
Y=5/9*X-460
23: ElseIf optF1.Value = True
24:
Y=X
25: ElseIf optF1.Value = True
26:
Y=9/5*X+492
27: ElseIf optR1.Value = True
28:
Y=5/9*X
29: ElseIf optR1.Value = True
30:
Y = 5*X/9
31: ElseIf optR1.Value = True
32:
y = X - 460
33: ElseIf optR1.Value = True
34:
y = x
35: End If
36: lblResult.Caption = y
End Sub

And optR2.Value = True Then


And optC2.Value = True Then
And optK2.Value = True Then
And optF2.Value = True Then
And optR2.Value = True Then
And optC2.Value = True Then
And optK2.Value = True Then
And optF2.Value = True Then
And optR2.Value = True Then

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 .

Listing 3.6: Using Nested Structure


Option Explicit
Private Sub cmdConvert_Click()
1:
Dim X As Double, Y As Double
2:
X=txtInput.Text
3:
If optC1.Value=True Then
4:
If optC2.Value=True Then
5:
Y=X
6:
ElseIf optK2.Value=True Then
7:
Y=X+273
8:
ElseIf optF2.Value=True Then
9:
Y=5/9*(X-32)
10:
ElseIf optR2.Value=True Then
11:
y=5/9*(X-492)
12:
Endif
13: Elseif optK1.Value = True Then
14:
If optC2.Value = True Then
15:
y = x - 273
16:
ElseIf optK2.Value = True Then
17:
y = x
18:
ElseIf optF2.Value = True Then
19:
y = 9*x/5-460
20:
ElseIf optR2.Value = True Then
21:
y = 9*x/5
22:
Endif
23: Elseif optF1.Value = True Then
24:
If optC2.Value=True Then
25:
y = 5/9 * (x 32)
26:
ElseIf optK2.Value=True Then
27:
y = 5/9 * (x + 460)
28:
ElseIf optFarenheit_1.Value=True Then
29:
y = x
30:
ElseIf optRankine_1.Value=True Then
31:
y = x + 460
32:
Endif
33: Elseif optR1.Value=True Then

110

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

If Then End If Structure

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

Listing 3.7: Using the if then End If


1:
If IsNumeric(txtInput.Text) Then
2:
Dim X As Double
3:
Dim Y As Double
4:
X = txtinput.Text
5:
Y = 9/5*X+32
6:
lblResult.Caption = y
7:
End If
In Listing 3.7, if line 1 evaluates to false, the whole program would not be executed. This
is actually very important in fail-safe programming. Other instances when the If Then
End If structure is used are
1).

To increment a number if a certain condition is true e.g.


If X mod 10 = 9 Then
X = X + 1
End If

112
2).
E.g.

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

To convert the If Then Else/IF then Else If to multiple independent condition.

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.

Select Case Structure


This is considered to be a more efficient decision structure than the if structure. It differs
from the If structure in that it evaluates a single statement at the header of the structure
and selectively executes the block of statement(s) which matches the result of the
evaluation. Here the result of the evaluation is compared with several alternatives with
each alternative having a block of statement(s) to be evaluated. The block of statement
that will be evaluated depends on the alternative that first matches (or is logically
equivalent to) the result of the statement evaluated. The syntax of the select case structure
is as follows:
Select case expression
Case Alternative #1
Block #1 statement #1
Block #1 Statement #2
.
.
.
Block #1 Statement #n
Case Alternative
#2
Block #2 statement #1

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.

The expression can be an object property e.g


txtResult.Text,lstResult.ListIndex,optCelsius.Value etc

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

As an example, we consider the roots of a quadratic equation given by.

x1 =

b + b 2 4ac
2a

- 3.3 a

b b 2 4ac
2a

- 3.3 b

and

x2 =

114

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Listing 3.8: Using the select case structure


Option Explicit
Private sub cmdconvert_click()
1:
Dim A As Double, B As Double, C As Double
2:
Dim X1 As Variant, X2 As variant
3:
a
= txtA.Text
4:
b
= txtB.Text
5:
c
= txtC.Text
6:
D
= b^2 - 4*a*c
7:
Select case D
8:
Case is > 0
9:
X1 = (-b + Sqr(D)) / (2 * a)
10:
X2 = (-b - Sqr(D)) / (2 * a)

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Nested Select case Structure


Like the If structure, the select case structure can be nested. Figure. 3.10 shows an
interface capable of being solved by nested Select Case structure. Listing 3.9 shows the
code used for the implementation of the interface of Figure 3.10. The flow chart used for
the nested structure is as shown in Figure 3.9

Figure 3.10
Candidate interface for
Nested Select Case.

Control Structures

Listing 3.9 Nested select case structure


Option Explicit
Private sub Form_Load()
1:
With cboInput
2:
.clear
3:
.AddItem Celsius
4:
.AddItem Kelvin
5:
.AddItem Fahrenheit
6:
.ListIndex = O
7:
End with
8:
With cboOutput
9:
.clear
10:
.AddItem Celsius
11:
.AddItem Kelvin
12:
.AddItem Fahrenheit
13:
.Listindex = 1
14: End with
End sub
Private sub cmdconvert_click()
17: Dim
X As Double, Y As Double
18: X = txtinput. Text
19: Select case cboOutput.Listindex
20: Case O
21:
Select case cboInput. Listindex
22:
case 0
23:
y = x
24:
case 1
25:
y = x + 273
26:
case 2
27:
y = 9/5 *x + 32
28:
End select
29: Case 1
30:
Select case cboInput.Listindex
31:
case 0
32:
y = x 273
33:
case 1
34:
y = x
35:
case 2
36:
y = 5/9*x-460
37:
End select
38: Case 2

117

118

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

If Then Else Statement


Visual Basic also has the one line form of the If Then statement that considers both the
True and False part of a condition. The syntax of this statement is
If condition THEN TrueStatement Else FalseStatement
The conditional function written in equation 3.1 can be written in terms of the IF then
Else statement as follows
If X > 3 Then G =SQR(x-3) Else G = X^2-1

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

The following comments about the choose function are in order.


 If expression evaluates to 1, statement 1 is executed and returned, if expression
evaluates to 2, statement 2 is evaluated and returned. Generally, if expression
evaluates to N, statement N is evaluated and returned.
 If expression evaluates to give a floating number, then it is approximated to the
nearest integer and the appropriate expression evaluated and returned
 The Choose function returns a Null(Error) if expression returns a value less than 1 or
greater than the number of executable statements(or choices listed) in the function .
 All the statements in the choose function are evaluated but only one result returned
 If expression can not evaluate to give one, then an appropriate constant should be
added to it(or subtracted from it) to make expression return an integer between 1 and
the number of executable statements in the choose function.
The choose function is exemplified using the interface shown in Figure 3.12. This
interface allows the user to enter an input in the input text box and select an input unit
from the combo box. On clicking execute, the input is converted from the present unit to
Kelvin. The code used to drive this interface is as shown in Listing 3.11

122

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Listing 3.11: Using the choose function


Private sub Form_Load()
1:
With InputUnit
2:
.clear
3:
.AddItem Celsius
4:
.AddItem Fahrenheit
5:
.AddItem Rankine
6:
End with
7:
End sub
Private sub cmdConvert_Click()
9:
Dim x As Double, y As Double
10: X = txtInput. Text
11: With cboInput
12: Y=choose(.listindex+1, x + 273, 1.8* x,5/9*(x-32)+273)
13: End with
14: lblOutput.Caption = y
End sub
When celsius is selected in the combo, then the listindex is zero(0) and hence adding
one(1) to it makes it 1 so that statement 1 is evaluated x + 273 is returned to y. Also, If
Fahrenheit with index of 2 is selected, then upon adding one to it you have 3, then
statement 3 is returned. Without the addition of one to the listindex a run time error
results.

Figure 3.12
Conversion problem
using the ComboBox

123

Control Structures

For Next Loops


In order to solve practical Science and Engineering problems programmatically, we need
a very good idea on how to work with loops. Loops are used to evaluate one or more
statements repeatedly. Several kinds of loops exist in Visual Basic and each has its own
application and special problem its solve. Based on their nature, we distinguish two types
of loops. The first is a loop that has a definite number of times it executes and the second
is one that has an indefinite number of execution. In Visual Basic, we call the first type
of loop the For Next Loop and the second, the Do loop. The for next loop is discussed
below
Consider the code
Dim Sum As Integer
Dim I As Integer
I = 0
Sum = 0
I = I + 3
Sum = Sum + I
I = I + 3
Sum = Sum + I
I = I + 3
Sum = Sum + I
I = I + 3
Sum = Sum + I
I = I + 3
Sum = Sum + I
MsgBox Sum = & Sum
Notice that the statements
I = I + 3
Sum = Sum + I
Were being over repeated. A question is, is there no way we can write the code without
repeating these statements.? How about if the statements need to be repeated 20 times, do
we have to write it that way?. This of course is not efficient because it is time and space
consuming. With the For Next Loop, an improved version of this code can be written
by enclosing the recurring statements in a loop block as follows
1:
2:
3:
4:
5:

Dim
Dim
I =
Sum
For

Sum As Integer
I As Integer,K As Integer
0
= 0
K = 1 To 5

124

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.



ini is the initial value or start value of the Loop Variable.


lim is the limiting value(stop value) of the Loop Counter.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Listing 3.12 a Evaluating Summation with Do While Loop Structure


1 : Sum = 0
2: I = 1
3: Do While I <= 100
4:
I = I + 3
5:
Sum = Sum + I
6: Loop
With the Do Until Structure, it takes the form shown in listing 3.12b
Listing 3.12b Evaluating Summation with Do Until Loop Structure
1: Sum = 0
2: I = 1
3: Do Until I > 100
4:
I = I + 3
5:
Sum = Sum + I
6: Loop
Basically the two structures are the same, the difference being in the nature of the
problem. However the negation(reverse) of While gives Until. For instance if a Loop
must proceed While a condition is True, then we have to use the While Loop. However,
we can also use the Until version and ask the program to Loop Until condition becomes
False. Also, if we are to loop until a condition becomes True, then we can also loop
while the condition is False. This is the basic difference between the two. In any
problem, the version used is a matter of prejudice. Also note that in this problem like the
For Next Loop, it is possible that the Loop might not be executed at all if the condition
becomes False(Listing 3.12a) or True(Listing 3.12b) before the start of the loop. This
feature makes the pre-checked Do Loop very similar to the For Next loop

Post Checked Do Loop

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Solving Problems with Do Loops


Common examples of problems that lend themselves to manipulation using Do Loops are
iterative problems, recursive problems and problems involving number base conversion.
Iterative problems are considered in Chapter 9 under numerical application. In iterative
problems, post checked Do Loops are used with logical operators to establish a
condition.(error < tolerance or IterationCount > MaxIteration).

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

This is stated as follows


HCF(A,B) =

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

In equation 3.7 since 60 mod 42(remainder when 60 is divided by 42) is 18 then


condition 1 is not satisfied hence condition 2 is satisfied. Therefore the problem is now
the problem of evaluating HCF(42, 60 mod 42)= HCF(42, 18) . We are now
faced with the problem of finding HCF(42,18). Equation 3.6 would be used again. This
gives
18 ,

42 mod

18 = 0

HCF(42,18) =

......... 3.8
HCF(18, 42 mod 18)

42 mod 18 0

Also, in Equation 3.8 since 42 mod 18(remainder when 42 is divided by 18) is 6


then condition 1 is not satisfied hence condition 2 is satisfied. Therefore the problem is
now the problem of evaluating HCF(18, 42 mod 18)= HCF(18, 6) . We are
now faced with the problem of finding HCF(18, 6). Equation 3.6 would be used again.
This gives

134

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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 )

HCF and GCD(Greatest Common Divisor) are used interchangably


Other examples of recursive problems are Fibonacci problem, factorial problem and
Ackerman problem. By suitably constructing the Do Loop, one can solve these problem
easily. However, because Visual Basic supports recursion, recursive problems are better
solved by writing recursive functions instead of using loops.(see Chapter 6)

Number Base Conversions


Problems involving number base conversions are very good examples of problems that
lend themselves easily to manipulation with the Do Loop. Conversion problems are
always in two forms. These are (a) Converting a number from a base other than 10 to
base 10 and (b) converting a number from base 10 to a base other than 10
Conversion from base 10 to other bases often involves repeated integer division until the
number becomes zero. For instance given the number 54210, we can convert it to base 5
by carrying out repeated integer division and storing the remainder as follows.
3
3
3
3
3
3

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Listing 3.14: Conversion from Base 10 to other bases using Do Loop


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
In Listing 3.14, three variables N,B and Sum are declared. N(Number to be converted)
and B(Base to be converted to) are declared as integer. Sum was declared as string
because the process of reading the remainder upward is seen as a string concatenation
operation. Line 4 initializes Sum to an empty string so that the first concatenation should
make sum equal to the number being concatenated. The header of the Do Loop is set in
line 5 while line 6 gets the remainder when the number is divided by the base(B). This
number is then concatenated to sum. Line 8 performs the integer division operation thus
reducing N. The structure loops until N= 0. Line 10 prints results using a Message Box.
Observe how Do Loops was used to convert the operation in Table 3.1 into a workable
code.
The problem of converting a number from other bases to base 10 is also done using Do
Loop though it is simpler. Given the number, 231256 you convert it to base 10 as follows

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

The Exit Statement


The exit statement is used to Exit a block of DoLoop and For...Next loop. It has the
effect of transferring control from the position it was used to the statement after the footer
of the loop. In a For Next Block, the exit statement takes the form
For I = a To b step c
Exit For
Next I
Likewise, in a Do loop, the exit statement takes the form
Do
Exit Do
Loop
Apart from the For Next and the Do Loop, the Exit statement can also be used to
Exit a Sub(Exit Sub),a function(Exit Function) and a property(Exit Property)

138

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Dynamic Interface Design


By suitably using Control Structures, one can design a Form whose looks changes as
different events are triggered. An example of this is the interface in most applications
options dialog. Here the form contains a tab strip control with tabs such that when a tab
is clicked a different user interface is show cased. The option dialog of Microsoft Visual
Basic is as shown in Figure 3.18a and b. In Figure 3.18 a, the ActiveTab(or index of
SelectedItem) is Tab #3 (General Tab) while in Figure 3.18b, the Active tab (or index of
selecteditem) is Tab # 1(Editor Tab). Interfaces of this sort are created using one form of
decision structure or the other. Before discussing how to create this type of interfaces, let
us consider the interfaces in Figure 3.19 a to c. In Figure 3.19, the option buttons were
used instead of the tab strip control. The principles behind the two are basically the same.
The steps needed to design the interfaces of Figure 3.19a to c, are
 Draw three option buttons on the Form as shown in Figure 3.19a

140

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe







Draw an instance of the PictureBox Control on the Form


Draw all the controls shown in Figure 3.19a on the PictureBox
Name the PictureBox picQuadratic , change its BorderStyle property to 0 None
Note the left of the PictureBox(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 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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Listing 3.17: Designing dynamic interfaces with OptionButtons


Option Explicit
Private Sub optQuadratic_Click()
1: If Me.optQuadratic.Value = True Then
2:
Me.picQuadratic.Left = 135
3:
Me.picEOS.Left = 135000
4:
Me.picConversion.Left = 135000
5: End If
End Sub
Private Sub optEOS_Click()
9: If Me.optEOS.Value = True Then
10:
Me.picEOS.Left = 135
11:
Me.picQuadratic.Left = 135000
12:
Me.picConversion.Left = 135000
13:
End If
End Sub
Private Sub optConversion_Click()
16: If Me.optConversion.Value = True Then
17:
Me.picConversion.Left = 135
18:
Me.picQuadratic.Left = 135000
19:
Me.picEOS.Left = 135000
20: End If
End Sub

144

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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 )

0.2 and 1.2

1.05 and 1.2


1.2+ and 1.4
1.4+ and 2.0
2.0+ and 3.0

z = Pr( 1.6643 Tr 2.2114) 0.3647 Tr +1.4383


z = Pr( 0.5222 Tr 0.8511) 0.0364 Tr +1.0490
z = Pr( 0.1391 Tr 0.2988) + 0.0007 Tr +0.9969
z = Pr( 0.0295 Tr 0.0825) + 0.0009 Tr +0.9967

0.2 and 1.2

1.05 and 1.2


1.2+ and 1.4
1.4+ and 2.0
2.0+ and 3.0

z = Pr(-1.3570 Tr + 1.4942) + 4.6315 Tr 4.7009


z = Pr( 0.1717 Tr 0.3232)+ 0.5869 Tr +0.1229
z = Pr( 0.0984 Tr 0.2053) + 0.0621 Tr +0.8589
z = Pr( 0.0211 Tr 0.0527) + 0.0127 Tr +0.9541

0.2 and 1.2

1.05 and 1.2

z = Pr(-0.3278 Tr + 0.4752) + 1.8223 Tr 1.9036

149

Control Structures

5.4+ and 15

1.2+ and 1.4


1.4+ and 2.0
2.0+ and 3.0

z = Pr(-0.2521 Tr +0.3871) + 1.6087 Tr 1.6635


z = Pr(- 0.0284 Tr +0.0625) + 0.4714 Tr 0.0011
z = Pr( 0.0041 Tr +0.0039) + 0.0607 Tr +0.7927

1.05 and 3.0

z = Pr( 0.711 + 3.66 Tr)-1.4667


- 1.637/(0.319 Tr + 0.522) + 2.071

Where Pr = P/ (709.604 58.518 G )


Tr =(T+ 460)/ (170.491 + 307.44 G )
Units of P and T are in psi and oF respectively . G is the dimensionless gas gravity
Figure Q3.4
Determination of real Gas
compressibility

Use both Select Case and If Structure for the implementation


b)
Repeat Exercise 3.4a by including ComboBoxes to enable the user manage units
differences. You may use two Forms.

150

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Declaring Dynamic Arrays


An array whose Lbound and Ubound are not specified during declaration is called a
Dynamic Array. It is dynamic in the sense that the Lbound and Ubound could be changed
severally during program execution. This is particularly important when the size of the
data to be stored in the array is not known before program execution. Dynamic arrays are
important in the following areas:
1. As Parameter to Function
2. When Transferring list items to an array
3. When Deleting an element from an array
4. When Inserting an element into an array
5. Generating array from program execution

158

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

A dynamic array is first declared using the Dim statement as follows.


Dim A() As Double
Observe how the parentheses enclosed nothing. Because of this declaration, dynamic
arrays are also called Open Arrays. After executing some lines in the program, the size of
an array may become evident and hence Visual Basic gives you a way to re-declare the
array with specified lower and upper bounds as follows
ReDim A(1 To 5) As Double
After assigning data to the array say A(1) = 7, A(2) = 9, A(3) = 4; you can again change
the size of the array with an option of whether to preserve the array values or to clear it.
The code
ReDim A(1 To 10) As Double
increases the upper bound(Ubound) of the array to 10, with the original data in A lost.
However, you can use the code
ReDim Preserve A(1 To 10) As Double
to increase the array size while preserving the data originally stored in A

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

ReDim B ( lbound(A) To Ubound(A) )


For I= Lbound(A) To Ubound(A)
B(I)=A(I)
Next I
Observe that array B is a dynamic array hence the upper and lower bounds are set from
the source array. Array transfer can also involve objects where elements from an array
are transferred to elements of the objects property array. We demonstrate this with the
ListBoxs list array
ReDim B(0 To lstScientist.Listcount-1)
For I=0 To lstScientist.Listcount-1
B(I)=lstScientist.List(I)
Next I
The array transfer operation above are actually very direct. In practical operations you
would not expect to have the same Lbound in both arrays. Therefore, the boldface
statements might need adjustment. E.g if Array B has a lower bound of 3( or we want to
change the third and subsequent elements) we have to write the array transfer assignment
statement as
B(I+3)=A(I)
The statement above assumes that the loop index has the same lower and upper bound as
array A. By suitably changing the Loop index, you can also express the bold face
statement as
B(I)=A(I-3)
It is not uncommon to have arithmetic operation as subscript in array transfer operation.
For example, to transfer all the odd(or even) array index from array A to another array
you express one of the arrays as
A(I/2) or A(I/2+1)
More complex arithmetic operations are possible depending on the statement of problem.
Transfer to a scalar variant variable: Here the right hand side is an array(static or
dynamic) while the left hand side is a simple variable declared as variant. For Example
the statement
varNames = strNames

160

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

In the assignment statement above, strNames is an array while varNames is a simple


variable declared as variant

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.

Transfer to a scalar variant variable using the Array


Function
Given the values 34, 56, 67, 21 and 45. You can transfer all these data into a variant
variable using the array function as follows
Dim A As Variant
A = Array(34,56,67,21,45)
After the transfer, the variant variable A is converted to an array with a lower point
dictated by the Option Base statement. For example if Option Base 1 is used, then A(2)
is 56 otherwise A(2) is 67.
When working with arrays, we will be performing one form of array transfer operation or
the other. Some situations that call for array transfer include but not limited to the
following

Data Structures

161

I.

Transferring list items of a ComboBox/ListBox to an array variable or filling the


list with array variable

II.

Transferring data from one or more columns of a grid ( or MS/MSH flexgrid) to


an array variable and vice versa

III.

Merging two arrays

IV.

Protecting an array from being changed by a function or sub procedure

V.

Evaluating simple arithmetic on arrays.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Array and Summation


The sigma notation is commonly used in statistics to represent sum of array elements in
compact form.

e.g : The statement,


5

T = xi
i =1

Means that T = X(1) + X(2) + X(3) + X(4) + X(5)


Since the elements are treated as array elements, the For Next Loop can be used to
evaluate T as shown in Listing 4.3.
Listing 4.3: Implementation of summation Using For Next Loop
Option Explicit
Option Base 1
Private Sub Form_Load()
1: Dim Sum As Double,I as Integer
2: Dim X() As Double,N as Integer
3: N = InputBox("Enter count of data")
4: Redim X(N) As Double
5: For I = 1 To N
6:
X(I)= InputBox("Enter Array Value")
7: Next I
8: Sum = 0
9: For I = 1 To N
10:
Sum = Sum + X(I)
11: Next I
12: T = Sum
13: MsgBox " Sum = " & T
End Sub
Listing 4.3 is the general summation programming algorithm It is the basis of
statistical and numerical programming. In Listing 4.3, a dynamic array X is declared in
Line 2 in addition to a variable N(which is to hold the number of data points). The
number of data to be added is assigned to N using the InputBox statement.(line 3). In line
4 the Redim statement was used to re-declare X having known the array limits in line 3.
Lines 5 to 7 used the InputBox statement inside a loop to accept all the array values and
subsequently passed to the appropriate array index. In Line 8, sum is initialized to zero.
This is necessary because the value of sum has to be incremented as a loop executes. Line

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

You express line 10 as


Sum =Sum + (X(I) mean)^2
And line 5 as
variance = sum/(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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

3
4
5
7
8

3
4
5
7
8

3
4
5
7
8

Figure 4.1(a,b,c) Pictorial demonstration of the bubble sort technique.


In Figure 4.1 the first two elements(ith and ith + 1) are compared, If the ith element is
greater than the ith + 1 element , the two numbers are swapped. The next two elements
are compared until the nth-1 element is reached. This marks the end of the first pass. The
second pass starts with the changed array until I reaches N -1.(end of second pass). The
loop continues until no swap is made. This is implemented in Listing 4.4
Listing 4.4: Bubble Sort Subroutine
Option Explicit
Option Base 1
Private Sub Form_Load()
1: Dim I as integer, Nsort As Integer , N As Integer
2: Dim Temp As Double, A() 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: Do
9:
Nsort = 0
10:
For I = Lbound(A) to Ubound(A) 1
11:
IF A(I) > A(I) Then
12:
Temp = A(I)
13:
A(I) = A(I + 1)
14:
A(I + 1) = Temp
15:
Nsort = Nsort + 1
16:
End If
17:
Next I
18: Loop Until Nsort = 0
19: Outputting sorted data using message box
20: For I = 1 To N
21: msgbox "A(" & I & ") = " & A(I)
22: Next I
End Sub

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Listing 4.6: Ranking an array


Option Base 1
Option Explicit
Private Sub Form_Load()
1: Dim I As Integer, J As Integer,Rank() As Integer
2: Dim B As Variant, A As Variant, N As Integer
3: N =InputBox("Enter count of data")
4: ReDim A(N) As Double
5: For I = 1 To N

6:
7:

A(I)= InputBox("Enter Array Value")


Next I

8: B=A Copies array A into B


9: Sorts array A in descending order using bubble sort
10: Do
11:
Nsort = 0
12:
For I = 1 To N 1
11:
IF A(I) > A(I) Then
13:
Temp = A(I)
14:
A(I) = A(I + 1)
15:
A(I + 1) = Temp
16:
Nsort = Nsort + 1
17:
End If
18:
Next I
19: Loop Until Nsort = 0
20: Starts ranking using nested For Next Loop
21: For I = 1 To N
22:
For J = 1 To N
23:
If B(I)= A(J)
24:
Rank(I)= J
25:
End If
26:
Next J
27: Next I
28: displaying each item and its rank
29: For I = 1 To N
30:
MsgBox "Item # " & I & " has Rank of " & Rank(I)
31: Next I
End Sub
In Listing 4.6, Lines 1 to 7 are used for declarations and to read the array. Line 8 uses the
array transfer technique for variant variable to transfer all the items in array A to array B
for safekeeping. Lines 10 to 19 form a segment of the bubble sort technique of Listing

168

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

There is no wasted space for unused elements in lists unlike arrays

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

Items in the list can be seen and torched.

The list can easily be loaded using the properties window.

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.

Inserting Items into a List at Design time Using the


Properties Window
One can use the properties window to fill the list with items as demonstrated in Chapter
1. This is also applicable to the ComboBox because their List properties are available at
design time in the properties window. To add items to the List array of either the
ComboBox or ListBox, you follow the steps outlined below

Draw an instance of the ListBox or ComboBox control on the Form

Select the List property from the Properties Window

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

Inserting Items into a List at Run time Using the


AddItem method
One of the most often used methods of filling the list array is the AddItem method. The
AddItem method has the following syntax
object.AddItem string, index
Where the object is any Visual Basic control with the List property. String is the item to
be added while index is the index of the item in the list. The index parameter is usually
omitted unless we want to insert an item into the list at a position other than the bottom of
the list. To create a list initially you use the Additem method without the index
parameter. For instance, to create a list comprising of the major E&P companies in
Nigeria you implement it as follows

170

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Inserting Items into a List at Run Time Using the


List Property

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?

Working with the ListItems using the ListIndex


Property
The index of the selected ListItem is called the ListIndex. The ListIndex of the List
shown in Figure 4.2 is 2(ListIndex = 2). Once an item is selected from a list, the listindex
changes. The ListIndex of a list with no item selected is 1 while the ListIndex when the
first item is selected is 0

NOTE
The ListIndex of a ListBox is never constant, it changes with selection.

Figure 4.2
Demonstrating List and
Listindex using the ListBox

172

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Table 4.2: Data used to create the ListItems


Surname Firstname
Nationality
Newton
Leibinitz
Euler
Einstein
Faraday
Nobel
Planck
Galileo
Laplace
Kepler

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

Diagram: Form used for this application is as shown in Figure 4.3

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Program Behavior: As a numeric text is entered into txtInputValue cmdAdd becomes


enabled. As cmdAdd is clicked(or Enter key is pressed), the Text in the TextBox is added
to the list and cmdAdd becomes disabled again until another numeric text is typed in the
InputValue TextBox. This continues until the user has added all his input to the list. As
the List is clicked(or as an item is selected in the list) cmdRemove and cmdEdit become
Enabled. On clicking cmdRemove, the item is removed from the ListBox. However, if
cmdEdit is clicked, the selected item appears in the TextBox so that it can be edited. On
clicking Add(or pressing Enter), the item replaces the selected item since EditMode is
True. The Form is unloaded on clicking the Close button(or pressing Esc)
Code: The code used to implement this program is as shown in Listing 4.8
Listing 4.8: Performing simple statistics with the ListBox
1: Option Explicit
2: Private Sub cmdAdd_Click()
3:
Dim x As Double
4:
x = txtInput.Text
5:
lstData.AddItem x
6:
txtInput.Text = ""
7:
txtInput.SetFocus
8:
Call ValidateExecute
9: End Sub
10:
11: Private Sub cmdEdit_Click()
12:
Dim I As Integer
13:
Static K As Integer
14:
K = K + 1
15:
I = Me.lstData.ListIndex
16:
If K Mod 2 = 1 Then
17:
Me.txtInput.Text = Me.lstData.List(I)
18:
ElseIf K Mod 2 = 0 Then
19:
Me.lstData.List(I) = Me.txtInput.Text
20:
End If
21: End Sub
22:
23: Private Sub Form_dblClick()
24:
lstData.Clear
25:
lblMean.Caption = ""
26:
lblMax.Caption = ""
27:
lblMin.Caption = ""
28:
lblCount.Caption = ""
29:
lblsum.Caption = ""

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Copying Items from a ListBox Using Drag-Drop


Manual Drag Drop operations offer a simple way to copy items from a ListBox to
TextBox or Label. This operation is similar to the Drag Drop operation used to copy
items from folder to folder in Windows Explorer. It will be astonishing to you that you
need only two lines of code in two event procedures to accomplish this. Before
implementing this, we first of all set the Drag Icon property of the ListBox(say lstData)
to any icon in the graphics folder of Visual Basic. After setting this, you write the code
lstData.Drag
in the MouseDown event of the ListBox so that a ListItem can be dragged out of the
ListBox to another control. To enable the ListItem appear on the control, you enter a line
of code in the DragDrop event procedure of the control (say txtInput) as follows
Private Sub txtInput_DragDrop(Source As Control, X As Single, Y As Single)
txtInput.Text = Source.Text
End Sub

On releasing the mouse on txtInput, you find out that the Text dragged from the source
control appears on the TextBox.

180

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Sorting Data in a List using the Sorted Property


The sorted property of the ListBox and ComboBox is used to present items in the list in a
sorted order. A List becomes sorted as the Sorted property is changed to True from the
properties window. Since this property is Read only at run time, it implies that a sorted
list cannot be restored at run time. It is advisable to store items to be sorted in two
different ListBoxes so that one ListBox maintains the Sorted List and the other the
Original List. The Visible property is then used to toggle visibility of the two Lists.
Sorting a List has a big implication on the List because the List becomes sorted and the
original positions of items in the list change thereby giving invalid reference to listitems
in code. To demonstrate the effect of sorting a List, change the sorted property of
lstScientist(Application A) to True and Run the program. The List should become Sorted.
Now click the first item in the list and observe that the bio-data of a different scientist is
displayed on the labels. This happens for each item in the list because the surname does
not synchronise with(or is no more parallel to) other biodata. The question now is, how
can we keep our list sorted and still make valid reference to each item in the list?.

Synchronising a Sorted List Using


Property

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Selecting Multiple Items from a list


By changing the Multiselect property of a ListBox to 1(Simple) or 2(Extended), you can
select multiple items in the list. Also, when the style of the ListBox is changed to
1(CheckBox) you can also select multiple items by placing a checkmark by each item.
Figure 4.5 shows a standard ListBox with multiple items selected and a check box
ListBox with multiple items selected. In the standard ListBox five items are selected
while in the CheckBox ListBox four items are selected.

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.

Manipulating Multiple Selection Using the Selected


Property
Unlike other array properties discussed earlier, the selected property is an array of
Boolean values with the same upper and lower bound as the List array property. The only
controls that support the selected property are controls with MultiSelect property e.g the
ListBox and FileListBox controls.
The syntax of the selected property is as follows
object.selected(index) [=Boolean]
i.e to find out if the Item with index of k is selected or not you use the
code
If

object.Selected(K) = True Then

184

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

In Figure 4.5, since methane is selected, you can say that


lstComp.Selected(0) =True
You can also use code to select or deselect an Item. For example, to
select the Item with index of 3 you use the code
LstComp.Selected(3) =True
In like manner, to deselect the item with index of 4 you use the code
LstComp.Selected(4) =False
By using conditional statement, you can determine whether an item is
selected or not as follows.
If lstData.Selected(4) = True Then
Else
EndIf
With the aid of the selected array property you can make multiple selection and then
apply a single action on the selected items. E.g. you can make multiple selections and
then delete all the items or transfer all the items to another ListBox on the same or
different forms.
Application C
Aim To demonstrate the MultiSelect property.
Procedure: (a) Create an application with two Forms (b)Place a ListBox on both Forms
( c ) Add the ListItems of Figure 6.5 to the ListBox in the First Form(frmmain.) (d) Set
the MultiSelect property of the ListBox to 1-Simple. (e)Place two command buttons on
each Form. Your interface should be as shown in Figures 4.6a and 4.6b.
Program behavior: As an item is clicked in frmMain, it becomes highlighted. When
another item is clicked, they second item is also selected(i.e SelCount) becomes 2. As
more items are clicked, the are selected thereby increasing the SelCount property of the

Data Structures

185

List. An item is deselected by clicking on it while it is selected. As the command


button(cmdTransfer is clicked) all the selected items are transferred to Form2.

Figure 4.6(a and b)


Manipulating MultiSelect property
with multiple Forms.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Adding the FlexGrid controls to the ToolBox.


The grid control is not a default control unlike the ListBox and ComboBox. Usually you
add them from ocx controls components. To add any of the grid controls to the toolbox,
follow the steps outlined below.


Select Components from the Project Menu.

Place a checkmark on any of the following grid controls in the components dialog

Videosoft flexarray

Microsoft FlexGrid

Microsoft HierachicalFlexGrid

Click OK or Apply to add the selected grid to the toolbox.

Use the ToolTip to identify a grid control (say MSFlexGrid) in the toolbox and
draw an instance of it on the form.

Resize it to get the height and width of Figure 4.7

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

End the Program

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.

Understanding Basic Properties of the Grid


In ListBoxes and ComboBoxes, the index of a selected item(active Text) is accessed
using the ListIndex property. In Grids as expected, the currently selected cell (Active
cell) should be governed by two properties. One of these properties should specify the
row index while the other should specify the column index of the Active cell.
The row property specifies the active row while the col property specifies the active
column. The intersection of the row and col gives the active cell.
You can use the code below to access the active cell
n=grid.Row
m=grid.Col

Assigns Active row to n


Assigns Active column to m

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.

Entering and Retrieving Data in Grids


Data can be entered and retrieved from grids using similar techniques like the list
discussed earlier. These techniques are discussed below

190

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Using the TextMatrix Property


This is the most direct method used to enter data into grids or retrieve data from grids.
The syntax of the TextMatrix property is
object.TextMatrix(rowindex,colindex) = string
the object could be any of the grids control. For the purpose of this text we will be using
the MSFlexgrid as our object. Like the List, the TextMatrix is zero based and hence the
rowindex starts from 0 to 1 less than the rows of the control. Likewise, the colindex can
be any number between 0 and 1 less than the cols of the grid control. The code below
inserts Ikoku into the first cell of the grid grdProf.
grdProf.TextMatrix(0,0) = Ikoku
Since the TextMatrix array is a two dimensional array property, it is therefore
compulsory that the row and column indices must be specified before an item can be
added or retrieved from the structure. You can add or retrieve Items from a particular
column by keeping the column index constant and then use loop to parse through the
specified row range. Likewise, you can retrieve or add items to a row by keeping the row
index constant and vary the column index using a loop. For example, the code segment
below writes A to J in the first row of the grid.
For I = 0 To 9
grdProf.TextMatrix(I,0) = CHR(I+65)
Next I
Items added in a ListBox can be transferred to the grids using the TextMatrix property as
follows
For I = 0 To lstNames.ListCount - 1
grdProf.TextMatrix(I+1,1) = lstNames.List(I)
Next I
The code transfers ListItems to column 1 of grdProf. As an exercise, create an
application with a ListBox and an MSFlexGrid control. Use any of the methods outlined
in the previous section to add about 10 to 15 names to the ListBox with name lstNames.
Change the name of the MSFlexGrid control to grdProf and place the code above in the
Form Double Click event. Run the program and fire the event. The names should be
transferred to the second column of the grid starting from the second row.

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

lstNames.ListCount > grdProf.Rows Then


grdProf.Rows =lstNames.ListCount + 1
End IF
This increases the rows of the grid before attempting to write to it. In fail safe
programming, this method should be complemented with the regular setting using the
properties window. When transferring items from a column or row of grid, it is
advisable to use the AddItem method which guarantees fail safe list creation as follows:
For I = 1 To 10
LstNames.AddItem grdProf.TextMatrix(I,1)
Next I
You can also use the inputbox with the TextMatrix property to Write data to the active
cell as follows
With grdProf
.TextMatrix(.Row,.Col)=InputBox(Enter Data)
End With

Using the Text Property


Unlike the ListBox whose Text property is Read-only at run time, the Text Property of
MSFlexgrid and MSHFlexGrid is write-able at run time. This attribute is exploited to
read and write to the grid. The text of a grid control is the content of the Active cell. The
code below transfers the content of the Active cell of a grid control to a label (lblScore)
lblScore.Caption = grdData.Text
The same technique is used to write to grids except that it is often necessary to control(or
set ) the Active cell before writing to the grid. You set the Active cell by changing the
Row and Col properties. The Row property returns/sets the index of the Active row.
Also, the Col property returns/sets the index of the active column. The code below

192

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Using the AddItem Method


The AddItem method works almost like the AddItem method of the List and ComboBox
controls. For e.g the code below writes Egbe to the first column of row 4
grdData.Row = Egbe, 4
Similarly, the code below writes ThankGod to the first column of row 10
grdData.Row = Egbe, 10
In a grid, Row N corresponds to the nth + 1 Row. This also applies to the Col property.
By using string functions, you can write to more than one column of the grid using the
AddItem method. This is done by using the ASCII function(the Tab function) to invoke
tabs which sends data to other columns other than the first column. Remember that
ASCII of 9 (i.e CHR(9) or vbTab) has the same effect of pressing the Tab Key.

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

Using the TextArray Property


This is similar to the TextMatrix property in that it allows you to directly set or retrieve
the contents of a cell without changing the Row and Col properties. However, unlike the
TextMatrix property, the TextArray property operates like a one-dimensional array of
data. In order to fully understand the Textarray property, we use the grid shown in
Figure 6.7 for illustration. In Figure 6.7 the text Production
is in
TextMatrix(2,5) while the text Economics is in TextMatrix(1,2). This Position is
equivalent to a TextArray of TextArray(21) and TextArray(10) respectively.

194

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 4.8
Comparing the
TextMatrix and the
TextArray properties

The TextArray is obtained from the Textmatrix as follows.


Let c = gridControl.Cols
And r = gridControl.Rows
Therefore

Number of columns in the grid


Number of rows in the grid

TextMatrix(x,y) = TextArray(c*x + y)

.4.1

We can also express the TextArray in terms of the TextMatrix as follows


TextArray(n) =

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

Dim I As Integer,C as Long


C =grdData.Cols
For I = 0 lstSample.ListCount 1
grdData.TextMatrix(I\C,I Mod C ) = lstSample.List(I)
Next I
Observe that it was more convenient implementing the code with the TextArray property
than with the TextMatrix property. In a situation like this, it is more convenient to use
the TextArray instead of the TextMatrix property.

Using the ClipBoard/Clip Property


You can use click and drag operation to make a selection and then trigger an event to
carry out Copy/Paste operation on the data in the selection/clipboard.
Recall that in windows, the copy command is used to copy(or send) data to the clipboard
while the paste command is used to paste(or get) data from the clipboard. Cut operation
copies data to the clipboard and then delete the copied data. You can write codes in
Visual Basic to carry out the Copy/Cut/Paste operation using the clipboard. The methods
of the clipboard object is as shown in Table 4.3.
Table 4.3: Methods of the Windows clipboard object
S/n
Methods
Description
1
Clear
Clears data from the ClipBoard
2
GetText
Used to paste string from the clipboard
3
SetText
Used to Copy string to the clipboard
4
GetData
Used to Paste data other than string from the clip board.
5
SetData
Used to Copy data other than string from the clip board
6
GetFormat
Used to Format data
By combining the SetText and GetText methods with the selection properties, we can
write codes to Copy/Paste data from a textbox, listbox or flexgrid. For example, the code
ClipBoard.SetText = txtSurname.Text
Is used to copy data from the textbox to the clipboard. Similarly, the code used to paste
data from the clipboard to the textbox is as follows
txtSurname.Text = clipboard.GetText

196

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Changing the Font Properties


The CellFontBold and CellFontItalics Boolean properties are used to toggle the Bold and
Italics state of the cells of the grid control. These properties apply to the Activecell. For
example, to change the font of cells(5,7) to bold face, you first of all make it the active
cell and then use the CellFontBold property to make it Bold. This is implemented as
follows.
Grid1.Row = 5
Grid1.Col = 7
Grid1.Text= Universe
Grid1.CellFontBold =True
To change the FontSize, You use the CellFontSize property to get the size you desire for
the activecell.
Grid1.CellFontSize = 12
Other Cellfont properties used to change the font characteristics of a cell or range of cells
are

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

The data in the cell is aligned left, top.

flexAlignLeftCenter

The data in the cell is aligned left, center.

flexAlignLeftBottom

The data in the cell is aligned left, bottom.

flexAlignCenterTop

The data in the cell is aligned center, top.

flexAlignCenterCenter

The data in the cell is aligned center, center.

flexAlignCenterBottom

The data in the cell is aligned center, bottom.

flexAlignRightTop

The data in the cell is aligned right, top.

flexAlignRightCenter

The data in the cell is aligned right, center.

flexAlignRightBottom

The data in the cell is aligned right, bottom.

flexAlignGeneral

The cell content is of general alignment. This is left,


center for strings and right, center for numbers.

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

Formatting a range of cells


In Microsoft Excel, you can apply a formatting feature to a range of cells by selecting the
cells and then invoke the desired format option. You can also perform this same
operation using the MSFlexGrid. Before going ahead to perform formatting a range of
cells, we should first of all understand the coordinate geometry of selection. These are
summarized below.
A selection is an object with properties and methods (see Chapter 8)
The Area of the selection is equal to the number of cells in the selection.
The height of the selection equals the number of cells in the vertical span of the
selection while the width of selection is the number of cells in the horizontal span of
the selection.
The ColSel property is used to get the width of selection in an MSflexGrid control.
Also, the RowSel property is used to get (or set) the height of a selection.
For example, the code below creates a selection with Area of 10
grid.RowSel = 5
grid.ColSel = 2
The active cell is always the first cell in the selection. Hence changing the active cell
changes the current selection. By implication, before you can use code to create a
selection, you have to use the active cell to specify start of selection before using the
Rowsel and Colsel to specify the Height and width of selection respectively.
To create a selection starting from cells (3, 2) with height of 5 and width of 6 you invoke
the code
Grid.Row =3
Grid.Col = 2
Grid.RowSel=5
Grid.ColSel=6

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Never. The cells containing identical


content are not grouped. This is the default.

FlexMergeFree

Free. Cells with identical content always


merge.

FlexMergeRestrictRows

Adjacent cells in the specified row


containing identical content are merged

FlexMergeRestrictColumns

Adjacent cells in the specified column


containing identical content merge.

FlexMergeRestrictBoth

Restrict Both. Only adjacent cells within

201

Data Structures

the row (to the left) or column (to the top)


containing identical content merge.
To merge two or more adjacent cells, the contents of the cells have to be the same before
this can be done. Figure 4.9a shows the MSflexgrid with repeated entries in the first
column. Figure 4.9b was obtained after executing the code in Listing 4.13
Listing 4.13: Merging the cells of a flexgrid
Private Sub Flexgrid_dblClick()
1: With FlexGrid1
2:
.MergeCol(0) = True
3:
.MergeCells = flexMergeRestrictColumns
4: End With
End Sub
In Line 2 of Listing 4.13, the MergeCol property was used to specify the column to
merge. It te merge col property is set to false, the mergecell property would have to effect
on the FlexGrid. To merge row you have to use the merge row array property to effect it.

Figure 4.9a: MS Flexgrid with similar records in adjacent rows

202

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 4.9b: MS Flexgrid of Figure 4.9a showing Merged cells

Sorting Data in Grids


Like most data structures, grids have the capability of sorting data in selected rows
according to selected criteria. These criteria are specified using the constants defined in
the sort property.These Sort property constant are as shown in Table 4.6
Table 4.6 Setting for the sort Property of Grid Controls
Constant
Value Description
FlexSortNone
0
None. No sorting is performed.
Generic Ascending. An ascending sort, which
FlexSortGenericAscending
1
estimates whether text is string or number, is
performed.
Generic Descending. A descending sort, which
flexSortGenericDescending
2
estimates whether text is string or number, is
performed.
Numeric Ascending. An ascending sort, which
flexSortNumericAscending
3
converts strings to numbers, is performed.
Numeric Descending. A descending sort,
flexSortNumericDescending
4
which converts strings to numbers, is
performed.

203

Data Structures

FlexSortStringNoCaseAsending

FlexSortNoCaseDescending

FlexSortStringAscending

FlexSortStringDescending

FlexSortCustom

String Ascending. An ascending sort using


case-insensitive string comparison is
performed.
String Descending. A descending sort using
case-insensitive string comparison is
performed.
String Ascending. An ascending sort using
case-sensitive string comparison is performed.
String Descending. A descending sort using
case-sensitive string comparison is performed.
Custom. This uses the Compare event to
compare rows.

Table 4.3 shows that grids have a more involved sorting capability than the List. For
Instance the List has the following shortcomings

List can only sort in ascending order


List sorts without case sensitivity
List sort numbers using string sort such that 2 is considered greater than 12
List Gives Lower a higher sort order than the corresponding upper case character.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

21: Dim n As Integer


22: n = FreeFile
23:
Open "C:\Egbe.txt" For Output As #n
24:
Write #n,txtinputa.Text, txtinputb.Text, txtinputc.Text
25:
Close #n
End Sub
Listing 4.14 contains three event procedures, the first is the Click event of cmdExecute
used to obtain the the solution of a quadratic equation with two real roots. The Second
Event procedure is the Form Load procedure used to read data in the file and placed in
the textboxes when ever the Form loads. The third event procedure is the Unload event of
the Form used to save the data in the textboxes to the file when ever the application
unloads. (see Problem Set 4.9 )

Writing /Reading Arrays/ListItem To files.


Writing Listitems and arrays to files involves using Loops. These loops are difficult to
handle since the number of items in the file is not known and hence a For Next Loop
cannot be used. However, the EOF (End of file) function enables you to test whether a
record (an item in the file) is the last item or not. If the item is the last item, EOF returns
True otherwise it returns False. Using the EOF function with Do Loops enables you to
read array of data from the file. For example, the code in Listing 4.15 is used to write
array to sequential file.
Listing 4.15. Writing ListItems array to files
1:
On Error Resume Next
2:
Open C\Egbe.txt For output As #1
3:
For I=0 To LstData.Listcount-1
4:
Write #1, lstSurnames.List(I) lstfirstName.List(I),..
5:
Next I
6:
Close #1
To read data from the file to a list or an array you use the code
Listing 4.16 Writing arrays to files
1:
On Error Resume Next
2:
Open C\Egbe.txt For Input As #1
3:
Do Until EOF(1)
4:
Input #1,S1,S2
5:
LstSurname.Additem S1
6:
Lstfirstname.Additem S2
7:
Loop

206

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Where P is any property of state which could be Enthalpy(h), Entropy(s) or Specific


volume(v) or specific internal energy(u). Subscripts f and g are properties at the liquid
and vapour region while x is the quality of steam. Using Table Q4.5 design a program to
determine the property of state and a corresponding saturation temperature with input of
Pressure and Quality.
Figure Q4.5
Proposed dialog for
thermodynamic
property of state
determination.

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

Note that the specific internal energy is given as u = h - pv


Question 6
Given that the Menus of Figure Q4.6 contains the items shown in Table Q4.6.
Table Q4.6:Menu Items of Figure Q4.6
File
Edit
Data
New
Cut
Names
Open
Copy
Courses
Save
Paste
Exit

Sort By
Surname
First Name
Average
Physics
Chemistry
Biology

Help
About

Figure Q4.6: Proposed interface for students academic performance database.

210

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

b) Repeat problem 7a such that the Surname list remain sorted.


Question 8
The Formula used to calculate a certain parameter D as a function of time(t) and Pressure
difference represented as h is given as
D=
Design a program to calculate D.
Also make a plot of logarithm of D,h vs logarithm t using MS Chart control.
Use the data shown if table as default data.
b) Repeat problem 8 by plotting D h and t using log scale
Question 9
a) Design and implement an interface to drive Listing 4.14
b) Discuss the implications of using the Form Unload event to Write data to files.

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 .

A variable-length string can contain up to 2^31 (or 2147483648)


characters.

A fixed-length string can contain 1 to 2^16 (or 65536) characters.

declaration differ for both types of strings


1: Dim strX As String
2: Dim strX As String * 12
statement 1 declares a variable length string while statement 2 declares a fixed length
string with a maximum of 12 charcters.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Most programmers look at the concatenation operation as an addition process. Thus, it is


a common occurrence to have a statement like
Atim + aka= Atimaka
you see the addition operator has the same effect as the concatenation operator.
It could be more convenient if you declare variables and assign strings expression to the
variables and use the concatenation operator to do the same manipulation as follows.
Dim str1 As String, str2 as String
Dim str3 As String,str4 As String
str1 = Atim
str2 = aka
str3 = str1 & str2
str4 = str1 + str2

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

One can write it simply with the Like operator as


X like "[abcd]"
This evaluates to True if x is like any single character in the square bracket. The Like
operator saves you the stress of using the OR operator.
For a range of characters, you use the hyphen (-) to separate the lower and upper bounds
of the range. example
Result = x like "[b-m]"
means if x is any character between b and m, then the expression evaluates to True. You
can also have multiple ranges as follows
= x like "[b-ms-z]"
i.e if x is any single character between b and m or s and z then the expression evaluates to
True. The Like operator can also be used to match enumerated single characters, range of
characters and multiple ranges as
X like "[adgk-mptw-z,.]"
The expression above evaluates to True If x is any character in the list
"a","d","g","k","l","m","p","t","w","x","y","z",",","."
When a range of characters is specified, then it must appear in ascending sort order i.e
a - z, A - z, 0 - 9
To negate a Boolean expression, we use the exclamation sign before the character list as
in
X like "[!amT]"
The expression above evaluates to True if x is not a single character in the list
"a","m","T"
For the exclamation sign to function as a negation operator, it must be the first character
in the character list. If it appears after the first character, then it will be matching itself
instead of negating the expression. Apart from the square brackets, other characters like
"?", "*" and "#" are also used in pattern matching. The functions of these characters
are shown in Table 5.1.
Table 5.1: Like operator pattern matching characters
Characters in pattern
Matches in string
?
Any single character
*
Zero or move characters
#
Any single digit (0 - 9)

216

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Examples using these characters are shown below


(a)

The Boolean expression


x like "west*"
evaluates to True if the first four characters in x starts with "west". Hence the expression
evaluates to True if x is "western", "west" or "westerhof"
(b)

The Boolean expression


x like "west??"
evaluates to True if x contains six characters with the first 4 characters being "west".
Also, the expression
X like "?rai??"
evaluates to True if x contains 6 characters with the second, third and fourth characters
being "rai". i.e the expression evaluates to True If x is "Trains","Brains" etc.
c) The # operator works in the same way like the ? operator though it applies to only
digits (numeric character) unlike the ? that applies to any character whether numeric,
special or alphabetic.

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.

Option Compare Statement


This is similar to the Option Explicit and Option Base statement. It could be any one of
(1) Option Compare Binary
(2) Option Compare Text
(3) Option Compare Database
The option compare Database statement is used when working with databases. In this
chapter, we consider only the Text and Binary comparison mode and difer database until
volume 2 of this text.

String Arithmetic

217

Option Compare Text


This is a case insensitive comparison mode. Here "A" = "a" and "B" = "b".
If Option Compare Text is used and x stores the string "Western" then the expression
x like "WEST*"
evaluates to True.

Option Compare Binary


This is a case sensitive comparison mode. Here "A" "a" and "B" "b".
If Option Compare Binary is used and x stores the string "Western" then the expression
x like "WEST*"
evaluates to False.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Cstr, Str, Str$ Functions


The Cstr,Str and Str$ functions are used to convert other data types to string. This is
usually necessary before passing data to functions that require strings as argument(s), or
assigning variables of other types to string variables.

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.

Ltrim, Rtrim and Trim Functions


These functions are used to remove spaces before or after or both before and after a
string. The Ltrim function removes spaces before the first character of the string.
Example
Given the string
Egbe
You can evaluate the number of characters in the string using the LEN function.
intP=LEN( Egbe)
This returns 5. When you trim the extra space to the left of the string before evaluating
the Len as in
intP=Len(LTRIM( Egbe)) Returns 4
It is more convenient using variable as follows
Dim strname as String,intP as Integer
StrName= Egbe
StrName= Trim(StrName)
IntP=Len(strName)

220

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Code used to drive this interface is presented as Listing 5.2


Listing 5.2: Testing the Len and Trim functions
Private Sub cmdExecute_Click()
1:
Dim strName As string
2:
StrName=txtinput.Text
3:
lblOutput.Caption= Len(strName)
End Sub
Run the application. Type different Names in the TextBox and click execute. It should
give you the number of characters in the string. Use the spacebar to add spaces (i,e
depress the spacebar key while focus is on the TextBox. Click the execute button once
again. You should observe that the spaces are counted as characters.
Replace statement 3 with the statement
3:
strName = Len(Ltrim(StrName))
Run the application again. You should observe that the spaces to the left have been
removed. Use Rtrim and Trim in statement 3 and try running the application all over.
Add spaces to the left and right. Observe what happens and learn from your experience.
Also replace line 3 with the Val function and test with some sample strings. Note your
results.

222

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

UCase, LCase and StrConv Functions


These functions are used to toggle the case of a string. The LCase function converts a
string to entirely lower case(small letters) while the Ucase function converts a string to
entirely upper case(Capital letters) . Both functions accept string as the only argument
and returns strings. The StrConv is capable of converting a string to lower, upper or
proper case(First character of each word capitalised while others remain in lower case.
Same as Title Case in MS Word) depending on its setting. This setting is the second
argument of the StrConv Function. Some of the arguments of the StrConv function are as
shown in Table 5.2.
Table 5.2: Settings for the StrConv function
Setting

Example

Named Constant

Remark

StrConv(str1, 1)

vbUpperCase

Converts str1 to Upper case

StrConv(str1, 2)

vbLowerCase

Converts str1 to Lower case

StrConv(str1, 3)

vbProperCase

Converts str1 to Proper case

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.

The code in listing 5.3 is used to drive the ASCII interface


Listing 5.3: Testing ASCII functions
Private sub cmdConvert_Click( )
1:
Dim w As Variant
2:
w = txtInput.Text
3:
If optAscii.Value = True Then
4:
lblResult.Caption = Asc(w)
5:
ElseIf optChr.Value = True Then
6:
lblResult.Caption = Chr(w)
7:
End If
End Sub
In Listing 5.3, Line 1 declares a variable as Variant. This was done so that the variable
can accept both numeric and non numeric entries. Line2 assigns the text in txtInput to w.
Line 4 converts w to ASCII if the ASCII option is selected. Otherwise, w is converted to
character in line 6. Because this application has an input that can be an integer or string,
the variable has to be declared as variant otherwise a type mismatch error will occur.
Also, the ElseIf statement was used so that if an option is not selected, nothing should
happen. This is a good practice especially in situations where a default option was not set
at design time.

224

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

The KeyPress Event


An application of the ASCII function is found in the KeyPress event. Here An ASCII
parameter( called KeyAscii) is passed by reference; changing it sends a different
character to the object. Changing KeyAscii to 0 cancels the keystroke so that the object
receives no character. The Syntax of the Header of the Event Procedure is as shown
below.
Private Sub object_KeyPress(KeyAscii As Integer)
We implement a simple design that uses the KeyPress event to prevent certain entries in
a TextBox. The interface of Figure 5.4 would be used for this purpose

Figure 5.4:
Working with
the KeyPress
Event.

Listing 5.4: Restricting Keystrokes in the TextBoxes using ASCII


Private Sub txtInput_KeyPress(KeyAscii As Integer)
1:
If KeyAscii = 44 OR KeyAscii = 46 Then
2:
KeyAscii = 0
3:
End If
End Sub

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Split and Join Functions

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

Split(expression[, delimiter[, count[, compare]]])


Where the first parameter (expression) is the string to be split. The second Parameter
(Delimiter is the specified delimiter in the string. The Count specifies the number of
substrings to be returned. Omitting it returns all. The compare parameter is a numeric
value indicating the kind of comparison to use(Binary,Text or database)
Having being able to extract each character from a string and assigned to a variable
array, you can use your result for so many purposes. The interface of Figure 5.6 shows
how the split function can be used to evaluate functions.
Here you enter a function in the form f(x) = ax + b where a 0 and b can be >= 0 or < 0
in the Sample Function text box. You enter the point of evaluation in the X value
Textbox. On clicking execute it gives expected and reliable results as far as your
function follows the form specified above.

228

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 5.6
Evaluating
polynomial
Functions with the
Split function.

Code used to drive this interface is as shown in Listing 5.5


Listing 5.5: Testing the Split Function
Private Sub CmdExecute_Click()
1:
Dim strA() As String, strF As String
2:
Dim dblX As Double, dblY As Double
3:

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

The Mid Function


The mid function is a powerful function that can perform the job of both the split and
join function. With the Mid function, loop index can be used to traverse each character in
a string. Basically, the Mid function is used to extract a substring from a given string. The
syntax of the mid function is given as
Mid(string, start[, length])
Here, string is the string in question, start is the character position in string at which the
part to be taken begins and length specifies the number of characters to return. If length
is not specified, then all the characters from start to the end of string is returned. Note
that Length is the only optional argument.
Given the string
StrState = CrossRiverState
Mid(strState,3,4) gives ossR
i.e four characters from
the third position. Also
Mid(strState,2,2) returns ro and
Mid(strState,1,1) returns C i.e the first character in the string
Mid(strState,6) returns "RiverState.
This is so because when the number of characters to return is not specified, then the Mid
function returns all the characters from the stated position to the end of the string.
Generally, Mid(strWest,n,1) gives the nth character in the string. This is a very
important relation especially when n can increment itself(i.e when it is a loop index).
In loops, the mid function can be used to traverse a string and also Split the string in any
manner. It is very flexible and amenable to manipulations with any kind of loop structure.
Listing 5.6 is a code segment used to split a String into an array using the mid Function
Listing 5.6: splitting a string using the Mid function
1:
Dim strWest as String, intN as integer
2:
Dim strA() as string, I as integer
3:
strWest = THANKGOD
4:
intN = Len(Trim(strWest))
5:
Redim strA(intN)
6:
For I = 1 to intN
7:
strA(I) = Mid(strWest, I , 1 )
8:
Next I

230

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Converting Numbers to Base 10

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

Listing 5.7: Conversion of numbers to base 10 using the split function


Private Sub cmdExecute_Click()
1:
Dim strNum as String, I as Integer, A() as String
2:
Dim Sum as String, N as integer, B as Byte
3:
StrNum = txtNumber.Text
4:
B = txtBase.Text
5:
A = Split(strNum,Chr(32))
6:
N = Ubound(A)
7:
Sum = 0
8:
For I = 0 To N
9:
Sum = Sum + val(A(I)) * B ^ (N I)
10: Next I
11: lblResult = Sum
End Sub

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Ordinarily, this is quite simple. However, implementing it with a computer program


looks difficult. The problem lies in the fact that no simple mathematical routine exists
that will help us evaluate Equation 5.4 which is obviously a mode arithmetic involving
characters and numbers. With strings, this problem could be solved with less difficulties.
The steps used for the implementation of this are outlined below.

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

Assuming D(I) = A, then D(I) = 65-55 = 10

Carry out the conversion to base 10 as usual using equation 5.3.

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

This function is used to reverse a given string. Given the string


T = "Paul"
And

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

divided by 5 remainder 1 integer part 0

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

13: lblResult.Caption = strReverse(strSum)


End Sub
In Line 7 the ReDim Statement was used with the Preserve keyword to Preserve array
values as the Size of the array changes. Line 12 joins the array using an empty string as
the delimiter. Line 13 uses the strReverse function to reverse the string. Compare listing
5.8 to listing 3.14 used for the same purpose.

The Mid Statement


The Mid statement has the same syntax as the mid Function. It replaces a specified
number of characters in a Variant (String) variable with characters from another string.
Given the String
strRegion = West
Mid(West,2,2) =
an
Want
Mid(West,1,1) = E
in strRegion with E

This changes strRegion to


This replaces the Character

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.

Encryption and Decryption


The popularity of the internet has made data security a very important area of concern in
computing. One of the methods used to implement data security is through Encryption.
Encryption involves changing the status of information so that a third party can not make
any meaning out of it. A common and simple way of encrypting string is to increment
or decrement the ASCII or each character in the string. Given the String Ebam on
adding one to the ASCII and converting to string gives the result Fcbn. We say the
Data or string Ebam has been encrypted. You can decrypt it by subtracting one from
the ASCII to get the original string. By combining the ASC,CHR,MID statement and
MID function, you can perform very powerful encryption on a given string. Use the
interface of Figure 5.8 to test listing 5.9 used to encrypt text.

String Arithmetic

235

Figure 5.8
Interface used to Test
Encryption program.

Listing 5.9: Implementing Encryption with string functions


Option Explicit
Option Compare Binary
Private Sub cmdExecute_Click()
1:
Dim strSample as String,I as Integer
2:
Dim T as Variant, intLen As Integer
3:
StrSample = txtInput.Text
4:
intLen = Len(strSample)
5:
For I = 1 to intLen
6:
T=Mid(strSample,I,1)
7:
T = ASC(T)
8:
T = T + 1
9:
T = Chr(T)
10:
Mid(strSample,I,1) = T
11: Next I
12: lblResult.Caption =strSample
End Sub
The Mid function was used in Line 6 to extract the ith character from the sample
string(Line 6) and then passed to the ASC function(line 7) to convert the extracted
character to ASCII value. One is added to this ASCII value(Line 8) before passing it to
the CHR function to convert to character(Line 9). In line 10, the mid statement was used
to replace this ith character. Line 11 increments I and line 12 assigns results to the caption
property of the label.
The encryption shown in listing 5.9 is considered too simple, you can perform a more
powerful encryption using the Randomize and Rnd Function

236

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Instr and InstrRev Function


The Instr Function returns a variant (long) specifying the position of the first occurrence
of one string within another.
Given the String strRegion = Western
You can use the Instr Function to find the position of t in the String. This is done as
follows
P = Instr(strRegion, t) it returns 4
also
Instr(strRegion, r) returns 2
A given String can be divided into two parts based on the position of a targeted character.
This is similar to the Split function. The limitation of the Split function is that the string
might be divided into more that two parts if the search string occurs more than once. In
situations like this, you may need to use the Ubound and Join function to accomplish
your objective. This is time consuming and therefore not recommended when time and
skills are constraints.
Note that when the String is not found, Instr Returns Zero. If Instr returns a result greater
than zero then the substring occurs atleast once in the String.
Given the String 23, 3
You can use the Instr function to find the position of comma and use the Left and Mid
functions to split the entry as follows
strT = 23,3
intP = Instr(strT, ,)
strX = Left(strT,P-1) x holds 23
strY = Mid(strT,P+1)
holds 3
In practise, it is often better to use If statement or Select Case to ensure that P is
greater than zero before proceeding otherwise a run time error results.
The Complete syntax of the Instr function is
InStr([start, ]string1, string2[, compare])
Where
1) Start sets the starting position for each search. If omitted, search begins at the first
character position.
2) String1 is the string being searched
3) String2 is the String expression sought.
4) Comapre is an optional parameter. It specifies the type of string comparison. If
compare is Null, an error occurs. If compare is omitted, the Option Compare setting
determines the type of comparison.
The compare argument settings are as shown in Table 5.3.

237

String Arithmetic

Table 5.3 : Settings of the compare arguments


Named Constant
Value
Description
vbUseCompareOption
-1
Performs a comparison using the setting of the
Option Compare statement. This is the default
setting
vbBinaryCompare
0
Performs a Binary comparison.
vbTextCompare
1
Performs a Textual comparison.
vbDatabaseCompare
2
Microsoft Access only. Performs a comparison
based on information in your database

The InstrRev Function

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

However, InstrRev(strSample, a, 3) returns 2


This is because from the third position on the right, a occurs in position number 2. If
we ignore case sensitivity, the function takes the form
InstrRev(strSample, a,3,1) this returns 7
The differences between the Instr and InstrRev function are demonstrated using the
interface of Figure 5.9 with Listing 5.10
Features of the program
Two TextBoxes with names txtSample and txtSearch; one slider with name sldPosition
and one label(lblResults) with FixedBorders. Other controls on the form are two frames
with two OptionButtons on each. The names of the OptionButtons are optLeft, optRight,
optSensitive and optInsensitive. The command buttons have names reflecting their
captions.

238

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Left and Right Function


The Left and Right functions are used to extract or inspect extreme characters from a
string.
The Left function returns a Variant (String) containing a specified number of characters
from the left side of a string. The syntax of the Left function is
Left(string, length)
On the other hand, the Right function returns a Variant (String) containing a specified
number of characters from the right side of a string. The syntax of the right function is
Right(string, length)
In both syntaxes, string is the string being considered and length is used to indicate how
many characters to return. If length is 0, a zero-length string ("") is returned. If length is
greater than or equal to the number of characters in string, then the entire string is
returned.
Consider the string
strRegion = Western Nigeria
Right(strRegion,2) returns ia
Left(strRegion,3)
returns Wes

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

We now consider some applications of the Left and Right functions.


Recall that under the section on the Split Function, the function ax+b was evaluated. It
was also noted that the Split Function can not be used to evaluate the function a + bx
because the x value occurs at the extreme. You can use the InstrRev function to find the
position of + or - and subsequently change the string to the form bx + a which can
then be evaluated using the interface of the function program.(Figure 5.9)
We now proceed with the steps to change a function of the form c + dx
dx + c

to the form

The Steps involved are


1. Find out the sign of C. if it has no sign concatenate positive sign to it as follows
If Left(strF,1) Like [!-+] Then
strF = + & strF
End if
Observe how the Like operator was used to simplify the scenerio. I.e if the first
character in the string is not like or + then it should concatenate + to the string.
2. From the second character, use the Instr function to find out the position of the next
plus or minus sign as follows
P = Max(Instr(2,strF,+) ,Instr(2,strF,-)
3. Take the string from point P to the end and assign to T1 and from the beginning to
the character before that point and assign to T2 i.e T1 holds +dx and T2 holds
+c as follows
T1 =Mid(strF,P) and T2= Left(strF,P-1)
4. Concatenate T1 and T2 to give the string in the form dx + c
The Implementation is as shown in Listing 5.12.
Listing 5.12: Reversing a function using the Instr function
Option Explicit
Option Compare Binary
Private Sub cmdExecute_Click()
1: StrF=Trim(txtInput.Text)
2: IF LEFT(strF,1) Like [!-+] Then
3:
StrF = + & strF
4: End If
5: intP1 = Instr(2, strF, +)
6: intP2 = Instr(2, strF, -)
7: intP = intP1 assume that intP1 is larger
8: If intP2 > intP Then intP = intP2
9: strT1 = Mid(strF,intP)
10: strT2 =Left(strF,intP-1)

242

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

11: strF = strT1 & strT2


12: lblResult.Caption = strF
End Sub
To test this application, design a Form with a TextBox(txtInput) and Label(lblResult).
Annotate the TextBox/label appropriately and trigger the code using a
CommandButton(cmdExecute).

Converting Numbers with Decimal Part to Fraction

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

Working with fractions

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.

Decimal and Binary Shifting

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

A standard way to represent a real number called Standard Notation is obtained by


shifting the decimal point and supplying an appropriate power of 10(for decimal
numbers, power of 2 for binary). For example, given the number 0.00000234 we
express it in Standard Form as 2.34 x 106 or in the more popular machine form as
2.34E06.
In the same way, the binary number 0.001011 is expressed by shifting the decimal n
places to the right to obtain 1.011 x 2-3
We can use our string functions to perform the conversion. The technique is to use Instr
function to find the first position of the character 1 in the string. If Instr returns n then
the character 1 appears in the nth position and the number in standard notation is
obtained as
1. & MID(strA,n+1)

&

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

Format Currency Function


The Format Currency function is used to format a number and present results in currency
style. For example given the data 34257,
Y = FormatCurrency(34257)
Returns
$34,357.00
Note that the default currency sign is the dollar ($). The format currency Adds this
currency sign ($), comma separator (,) and two decimal places by default.
The complete syntax of the format currency function is
Formatcurrency
(Number,
NumDigitAfterDecimal,
Include
LeadingDigit, UseparensforNegativeNumbers,GroupDigits)
These parameters are discussed below
Number: This is the number or the numeric expression to be formatted. Default is 2.d.p
NumDigitAfterDecimal: Used to specify the number of decimal places in the output
IncludeLeadingDigit: Used to ascertain whether zero should be displayed to the left of
decimal point or not. This is a Boolean parameter that applies to fractional numbers only.
True means leadingDigit should be added (e.g. 0.572) and false means leading digits
should not be added (e.g. .572): Default is Includeleadingdigit.
Useparensfornegativenumbers: Used to verify whether negative numbers should be
returned with the conventional negative sign or enclosed with parenthesis e.g. -27 or (27).
This is a Boolean parameter with True meaning use negative sign and False meaning use
parenthesis. Default is use negative sign.
GroupDigits: Verify whether number/ expression should be grouped in threes from the
right or not. Here True means group digits e.g. (2,347,248) and False means don't group
(2347248) Default is GroupDigits.
The Format Parameters; UseParensForNegativeNumbers, IncludeLeadingDigit and
GroupDigits are not strictly Boolean parameters. In Visual Basic parlance, we say they
are tristate parameters. A tristateparameter has three settings; vbTrue, vbFalse and
vbUseDefault. When the vbUseDefault option is selected, then the function determines
the True or False setting based on the Regional settings in the control panel. In Nigeria
our regional setting is vbTrue.

246

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Format Percent Function


The FormatPercent function is used to format results and present results in percentage.
Given the number 0.872, the format percent formats this number as
=FormatPercent(0.872)
and returns 87.20%
The basic difference between the FormatPercent and the FormatCurrency is that the
FormatCurrency appends a currency sign in front of the number while the FormatPercent
appends a percent sign "behind" the number.
The complete syntax of the formatpercent function is
Formatpercent(Number,NumDigitAfterDecimal,IncludeLeadingDig
it, UseParensForNegativeNumbers,GroupDigits).
Observe that the parameters are the same as the parameters in the FormatCurrency
function.

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

In the second example, the optional parameters NumDigitsAfterDecimal and GroupDigits


were specified, hence the result. Observe how commas were used to omit the
UseParensForNegativeNumbers and IncludeLeadingDigit parameters.

FormatDate Time Function


This function is completely different from the previously discussed format functions. It
accepts a string representing a date and a named constant (or constant) and returns a date
in the format specified. Example given the date #17/01/1977# and the format
=FormatDate time ("01/17,77", vbLongDate)
This returns Monday 17th, January 1977.
Table 5.3 presents all the constant/named constants used with the formatDateTime
function.
Table 5.3 Named Date/Time Constants
Named constant
Constant
vbGeneralDate
0
VbLongDate

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Customizing The Format Function

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Some of the features of the message box of Figure 5.9 include

It displays the message The selected floppy disk is not in use. Check to "

It displays a critical icon

It displays two buttons, Retry and Cancel

It has a title, Microsoft Word

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

Message Box Buttons


Apart from Retry and Cancel, the message box can display five other combination of
buttons. Table 5.6 displays all possible button combinations available in Visual Basic
Table 5.6: Visual Basic Message Box Buttons
Button Combination
Value
OK Only
0

Name Constant
VbOKonly

OK and Cancel

VbOKCancel

Abort, Retry And Ignore

VbAbortRetryIgnor

Yes, No and Cancel

VbYesNoCancel

Yes and No

VbYesNo

Retry and Cancel

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.

Message Box Icons


Other icons that can accompany the message box are the Exclamation, the Information
and the Question icons. The named constants and value of the icons are as shown in
Table 5.7
Table 5. 7: Visual Basic Message Box Buttons
Icons
Value
Value
Critical Warning
16
vbCritical
Query (Question)

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

1: Dim strMessage As String, strTitle As String


2: strMessage= "Are you sure you want to Exit " & _
"This Application ?"
3: strTitle = "Confirm Exit"
4: MsgBox strMessage, 32 + 4, strTitle
Figure 5.11
Message Box with a
message, buttons, icon
and title.

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.

Using the Message Box as a Function


The message boxes discussed in the previous sections have been issued as statements.
This is a very simple way of using the message box but it is however, not popular. A
popular and more purposeful way of using the message box is as a function. Like all
functions, the message box must return a value. The value returned by the message box
depends on the buttons clicked. Since the buttons have integer values, the message box
therefore returns an integer corresponding to the button clicked.
The return values of the windows message box are tabulated in Table 5.8

253

String Arithmetic

Table 5.8: Return Values/Constants of Windows Message Boxes


Button clicked

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Controlling The Default Button

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.

Message Box with Optional Arguments


A message box can be issued without the second and third arguments. In this case the
default button (OKOnly) and the default title(Project name) is used. In most message
boxes used in windows application, the third argument is usually omitted. This is why the
project name is displayed as the title. You can omit the second argument by just typing 0
after the comma or leaving an empty space as follows:
MsgBox Invalid Entry, , Error

255

String Arithmetic

Or

MsgBox

Invalid Entry, 0 , Error

String Functions and the Message Box Message

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.

Input Validation and Errors


Input validation is a very important topic in software Engineering. This is because users
inputs have to be screened so that runtime errors due to unexpected input would not crop
up. Apart from runtime errors, unexpected input could cause logic error that might be
very difficult to detect in large programs. Invalid input could be of the form of data type
mismatch or data range error among others.

256

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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)

Error 13 results when data of a different type is assigned to a variable expecting a


conflicting type. You avoid Error 13 or Mismatch error by changing data type(input) or
changing declaration.
Changing data type or declaration defeats the aim of the program and hence it is not the
recommended option. Other techniques used to arrest this error are:
1. Use the VAL function so that the entries are converted to numeric VALue before
being assigned to the Variable. In this case 3b will be converted to 3 before
assignment.
2. A second Technique is to use the KeyPress event and ASCII functions to divert non
numeric keystroke. This is actually OK. However, it does not always give the user
an idea on the error committed.
3. A third method is to use controls that will enable the user enter strictly numeric data
without using the Keyboard.
4. A very vocal and common technique used to enforce valid data entry is the use of
Message Box.

Data Inspection Functions


The data inspection functions are used to verify whether an argument is of a desired type
or not. If it is otherwise, a message box is used to frown at invalid data. Calculations
often proceed after validation is OK. Table 5.10 shows the Visual Basic data inspection
functions

258

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Table 5.10: Data Inspection Function


S/no

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Input Validation using the Validate Event

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

,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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Hence or otherwise, write a program to multiply the matrices


A = {3,2,-1,3;3,2,21,4;-1,0,3,4;2,-3,4,5} and B = {2,1;3,4;-2,7;2,9} expressing your
results in Linear form.

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

Functions and Sub Procedures

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Public Function Len(X As String) As Integer


.
.
End Function
Function declaration is as important as function definition. So we advise that you get
used to the Visual Basic function declaration syntax. Note that in function declaration,
you specify the data to be passed to the function as function parameters and also the data
type of the results expected from the function as function return type. These are important
to enable the compiler trap errors at compile time.
Though most functions are made public so that they can be accessed outside their
module, a function is made private when it can only be accessed within its module. Static
functions retain their values on separate calls of the function. Replacing the Public key
word with either Private or Static changes the scope of the function to the desired scope.
You should have enough reason to make a function Private.

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.

Functions and Sub Procedures

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

Implementation of Function in Visual Basic

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Functions and Sub Procedures

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

7. Save your Project.

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.

Writing Programs with User Defined Functions


We now demonstrate how to write a test driver for the Max function. The interface
needed for this task is as shown in Figure 6.6.

Functions and Sub Procedures

273

Figure 6.6
Testing the Max function
with Visual Basic Form and
controls.

The Object module used in the implementation is as shown below


Listing 6.1 Using a User Defined function in a Visual Basic program
Option Explicit
Private Sub cmdExecute_Click()
1: Dim intFirst As Integer,intSecond As Integer
2: Dim intThird As Integer
3: intFirst = txtFirst.Text
4: intSecond = txtSecond.Text
5: intThird = txtThird .Text
6: lblResults.Caption = Max(intFirst,intSecond,intThird)
End Sub

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)

Using the ByVal and ByRef Keyword


In the max function written above, the arguments were passed ByRef ( by reference). The
implication of this is that when calling the function in a main program, the argument must
agree in type with the function definition. Hence, if a variable declared as long is passed
to the function whose parameter was declared as integer, then an error pops up as shown
in Figure 6.7.

274

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Functions with one argument

3.

Functions with two arguments

4.
5.

Functions with three or more arguments


Functions with indefinite arguments

6.

Functions with array(s) as argument(s)

Functions and Sub Procedures

7.
8.

Functions which return array


Function with optional argument(s)

9.

Function with objects as argument(s)

10.

Function with object as return Value

275

Functions With No Argument


Two examples of Visual Basic functions without arguments are the Randomize function
and the Rnd function. Most functions with no argument are actually functions that return
constants. E.g . we can write a function that returns the constant pi as follows.
Public Function Pi() as double
Pi =22/7.
End Function
Note because no parameter appears inside bracket, it means the function we are writing is
a function with no argument. It should always return a constant. Mathematical constants
are often written as functions with no argument.

Functions With One Argument


Functions of the form y = f(x) are the most frequently occurring functions. They accept
one argument and return one value. All the mathematical functions available in Visual
Basic are functions with one argument. Once you understand the tricks, writing the
functions is simple and interesting. Use the argument as input in your calculations and
assign result to the function name.
Given a function which accepts a number and returns its Square, you write it as follows
Function Square (ByVal Number As Integer) As Integer
Square = Number * Number
End Function
The function above is the simplest example of a function with one argument. Others are
mainly in the form of a polynomial and tailor series as follows
Public Function F(ByVal X As Double) As Double
F = X^2 3*X - 4
End Function
The function above are used when writing programs to solve non linear problems
iteratively.

276

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Functions with two Argument


Examples of functions with two variables abound in Science and Engineering. We will
only consider a few examples and keep the rest as exercise. Converting numbers from
one base to the other is a good example of a function with two arguments. Others include
getting the Highest Common Factor of two numbers as well as the Lowest Common
Multiple. Scores of pages will be needed to list and implement all the problems that lend
themselves to manipulations with two arguments.

Functions and Sub Procedures

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Functions with three Arguments


There is no big deal concerning functions with three arguments, each argument stands
for a particular purpose. The mid function is a good example of a function with three
arguments. You can write functions with up to five and more arguments once each
argument provides data for a parameter. However, when the data provided are all of the
same type like in the Max, Sum and HCF function, then treating it as function with three
or more arguments is actually disturbing. These are considered as functions with
indefinite arguments. We will demonstrate examples of functions with three arguments
by modifying the Mid Function such that it can return the characters in a particular
range.
E.g given the String Ekukunela
we can write a function that will extract a given number of characters before a specified
position.
e.g
MMID(strA, 7, -3) should return kun
and

MMID(strA, 4, -1) should return

Clearly this is a function with three arguments. The implementation of this is left as an
exercise.

Functions With Indefinite Arguments


The name function with indefinite arguments could be intimidating at times. We will
rather call it functions with variable number of arguments. The idea here is that you
implement a function that can work with one argument, two arguments and/or up to 255
arguments or 32767 arguments as the case may be.
The technique used is to specify the first argument or the First and second arguments and
then use an array as the last argument. Since this array is an array of parameters, it is
called ParamArray. The paramarray is actually the argument with variable number of
arguments. If two arguments are specified with the paramarray then the function must
have atleast two arguments. If three are declared with the paramarray, then at least three
arguments are required. However, if the only argument is the paramarray then the
function can work with or without arguments.
The max function implemeneted as a parameter array with at least one argument is as
shown in Listing 6.5
Listing 6.5: Implementing a function with indefinite arguments
Option Explicit
Function max(ByVal X1 As Integer, ParamArray X2()) As _
Double
1:'Set max equals the first Required argument
2:
Dim I As Integer

Functions and Sub Procedures

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.

Functions with Optional arguments

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Function Mid(Source As String, start As Long, Optional _


count) As String
.
.
End Function
The declaration above dictates that the mid function should have at most three arguments
with two required and one optional argument. Note the presence of the optional keyword
in the declaration. We can illustrate a practical example of function with optional
arguments with the problem of finding the sum of an arithmetic series. The sum of
numbers from 1 to 10 is an example of an arithmetic series. Here the start point is one
and the increment and limits are 1 and 10 respectively. One can write a function which
evaluates the sum of the AP and any other AP for specified values of start point, end
point and increment with assumption that if the first argument and the increment are
missing, then default values of one(1) are specified. In other words, we also refer to
functions with optional argument(s) as functions with default argument(s). Listing 6.6
shows an implementation of function with default arguments.
Listing 6.6: implementation of function with optional arguments
Public Function SumAp(ByVal Limit As Long, Optional start,
_ Optional increment) As Long
1:
Dim I As Long
2:
If IsMissing(start) Then start = 1
3:
If IsMissing(increment) Then increment = 1
4:
SumAp = 0
5:
For I = start To Limit Step increment
6:
SumAp = SumAp + I
7:
Next I
End Function
The header of the function declares the sumAp function as Long with three arguments.
The first argument is declared as Long and is a required argument. The second and third
arguments are optional and are declared as variant because like paramarray, optional
arguments are always declared as variant otherwise a compile error pops-up. Line 2 of
the function uses the IsMissing Boolean function to find out if the argument start is
missing. The IsMissing function returns True if the start argument is missing and hence
a default value of 1 is assigned to the start argument. Line three does the same thing like
the increment parameter. Line 5 sets the loop in motion that generates the sequence
while line 5 updates SumAp with the current index. The Immediate window was used to
test the function and the results obtained are displayed in the Table 6.1

281

Functions and Sub Procedures

Table 6.1; Tests results for the SumAp function using the immediate window.
Syntax
Print

Result

Implication

15

Second and third arguments missing, 1 and


1 were assumed

Print Sumap(10,2)

54

Last argument missing, 1 was assumed

Print Sumap(13,,2)

49

The second argument is missing, 1 was


assumed

Print Sumap(10,2,5)

The full syntax was used

Sumap(5)

Print Sumap(,1,3)

Error

Syntax Error,First argument not optional

Print Sumap(,,3)

Error

Syntax Error,First argument not optional

Print Sumap()

Error

Syntax Error,First argument not optional

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

Default arguments enable you to enforce types instead of using variant

Default arguments avoid the IsMissing function.

Default arguments enable you avoid unnecessary type conversion

282

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Functions with Array As Argument


Array declared of any type can be passed to functions just like any other variable.
Usually, it is compulsory that you pass a dynamic array because the size of the array to be
passed by the user might not be known. In the body of the function the Lbound( Lower
Bound) and Ubound of the array are then determined.

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:

Dim Size As Integer, index As Integer, Sum As Double


Dim UB As Integer, LB As Integer
If IsMissing(UpperBound) Then
UB = UBound(A)
Else

Functions and Sub Procedures

6:
7:
8:
9:
10:
11:

If UpperBound > UBound(A) Then


UB = UBound(A)
Else
UB = UpperBound
End If
End If

12:
13:
14:
15:
16:
17:

If Not IsMissing(LowerBound) Then


LB = LowerBound
If LB < LBound(A) Then LB = LBound(A)
Else
LB = LBound(A)
End If

283

18: Size = UB - LB + 1'obtains the size of the array


19: For I = LB To UB
20:
Sum = Sum + Arraydata(I)
21: Next I
22: Average = Sum / Size
End Function
In Listing 6.9, Line 4 assigns the upper bound of the array to be the desired upper bound
if the upperbound parameter IsMissing. Lines 6 to 10 handles the case where the
upperbound is not missing. In this case the user is given a choice to specify his/her
lower and /or upper bound and also giving him/her a potent weapon to mess your
function up. This is actually the reason why a conditional statement was used to check
whether the supplied upper bound is greater than the actual upperbound. When the
supplied upperbound is greater than the actual upperbound, then the actual upperbound is
used.
Lines 12 to 17 does the same thing with the lower bound parameter.
Line 18 computes the number of terms to be averaged.
With a good understanding of the average function, you can also write a function that
returns other statistical parameters.

Functions Which Return Array


Writing a function that returns an array is like an uphill task. This is because before
arrays can be used in a program, it has to be declared appropriately as a dynamic or
static array. However, if we remember that the variant data types can accept numbers,

284

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Functions with Object as Argument/Return Type


An object as used in Visual Basic and other object oriented programming (OOP)
languages is an instance of a class. A class itself is a collection of variables (or data)
combined with a set of functions. An instance of a class is called an object. The data in a

Functions and Sub Procedures

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:

Dim strTemp As String, T As String, I As Integer


Select Case intsetting
Case is <= 0
Mlen = Len(txtBox.Text)
Case 1

286

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Functions and Sub Procedures

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

Dim strTemp As String, T As String, index As


Set Mlen =txtBox object variables must be set
Select Case intsetting
Case is <= 0
Mlen.Height = Len(txtBox.Text)
Case 1
StrTemp = Trim(txtBox.Text)
Mlen.Height = Len(strTemp) :Mlen.Tag =
Case 2
StrTemp = LTrim(txtBox.Text)
Mlen.Height = Len(strTemp) :Mlen.Tag =
Case 3
StrTemp = Rrim(txtBox.Text)
Mlen.Height = Len(strTemp) :Mlen.Tag =

As

Integer

strTemp

strTemp

strTemp

288

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

This was explained in Chapter 3 (Listing 3.13)


Listing 3.13 used the Do Loop to evaluate the HCF. Listing 6.13 shows the recursive
implementation of Listing 3.13.
The Functional implementation of the Euler GCD recursive relation is given as follows

289

Functions and Sub Procedures

Listing 6.13: Recursive implementation of the Listing 3.13


Public Function HCF(ByVal A as Integer,ByVal
Integer) As Integer
1:
If A Mod B = 0 Then
2:
HCF = B
3:
ElseIf A Mod B <> 0 Then
4:
HCF = HCF(B, A Mod B)
5:
End If
End Function

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

A recursive implementation of the factorial problem is as shown in listing 6.14


Listing 6.14: Recursive implementation of the Listing 6.3
Public Function Fact(ByVal N As Integer) As Integer
1:
If N = 0 OR N = 1 Then
2:
Fact = 1
3:
ElseIf N > 1 Then
4:
Fact = Fact(N 1) *
N
5:
End If
End Function
Observe that the loops are not used to implement recursive functions because the
language does the internal looping while the programmer just writes the code with a
conditional statement and Visual Basic handles the rest.

290

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Functions and Sub Procedures

291

Listing 6.15: Implementation of the swap sub procedure.


Public Sub swap(number1 As Double, number2 As Double)
Dim Temp As Double
Temp = number1
number1 = number2
number2 = Temp
End Sub
The procedure above swaps two numbers. It assigns the first number to Temp and then
assign the value in number2 to number1 and thereafter assigns the value stored in Temp
to number1. We try a simple application to test this procedure.
To test this Sub procedure, we use the interface shown in Figure 6.8 . The
implementation is as shown in Listing 6.16
Figure 6.8
Testing a Sub Procedure with
a Visual Basic program

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Passing Objects To Sub Procedure


You can now see that writing sub procedures are as easy as writing functions. In Sub
procedures, once you pass your arguments, you dont need to worry about return value.
The sub procedure performs some task on the objects. This feature makes it capable of
returning multiple values with a single Call to the Sub. We illustrate an example with a
sub to Select the text in a textbox. Here a textbox has to be passed to the sub procedure as
an object. Once the sub routine is called, the textbox becomes highlighted automatically
Listing 6.17: Passing objects as argument to Sub procedure
Public Sub SelectTextBox(txtBox As TextBox)
1: txtBox.SelStart = 0
2: txtbox.SelLength = Len(txtBox.Text)
3: txtbox.SetFocus
End Sub
The subroutine in Listing 6.17 selects all the text in the textbox passed to it once it is
called. This shows that a subroutine can be used to call various parts of a program for
automatic execution. Test this program by placing a textbox on the Form and then enter
the following code in the Click or dblClick event of the Form.
Call SelectTextBox(txtSurname)

293

Functions and Sub Procedures

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

When different Autoshapes are passed to a routine to format

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.

Returning Multiple Values From A Sub Procedure


We use a simple quadratic equation with two real roots to demonstrate how a sub can
return multiple values. The equations used are of the form

b + b 2 4ac
X1 =
2a

X2 =

b b 2 4ac
2a

294

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Functions and Sub Procedures

295

Listing 6.20: Using Sub procedure that return multiple values


Private Sub cmdExecute_Click()
1:
Dim A As Double, B As Double, C As Double
2:
Dim X1 As Double, X2 As Double
3:
A = txtA.Text
4:
B = txtB.Text
5:
C = txtC.Text
6:
Quadratic A, B, C, X1, X2
7:
lblX1.Caption = X1
8:
lblX2.Caption = X2
End Sub
In Listing 6.20, the high point is in Line 5. Here A, B, and C are passed by value to the
quadratic sub while X1 and X2 are passed by reference. The quadratic sub procedures
calculates X1 and X2 and passed by reference hence changing the value stored in X1 and
X2. These values are then used to set the caption of the lblX1 and and lblX2 in line 7 and
8 respectively. Note that for Listing 6.20 to work, the Listing 6.19 must be visible in the
module where Listing 6.20 exists.

Event Sub Procedure


Event procedures are also subroutines and called in the same way user defined
procedures are. For example a program written in the dblClick event of the Form can be
called directly by double clicking the form. Another method that can be used to call the
event procedure is to use the standard method of calling sub procedure using the call
keyword as follows
Call Form_dblClick
Or with the call keyword as
Form_dblClick
For event procedure with parameters, you call them as usual by passing appropriate
variable/data types for the parameters.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Functions and Sub Procedures

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Functions and Sub Procedures

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

Controls Array and Menus

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.

Creating Controls Array


Though elements of controls array can be loaded and unloaded at runtime, controls array
must be created at design time before they can be used in code. Three methods used to
create controls array are discussed below.

Creating controls array using copy and paste method


When a second instance of a control say a CommandButton with name cmdNum is
pasted on the form from the clipboard, a MessageBox(see Figure 7.1) pops up asking
you if you want to create controls array. On clicking yes, Visual Basic creates a control
array by giving the first an index of 0 and second an index of 1. The indices of
subsequent elements of the controls array are automatically incremented once Visual
Basic notices that the current name is same as an existing control. This method is the
most often used method of creating elements of a control array.

302

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 7.1
MessageBox
confirming the
creation of
control array.

Creating controls array using the Index property


The index property of all controls is usually blank(empty). By typing any unsigned
integer in the index property converts the control to a control array.

Creating controls array using the Name property


A third method of creating a control array is to give a control the same name with another
control in the same Form. When this is done, a message similar to that displayed in
Figure 7.1 is invoked.

NOTE
Once the first element of the control array has been created, any of the three methods can
be used to create other elements.

Event Procedures of Controls Array


Use any of the methods discussed above to create an array of CommandButton(cmdNum)
with five elements. Also create another CommandButton control with name cmdPlus and
a TextBox with name txtScreen. Configure your Form as Shown in Figure 7.2.
Figure 7.2
Using Controls Array.

Controls Array and Menus

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Properties of Controls Array


Controls array have the following properties
 Count : The total number of elements in the control array
 Ubound : The highest index of the elements of a control array.
 Lbound : The lowest index of the elements of a control array.
 Item : Used to identify a specific element in the array.
The Item property is used to reference a particular item in the array. E.g to reference the
item with index of zero you use the statement
cmdNum.Item(0).Caption
Since the item method is the default method of the array, you can use it without the item
method as follows
cmdNum(0).Caption
This is a more popular method of referencing an element of a control array(see Listing
7.1 Line 3). However, it makes more sense using it with the item method though it is
somewhat longer

Controls Array and Menus

305

Creating Elements of Controls Array at Runtime


One interesting thing about a control array is that its other elements can be added and
removed at run time using code. An element is added to the controls array using the Load
statement as follows
Load cmdNum(1)
The code above loads the second element of the control to the array.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Unloading controls array Elements at runtime


Codes can also be used to remove elements of a control array created at run time. This is
done using the unload statement. E.g. to unload a control array element with name
cmdNum and index of 2, then use the code
Unload cmdNum(2)

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

Controls Array and Menus

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

Giving Controls Array Element Equal Spacing


Control array elements are usually aligned Left or Top with elements having equal
vertical or horizontal spacing. We extend the principle used in Listing 7.3 to give more
than two control array elements equal vertical(or horizontal) spacing. Here, a control
structure would be used. Since array is involved, it appears simple. Remember that the
Top of an element of a control array other than the first is a function of the top of the
preceding element, the height of the preceding element and the separation between the
elements(see Figure 7.4). This is written using functional notation as
Topn = Topn-1 + Heightn-1 + Spacing .......................................... 7.1
Equation 7.1 is used in Listing 7.5 to create the CommandButtons shown in Figure 7.5
Listing 7.5: Creating and equi-spacing controls array Elements
Private Sub Form_Load()
1: Dim I as Integer
2: For I = 1 to 4
3:
Load cmdNum(I)
4:
With cmdNum(I)
5:
.Visible = True
6:
.Top = cmdNum(I-1).Top + cmdNum(I-1).Height + 200
7:
.Caption = I
8:
End With
9: Next I
End Sub
The code above loads 4 elements into the form with vertical spacing of 200.(line 6)
The Left as well as other properties of controls are same as the previous control array
element created . So you should expect the alignment and size displayed in Figure 7.5.
Line 7 was used to set the caption of each button.

308

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Controls Array and Menus

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Controls Array and Menus

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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)

One cycle complete


Start of Second cycle

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

Controls Array and Menus

313

Where n = Index of one dimensional array


C = number of column in matrix B
E.g A(7) to a matrix with 4 columns is B(7/4), 7 mod 4) = B(1,3)
With equation 7.2 , you can transfer values from a one dimensional array to a two
dimensional array and vice versa. The code in Listing 7.9 is used with the interface of
Figure 7.9 to demonstrate how to transfer Items from a TextBox array to a grid. The
program interface is as shown in Figure 7.9.
Listing 7.9: Transfering Items from a TextBox array to a FlexGrid
Private Sub cmdCreate_Click()
If txtData.UBound <> txtData.LBound Then UnloadTextBoxes
1: Dim I As Integer, K As Integer
2: Dim NPC As Integer
'NPC= Number per column
3: Dim N As Integer 'Count of control
4: NPC = Me.txtCols.Text
5: N = Me.txtCols.Text * txtRows.Text - 1
6: For I = 1 To N
7:
Load txtData(I)
8:
txtData(I).Visible = True
9:
With txtData(I - 1)
10:
If I Mod NPC <> 0 Then
11:
txtData(I).Left = .Left + .Width + 200
12:
txtData(I).Top = .Top
13:
Else
14:
txtData(I).Left = txtData(0).Left
15:
txtData(I).Top = txtData(I - 1).Top + .Height +
200
16:
End If
17:
End With
18: Next I
End Sub
Private Sub cmdTransfer_Click()
20: Dim I As Integer
21: Dim N As Integer
22: N = txtData.UBound
23: NPC = txtCols.Text
24: For I = txtData.LBound To txtData.UBound
25:
FlexGrid1.TextMatrix(I \ NPC, I Mod NPC) = txtData(I)
26: Next I
End Sub

314

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Private Sub cmdClearText_Click()


29: Dim I As Integer
30: For I = txtData.LBound To txtData.UBound
31:
txtData.Item(I).Text = ""
32: Next I
End Sub
Private Sub cmdClearGrid_Click()
35:
FlexGrid1.Clear
End Sub
Private Sub cmdClose_Click()
38: Unload Me
End Sub
Private Sub UnloadTextBoxes()
41: Dim I As Integer
42: For I = txtData.LBound + 1 To txtData.UBound
43:
Unload txtData(I)
44: Next I
End Sub
In Listing 7.9, the line 1 to 18 is same as the code used in listing 7.6. The difference is
that TextBoxes are involved instead of CommandButtons(i.e txtData instead of
cmdNum). Observe that a statement was placed above line 1 in Listing 7.9. The purpose
of this statement is to enable the program unload all the controls array elements created
at runtime before attempting to create other elements other wise an error occur would.

Controls Array and Menus

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:

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Controls Array and Menus

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Controls Array and Menus

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Controls Array and Menus

Figure 7.14a

321

322

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

In order for us to appreciate the utility of array of PictureBoxes, we create an application


involving the Tabstrip control and an array of PictureBoxes. The following steps would
be required:
 Add the Tabstring control To the ToolBox if it is not already loaded.(You add the
TabStrip control from components dialog by selecting Microsoft Windows Common
Controls 6.0. You then click OK or Apply to close the component dialog)
 Draw an Instance of the TabStrip control on the form( Your Form should be as
shown in Figure 7.15
 Resize it so that it optimally covers the form(Figure 7.15b)

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

Controls Array and Menus















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.

Listing 7.12: Using the Tabstrip control


Private Sub tbsOption_Click()
Dim I as Integer
For I = 1 to tbsmain.Tabs.count
If I = tbsoptions.Selecteditem.Index 1 then

Else

End if
Next I
End Sub

324

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Controls Array and Menus

Figure 7.18
Making charts
from Array of
Lines

325

326

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Controls Array and Menus

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

a) Write a simple program that can be used to implement this


b) Given that one mark is subtracted from a student who fails three consecutive numbers.
modify program 7.6a to handle this.
c) Given that One mark is subtracted from a students score for every three questions
failed. Modify program 7.6a to handle this option
d) Integrate 7.6a, to c into a single program such that the examiner can pick an option to
work with.
Question 7.7
Repeat Question Q7.6a such that at least 10 students names and answers are collected in
an array of listboxes. Your program should evaluate each student and display results in a
grid or a control array under the following order.
S/No.
Surname
Firstname
Total Score
Position
Question 7.8
The interfaces shown in Figure Q7.8 a to c are used for Hydrocarbon gas analysis. Figure
Q7.8a has a CheckBox ListBox where one or more Alkanes can be selected. On Clicking
the Next button, a parallel array of textboxes and Labels are created sufficient to hold the
number of components selected.(see Figure Q7.8b). The gas gravity of each selected
component is entered in the textboxes. On Clicking Next again, the Comp. Name, Gas
gravity(y) , Mol wt(M), Critical Pressure(Pc) and Critical temperature (Tc) of each
component should be displayed in a grid or controls array in the third Form. Also include
columns that will enable you obtain the following
n

M a = yi M i , Ppc = yi Pci ; Tpc = yiTci


i =1

Figure Q7.8a
Hydrocarbon Gas Components
used in Question 7.1

Controls Array and Menus

329

Figure Q7.8b
Form displayinging components
selected from Figure Q7.8a

As a Form of Validation, use message boxes to ensure the following.


i) At least one component is selected from Figure Q7.8a
ii) Gas gravities in Figure 7.8b are numeric and must be between 0 and 1 inclusive
iii) Sum of Gas gravities in Figure 7.8 b gives 1
Note: the height of Figure Q7.8b should change dynamically relative to the number of
components selected. Step 3 of 3 was deliberately not shown.
See Literatures(or the accompanying CD ROM) for Critical Pressures, Critical
Temperatures and Molecular weight of Hydrocarbon gases.
Question 7.9
In a random sample of Q students from an Utopian University, the following statistics
were obtained. n students study Geology, m students study Mathematics, p Students
study Chemistry and r Students study Biology. Using array of Lines (with Shape control
as the case may be), represent the information in
a)
Bar Chart
b)
Histogram
c)
Pie Chart

CHAPTER

8
Visual Basic for Applications
Overview of ms excel
VBA Functions
VBA Collections
VBA dialog Boxes
Macros
VBA and OLE automation

Visual Basic for Applications

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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).

Visual Basic for Applications

333

Filling formulae in cells


The process of filling formulae in cells is like a user controlled for next loop with step of
one(1). For e.g., given the formula
Fn =

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 8.3
Excel MDI showing data
to be plotted.

Chart Wizard Icon


Figure 8.4
Excel Chart Wizard dialog
used to select Chart type
and chart sub type.

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.

Visual Basic for Applications

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.

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic for Applications

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.

Using Excels Functions


Microsoft Excel has more than 240 functions used for a variety of purpose. Figure 8.10
shows the MS Excels Paste function dialog invoked by selecting functions
from the Insert Menu. You use the Paste Function dialog to view the syntax of a function
as well as pasting the function in a worksheet.

338

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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
=
=
=
=
=

SUM(A1:A6) used with range


SUM(A1,A2,A3,A4,A5,A6) used with cells or scalars
SUM(A1:A5,A6)used with range and cell
SUM(3,4,9,6,8,17) used with enumerated scalars
SUM(Xdata) used with names where Xdata is the name of range A1:A6

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 .

Working with Array Functions


Excel also has functions that could be used to work with one-dimensional array as well as
two dimensional arrays. These functions are the Linest function, the slope function,
ZTEST functions etc. For example to get the slope of the data

339

Visual Basic for Applications

X
Y

3
10

4
12

5
14

6
16

7
18

Using the SLOPE function, you implement it as follows


=SLOPE({10,12,14,16,18},{3,4,5,6,7})
or with names as follows
=SLOPE(Yvalues, Xvalues)
where Xvalues is the name given to the X data points and Yvalues is the name given to
the Y data points using the Insert names dialog.
In like manner, the two dimensional array represented in matrix form as
2 0 1

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

2x1 + 0x2 + 4x3 + 3x4 = 28


4x1 + 2x2 + 2x3 + x4 = 20
-3x1 + x2 + 3x3 + 2x4 = 6
using spread sheet functions. To implement this, you first of all write the SLE in matrix
form as
AX = B
Such that
X = A-1B
1

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


Open MS Excel if it is not already opened

Select Macros from the Tools Menu

Select Macros from the Macros Sub Menu. The Macro dialog should appear as
shown in Figure 8.11.

341

Visual Basic for Applications

Figure 8.11
MS Excel Macro dialog
used to Create/Edit
functions, sub procedure
and macros.

Enter HCF as the Macro name and click create.

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)

Listing 8.1 : Writing Simple VBA functions


Public Function HCF( ByVal A
Integer)As Integer
1:
Dim intRem As Integer
2:
intRem = A mod B
3:
If intRem = 0 Then
4:
HCF = A mod B
5:
Else
6:
HCF = HCF(B, A mod B)
7:
End IF
End Function

as

Integer,

ByVal

As

Close the VBA Window and return to MS Excel.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 8.12
The Excel Paste Function
Dialog showing the newly
written HCF function

Close the function dialog and type


= HCF(60,45)

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.


Now put 60 in Cell A1 and 45 in Cell A2 and type


= HCF (A1,A2).

It should give you expected results.




Repeat the same procedure and test the LCM function(see Listing 5.). Note your
observation. It should be well behaved.

Worksheet and VBA Functions


Beginers often ask the question, why are the scores of functions available in Excel not
incorporated in VBA. The simple answer to this is VBA VB while Excel Spreadsheet
Application. By implication, there is no VBA function to evaluate matrix inverse or
determinant as well as other subtled mathematical/statistical operations. To use the Excel
application worksheet functions, you must pass through the application object to access
the function. For example, to find the median of the data 3, 7, 4, 9, 6, 8 using VBA, you
implement it as

Visual Basic for Applications

343

X = Application.Median (3,7,4,9,6,8)
NOTE

VBAs square root function is SQR while Excels square root function is SQRT.

Writing VBA Functions with Indefinite Arguments


The functions we have so far written are considered simple because they accept definite
number of arguments. The HCF and LCM functions can not be used to evaluate the HCF
of 15, 12 and 39. This is because the HCF function was written with two arguments only.
To make it work with three or more arguments, we implement the HCF function with
indefinite argument so that it can be used in any of the following forms.
= HCF (20,60,24,32,40,100)
= HCF(B2,C2,D2,E2,F2,G2)
Both forms give correct answers because our function was written with indefinite
arguments. Since cells B2, C2, D2, E2, F2 and G2 form the range (i.e. B2:G2), then what
happens if we write our HCF function as
=HCF(B2:G2)
This should invoke an error because our HCF function was written with simple variable
as arguments and not object (range object). How do we handle this? Handling this will
become obvious after considering VBA collections.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Visual Basic for Applications

345

Methods of the Range/Selection Object


Some methods and properties of the range/selection object are tabulated in Table 8.1
Table 8.1: Selected properties and methods of the range object
Method/Property
Function
Clear
Clears the range
Select
Selects the range
Sort
Sorts the range
Insert
Used to Insert an item into the range
Item
Reference to a specific item in the range
Value
Used to Read/Write a value to range
Count
Property of the Area/Columns/Rows properties
Columns
Used to get or set an atrtribute for columns of a range/selection
Rows
Used to get or set an atrtribute for Rows of a range/selection
Areas
Used to get or set an attribute for multiple selections
Having understood some properties and methods of the range object, we now consider a
program that accepts a range and returns the sum of all the Items in
the range.
Listing 8.2: Writing a Function that accept a range
Function SumRange(X AS Range) as Double
1:
SumRange = 0
2:
For Each item in Range
3:
SumRange = SumRange + Item.Value
4:
Next Item
End function
The SumRange function cannot work with scalars because it was implemented to work
with Range only. To prevent this, we use the type Name function to confirm if the
argument is actually a Range. This is done as shown in Listing 8.3.
Listing 8.3:Fail safe Function that accepts a range
Function SumRange (X As Range)
1:
If TypeName(x) <> Range Then
2:
Exit function
3:
Endif
4:
SumRange = 0
5:
For Each Item in Range
6:
SumRange = SumRange + Item.Value
7:
Next Item

346

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

The Selection Object


Selection object is somewhat related to the Range Object. It has properties and methods
similar to the range object. If the number of rows and columns in a selection are both
equal to 1 then selection is a cell, otherwise the selection is a range.
You can use the message box to determine the number of rows and columns in a selection
as follows
MsgBox Rows = & Selection.Rows.Count
MsgBox Columns = & Selection.Columns.Count
With the selection object and the ActiveCell object, you can write a function that returns
a range since a range is regarded as a selection with more than 1 row or column.

Reading and Writing from Selections


Any of the following methods can be used to write or read from a selection.


Offset Method

The range 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

Visual Basic for Applications

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

The Cells Property


The VBA cells property is similar to the Textmatrix/TextArray/Text property of the
MSflexgrid and MSH flexgrid. We consider the different forms of the cells property.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Visual Basic for Applications

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

VBA Dialog Boxes


Dialog Boxes can be created and designed with forms and controls using VBA. These
forms and controls have properties similar to those created with Visual Basic.
Figure 8.13 shows the VBA MDI(Multi-Document Interface) used to create dialog
driven VBA applications. You activate the interface by selecting Visual Basic from the
Macros sub Menu of Microsoft Excels Tool Top level menu.
Figure 8.13
VBA
integrated
development
Environment

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

Visual Basic for Applications

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic for Applications

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Listing 8.6: Evaluating Functions at runtime


Option Explicit
Private Sub cmdEvaluate_Click()
3: Dim S As String, X1 As Integer, I As Integer
4: Dim X2 As Integer, Xinc As Integer, y As Double
5: Dim K As Integer, A As String
6: S = txtFunction.Text
7: X1 = txtXStart.Text
8: X2 = txtXStop.Text
9: Xinc = txtXIncrement.Text
10: K = 0
11: For I = X1 To X2 Step Xinc
12:
A = Replace(S, "x", I, , , vbTextCompare)
13:
y = Application.Evaluate(A)
14: If chkDisplay.Value = 0 Then
15:
ActiveCell.Offset(K, 0) = y
16: Else
17:
ActiveCell.Offset(0, K) = y
18: End If
19: K = K + 1
20: Next I
End Sub

Visual Basic for Applications

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

The Record Macro dialog appears as shown in Figure 8.17

Figure 8.17
Excel Record Macro dialog used
to assign macros name,
shortcutkey and Scope.

Type the macros name(say TestMacro)

356

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Type the following in Cell E7 to E10 {5,9,4,7}

Stop the macro recorder.

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.

Visual Basic for Applications

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)

Listing 8.7: Code generated by the macro recorder


Sub TestMacro()
1: ' TestMacro Macro
2: ' Macro recorded 7/22/2003 by Engr. ThankGod Egbe
3: Range("E7").Select
4: ActiveCell.FormulaR1C1 = "5"
5: Range("E8").Select
6: ActiveCell.FormulaR1C1 = "9"
7: Range("E9").Select
8: ActiveCell.FormulaR1C1 = "4"
9: Range("E10").Select
10: ActiveCell.FormulaR1C1 = "7"
End Sub
Line 1 and 2 are comment generated by the Macro recorder. The main line of code is in
Lines 3 to 10. Line 3 activates Range("E7") i.e sets the focus rectangle on Cell E7. Line
4 types the string "9" on the ActiveCell which invariably is Cell E7. The rest of the lines
are mainly duplicates of Lines 3 and 4.
NOTE

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Using Recorded Macros


After recording macros, you can re-play the actions performed on the application by
triggering the macros command. The actions performed are reproduced and displayed on
the worksheet or chartsheet as the case may be. To demostrate the importance of macro
we should pause and record a graph plotting macro and then integrate it to a VBA
application.

Recording a Graph Macro


Place some data in two columns of the Excel spreadsheet and activate the macro
recorder. Select the data and follow the steps outlined earlier to plot the data and place
your graph in a new chart sheet. Stop the macro recorder. The code generated should be
similar to the code in Listing 8.8
Listing 8.8: XY Scatter Graph plotting Macro generated by MS Excel
Sub XYGraphMacro1()
1: Range("E3:F12").Select
2: Charts.Add
3: ActiveChart.ChartType = xlXYScatterSmooth
4: ActiveChart.SetSource DataSource := _
Sheets("Sheet1").Range("E3:F12"),PlotBy:=xlColumns
5: ActiveChart.Location Where:=xlLocationAsNewSheet
6: With ActiveChart
7: .HasTitle = True
8: .ChartTitle.Characters.Text = "Correlating Y and X"
9: .Axes(xlCategory, xlPrimary).HasTitle = True
10: .Axes(xlCategory,xlPrimary).AxisTitle.Characters.Text _
="x"
11: .Axes(xlValue, xlPrimary).HasTitle = True
12: .Axes(xlValue,xlPrimary).AxisTitle.Characters.Text ="y"
13: End With
End Sub
Understanding the code generated by Macro is often easy once we understand the actions
we performed. Listing 8.8 is like a programmatic summary of the graph plotting routine.
Line 1 instructs VBA to select the Range("E3:F12") . This is equivalent to selecting
Range("E3:F12") with the mouse by click and drag operations.
Line 2 instructs VBA to add a Chart. Manually it means clicking the chart wizard icon on
the Standard ToolBar

Visual Basic for Applications

359

Line 3 instructs VBA to select xlXYScatterSmooth. Other Options on the XYScatter


category are xlXYScatter, xlXYScatterSmoothNoMarkers, xlXYScatterLines and
xlXYScatterLinesNoMarkers. See Figure 8.4
Line 4 presents the code generated in step 2 of the four graph plotting steps. It Instructs
VBA to set the range of data to be plotted and the orientation (see Figure 8.5). Any
change you make in this step supercedes the instruction in Line 1 though the default is
always the range selected.
Line 5 instructs VBA to place the newly plotted chart in a new sheet( i.e chart sheet). The
other option is to place it on the same sheet as the data(xlLocationAsObject,
Name:="Sheet1"). This instruction is contained in step 4 of the four graph plotting
steps.(see Figure 8.7)
Lines 6 to 13 are the codes generated in step 3 of the four graph plotting steps(see Figure
8.6). The importance of this step is that it customizes the graph to be plotted. It is actually
regarded as an optional or secondary step. Line 6 opens the With block using the
ActiveChart as the object. Line 7 means the Activechart would have a title and Line 8
sets this title. If Line 7 was set to False meaning that the active chart would not have a
title then Line 8 is ignored and would be missing in the code generated by VBA. Lines 9
and 10 are similar to Lines 7 and 8 though they apply to the title of the primary x axis
instead of the chart title. Since Line 9 is set with True then a title is set for the x-axis in
Line 10. If Line 9 was set to false, then Line 10 would have been omitted by VBA. Lines
11 and 12 are the same as Lines 9 and 10 though they apply to the y-axis
NOTE

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Visual Basic for Applications

361

Listing 8.10 Re using Recorded macro with VBA dialog


Private Sub cmdPlot_Click()
1: Dim i As Integer, j As Integer
2: Dim DataRange As String
3: For j = 0 To 1
4:
For i = 0 To 7
5:
Worksheets(1).Cells(i + 1, j + 1).Value = _
MSFlexGrid1.TextMatrix(i, j)
6:
Next i
7: Next j
8: DataRange = "A1:B" & CStr(i)
9: Call xyGraphMacro(DataRange)
End Sub
Private Sub UserForm_Activate()
12: Me.MSFlexGrid1.TextMatrix(0, 0) = "x"
13: Me.MSFlexGrid1.TextMatrix(0, 1) = "y"
End Sub
Private Sub MSFlexGrid1_DblClick()
16: Dim S$, R%, C%
17: With MSFlexGrid1
18:
R% = .Row
19:
C% = .Col
20:
S$ = InputBox("Enter Plot Data")
21:
.TextMatrix(R%, C%) = S$
22: End With
End Sub
Private Sub cmdClose_Click()
23: Unload Me
End Sub
Sub XYGraphMacro(DataRange As String)
26: Range("E3:F12").Select
27: Charts.Add
28: ActiveChart.ChartType = xlXYScatterSmooth
29: ActiveChart.SetSourceDataSource:= _
Sheets("Sheet1").Range(DataRange),
PlotBy:=xlColumns
30:
ActiveChart.Location Where:=xlLocationAsNewSheet
31: With ActiveChart
32:
.HasTitle = True
33:
.ChartTitle.Characters.Text = "Correlating Y
and
X"
34:
.Axes(xlCategory, xlPrimary).HasTitle = True

362

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

VBA and OLE Automation


Having understood Visual Basic and VBA we now consider how we can use a
technology called OLE(Object Linking and Embeding) Automation to manipulate
Excel(or other applications) using VBA from within Visual Basic. An example is to send
data from a ListBox to a column in an MS Excel application. To do this you need to set
references to the Excel object and then create an instance of Excel object using code.
You use this object to communicate with Excel. You set the references to the Excel
object using the Visual Basic references dialog invoked by selecting References from
the Project menu.

Visual Basic for Applications

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Visual Basic for Applications

365

Listing 8.12. Creating Dialog Boxes


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

366
41:
42:
43:
44
End
Sub
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
End

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic for Applications

367

Visual Basic, VBA , OLE Automation and OLE Control


You enjoy the utility of OLE Automation and VBA when you can embed a plotted Excel
graph or other applications inside your Visual Basic application instead of having them in
separate applications. By adding the OLE container control to the Form, you can link or
embed other applications inside your application. Before trying to embed our plotted
graph in Visual Basic using OLE, we should pause and consider the OLE control.

Adding the OLE Control to the Form


Draw an instance of the OLE control on the form and wait for a while. The Insert object
dialog appears for you to select.

Figure 8.22
Visual Basic Form showing
OLE control.

Figure 8.23
Visual Basic OLE
Insert Object.

368

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic for Applications

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

"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
objExcel.ActiveWorkbook.SaveAs FileName:= _
"C:\EgbeGladys.xls"
OLE1.CreateEmbed ("C:\EgbeGladys.xls")
OLE1.SizeMode = 1
Sub

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

Using VBA programming techniques, write a spreadsheet HCF function capable of


accepting a range, indefinite arguments, scalars, cell values and any combination of
these.
Question 8.2
The LCM of two numbers is defined as

LCM ( A, B) =

A B
HCF ( A, B)

Using VBA programming techniques, write a spreadsheet HCF function capable of


accepting a range, indefinite arguments, scalars, cell values and any combination of
these.
Question 8.3
Given a simultaneous Equation in the form

371

Visual Basic for Applications

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

An author once defined numerical method as a computer approach towards manipulating


conventional and matrix related functions. If this definition is to be taken seriously, then
we have already conquered numerical analysis in disguise. This chapter considers how
the familiar Visual Basic objects can be used to effectively and efficiently analyse
mathematical problems numerically.

Evaluation of Functions at Runtime


Since most numerical problems consist of functions with one or more variables, it would
be difficult to create a complete visual solution without being able to evaluate functions
at runtime. Lots of techniques exist that are used to evaluate functions at runtime. Some
of these are

String Techniques

Excel Application object

FunctionBox Control

Script control
Details on these methods are discussed in the sections that follow

Evaluating Functions at Runtime using Strings


When Intelligently applied, strings can be used to evaluate functions at runtime. This was
demonstrated in Chapter 5 with a simple linear function. Code used to evaluate. An
advantage of using string is that it can be customized to accept strings(functions) in any
syntax and evaluates very fast.

Excel Application object


The evaluate method of Microsoft Excel object simplifies function evaluation at runtime.
This method is often the most preferred because the Excel object exposes all the function
available in MS Excel through Automation. We saw in chapter 8 how application object
was used to access some mathematical functions. The syntax of the Evaluate method is
= ExcelObject.Evaluate

string

The return value is assigned to a variable as


Y=Excelobject.Evaluate string
To evaluate the function f(x) = Cos(x) Exp(x) + x

Numerical Applications

375

You pass the function as a string to the evaluate method as follows


Y = ExcelObject.Evaluate (Cos(x) LOG(x)+x)
To evaluate the function at specified value of x say x = 30, you replace all the x with 30
as follows
Y = ExcelObject.Evaluate (Cos(30) Log(30)+30)
Or in the more convenient form as
Str = (Cos(30)-Exp(30)+30)
Y=Application .Evaluate str
Manual replacement is often not convenient and hence a more convenient technique is to
use the string replace function to replace x(the variable) with 30(its value) as follows
str = (Cos(x)-Log(x)+x)
str = Replace(str,x,30)
Y=Application.Evaluate str
The replace function was used to replace all the x with the value 30 . You can use
the TextBox Control to enter a value for x as follows
x = txtxvalue.Text
strA = Cos(x) Exp(x) + x
strA = Replace(fx, "x", x)
y = objExcel.Evaluate(" cos(30) +sin(30) + 5")
To evaluate a function at runtime you have to accept both the function and the values of
the independent variables at run time using text boxes. Figure 9.1 is a program interface
used to accept and evaluate a function at runtime. The Code used to drive the interface is
as shown in Listing 9.1

376

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Figure 9.1
Accepting and Evaluating
Function at
Runtime

Listing 9.1:Evaluating function at runtime using Excel object


Private Sub cmdExecute_Click()
1:
'References... Ms-Excel Object
2:
Dim objExcel As Excel.Application
3:
Dim x As Double
4:
Dim fx As String, y As Double
5:
Set objExcel = New Excel.Application
6:
objExcel.Workbooks.Add
7:
objExcel.SheetsInNewWorkbook = 1
8:
x = txtxvalue.Text
9:
fx = txtfunction.Text
10:
fx = Replace(fx, "x", x)
11:
y = objExcel.Evaluate(fx)
12:
lblOutput.Caption = y
13:
Set objExcel = Nothing
End Sub
Line 1 of Listing 9.1 reminds us to set references to the Excel object. This should be
done otherwise the rest of the code wouldnt work. The rest of the code should be
familiar from our discussion in the previous chapters.
Test the application with different functions and observe that it gives correct answers.
You can use any of the intrinsic function in the appendix with more than one argument.
However, you need two text boxes to accept the two arguments. For a function with array
as argument, you can use the List, String, Control array or Grid as users input panel.

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.

Using Script Control


The Scripting Control could be used to overcome the limitation inherent in the use of
Excel object to evaluate function at runtime. This control is added to the toolbox using
the Components dialog. In syntax , the script control is very much similar to the
Evaluate method of MS Excel application object. The script control evaluation
technique compares well with the MS Excel technique. The syntax of the script control
is
ScriptControl.Eval

string

To evaluate the function


write the code as

Cos(x) LOG(x) + x

using the script control, you

Y = ScriptControl.Eval ( Cos(x) LOG(x) + x)


This is fairly similar to the Excel Evaluate method. With the example above, you can
now repeat Listing 9.1 using the script control. Before doing this you have to add the
script control to the toolbox. Figure 9.2 shows the component dialog with the
ScriptControl selected.

378

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Using Function Box


The FunctionBox control a third party ActiveX control used to evaluate functions at
runtime. It recognizes over 300 intrinsic function and has familiar syntax and is less
prone to error. The FunctionBox has among other properties, a property called the
SyntaxOption property. This property enables you to specify the nature of your syntax
which may be any of the following; fbFortran, fbBasic, fbCpp, fbCobol, fbDbase and
fbUser. You can obtain a copy of functionbox by contacting the Arthur.

Non Linear Equations.


Equations of the Form
 Exp(x) 3 = 0
 Cos(x) 5 = 0
 Log(x) 4= 0
 x2 9x 35 = 0
are considered as non linear equations. Generally, all Trancedental, Logarithmic,
Exponential and Polynomial functions of order greater than 1 are non linear by definition.
Some of the techniques used to find approximate roots to non linear problems include
 Newton Raphson method
 Secant method

380



Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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!

ignoring higher derivatives, equation 9.1 becomes


f(x+h) f(x) + hf(x)
hence the First derivative is given as

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

for backward difference. Equivalently, the central difference is given as

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

Listing 9. 5: Implementation of the numerical differentiation with function


Private Sub cmdexecute_Click()
1:
Dim x As Double
2:
x = txtxvalue.Text
3:
If optCentral.Value = True Then
4:
lblOutput.Caption = fp_c(x)
5:
Else If optBackward.Value =True Then
6:
lblOutput.Caption = fp_b(x)
7:
Else If optBackward.Value =True Then
8:
lblOutput.Caption = fp_f(x)
9:
End If
End Sub
Function f(x) As Double
12:
With ScriptControl1
13:
.ExecuteStatement "X = " & x
14:
f = .Eval(txtfunction.Text)
15:
End with
End Function
Function fp_c(x) As Double
16:
Dim h As Double
17:
h = 0.001 'Using central difference of order h*h
18:
fp_c = (f(x + h) - f(x - h)) / (2 * h)

385

386

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Numerical Differentiation with Discrete points


The method used to evaluate numerical differentiation based on discrete data points is
similar to the method used to determine it with function. Given the data shown in
table 9.1
Table 9.1: Discrete Data points can also be differentiated numerically

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Listing 9. 6: Implementation of numerical differentiation using discrete function.


Option Explicit
Private Sub cmdExecuate_Click()
1: Dim i As Integer, xp As Double,fx As Double
2: Dim n As Integer, h As Double,fPrime As Double
3: Dim fx_ph As Double, fx_mh As Double
4: n = txtN.Text
5: xp = Me.txtx.Text
6: For i = 0 To n - 1
7:
If Val(Form2.txtx(i).Text) = xp Then Exit For
8: Next i
9: h = Abs(Form2.txtx(0).Text Form2.txtx(1).Text)
10: fx = Form2.txtY(i).Text
'f(x)
11: fx_mh = Form2.txtY(i - 1).Text 'fx_mh = f(x-h)
12: fx_ph = Form2.txtY(i + 1).Text 'fx_ph = f(x+h)
13: If optCentral.Value = True Then
14:
fprime = (fx_ph - fx_mh) / (2 * h)
15: ElseIf optBackward.Value = True Then
16: fprime = (fx - fx_mh) / h
17: ElseIf optForward.Value = True Then
18: fprime = (fx_ph - fx) / h
19: End If
20: With lblResult
21:
.Caption = "f'" & CStr(xp) & ") = "
22:
.Caption = .Caption & CStr(fprime)
23: End With
End Sub
Private Sub cmdLoad_Click()
26: Dim i As Integer
27: Dim n As Integer
28: n = txtN.Text
29:
With Form2
30:
For i = 1 To n - 1
31:
'load textboxes
32:
Load .txtx(i)
33:
Load .txtY(i)
34:
Load .lblSn(i)
35:'Make them visible
36:
.txtx(i).Visible = True
37:
.txtY(i).Visible = True
38:
.lblSn(i).Visible = True
39:'Set their top

Numerical Applications

389

40: .txtx(i).Top = .txtx(i - 1).Top + _


.txtx(i - 1).Height + 200
41: .txtY(i).Top = .txtx(i).Top
42: lblSn(i).Top = .txtx(i).Top
43: 'set caption of label
44: lblSn(i).Caption = i + 1
45:Next i
46:.Show vbModal
47:End With
End Sub
Private Sub cmdClose_Click()
50: End
End Sub
This code exist in form 2
Private sub cmdClose_Click
54: Me.Hide
End Sub
Study Listing 9.6 carefully and observe how straight forward it is. The variables n and xp
are used to obtain the number of data points and the point of evaluation from the
user(Line 4 and 5). Lines 6 to 8 are used to find the location of xp in the data of
Form2(this is a linear search technique). This location is equal to i after the For Next
of lines 6 to 8 terminates.(Linear search principle). Line 9 obtains the step value by
subtracting adjacent x values in Form 2. The value of the dependent variable( y or f(x)) at
the point of evaluation is obtained from line 10 using result of the linear search technique
of lines 8 to 10. The parameters f( x - h) and f(x + h) were obtained in lines 11
and 12 as fx_mh and fx_ph. Lines 11 to 19 inspects the option buttons of
Form1(Figure 9.5a) and evaluates the appropriate difference using any of equations 9. 2
to 9.4. Lines 20 to 23 were used to display results in the label. Lines 26 to 45 were used
to create the controls array shown in figure 9.5 b.(see chapter 7). Line 46 shows Form 2
modally.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

f (a) + 2 f ( xi ) + f (b) .............................................................................. 9.5


2
i =1

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

Where n = number of trapeziums


h = step size
a = lower limit of integration
b = upper limit of integration

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Listing 9.8: Visual Basic implementation of the Simpson 1/3 rule


Private Sub cmdExecute_Click()
1:
Dim Str As string,UB as Integer,LB as Integer
2:
Dim h As double,n as Integer
3:
Str= txtFunction.Text
4:
LB= txtLB.Text
5:
Ub=txtUB.Text
6:
If optStripSize.Value = True Then
7:
H=txtstripWidth.Text
8:
lblOutput.Caption = Fsimpson13(str,LB,UB,H)
9:
ElseIf optStripWidth.Value = True Then
10:
N =txtStripNumber.Text = True Then
11:
lblOutput.Caption = Fsimpson13(str,LB,UB,,N)
12: End If
End Sub
Private Sub cmdClose_Click()
15: End
End Sub
Private Sub cmdOptions_Click()
18: Form2.show vbModal
End Sub
Line 8 is calls the Fsimpson13 function by passing the required arguments and the Strip
width to the function when the strip width is specified. However, when the strip width is
not specified, Line 11 calls the Fsimpson13 function with the strip width missing and the
stripnumber specified. The option command button in Figure 9.9 was added so that users
can view the detailed solution using a grid. This is left as an exercise for the student.

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

Given the integral


1 3

I xy =

(x

0 2

2 x + xy )dxdy

One can break the integral into the form


3

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe


n 1

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

x dxdy 2 xdxdy + xydxdy

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

19: SplitPoly = TermArray


End Function
Listing 9.10 used the familiar string function to split a polynomial of the form
a1xn1ym1 + a2xn2ym3 + a3xn3ym3 +
into the different terms such that a1xn1ym1 , a2xn2ym3, a3xn3ym3 etc are stored as different
array elements.
The form used for the implementation of the double integral is as shown in figure 9.10

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)

Lagrange interpolation and

(b)

Divided difference interpolation.

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

Where p is the point of interpolation


Given the data points shown in Table 9.2
Table 9.2: Example problem
K
Xk
yk
0
2
5
1
3
10
2
5
26
3
6
37
To estimate the value of y at x=P= 2.3 you evaluate
3 2.3 x
j
LK (x ) =
x x
j =0
K
j
j k

and there after evaluate


3

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Dim I As Integer, P As Double, K As Integer


Dim J As Integer, L() As Double, Sum As Double
If lstXdata.ListCount < > lstYdata.ListCount Then
MsgBox "X and Y data list must contain equal " & _
number of data"
16:
Exit Sub
17: End If
18: N = lstXdata.ListCount - 1
19:
ReDim X(N) As Double
20:
ReDim Y(N) As Double
21:
ReDim L(N) As Double
22:
For I = 0 To N
23:
X(I) = lstXdata.List(I)
24:
Y(I) = lstYdata.List(I)
25:
Next I
26:
P = txtInterpolationPoint.Text
27:
For K = 0 To N
28:
L(K) = 1
29:
For J = 0 To N
30:
If J <> K Then
31:
L(K) = L(K) * (P - X(J)) / (X(K) - X(J))
32:
End If
33:
Next J
34:
Next K
35:
Sum = 0
36:
For K = 0 To N
37:
Sum = Sum + L(K) * Y(K)
38:
Next K
39:
lblResult.Caption = Sum
End Sub
Private Sub cmdRemoveX_Click()
42: If lstXdata.ListIndex > -1 Then
43:
lstXdata.RemoveItem lstXdata.ListIndex
44: End If
End Sub
Private Sub cmdRemoveY_Click()
47: With lstYdata
48: If .ListIndex > -1 Then
49:
.RemoveItem .ListIndex
50: End If
51: End With
End Sub

402

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Divided Difference Interpolation


The divided differences for a function y=f(xK) are defined as follows

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

Hence, the recursive rule for constructing divided difference is

F xx j , xk j +1 ,..., xk =

] [

F xk j + +1 ,..., xk F xk j ,..., xk 1
xk xk j

] ........................... 9.11

and is used to construct the divided differences in table 9.3


Table 9.3 Divided difference table for y=f(x)
Xk F[xk]
F[,]
F[,,]
X0 F[x0]
X1 F[x1]
F[x0,x1]
X2 F[x2]
F[x1,x2]
F[x0,x1,x2]
X3 F[x3]
F[x2,x3]
F[x1,x2,x3]
X4 F[x4]
F[x3,x4]
F[x2,x3,x4]

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]

(for j= 1 to k) ................................................ 9.12

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

D(k,0) = f(xk) = yk k= 0 to n............................................................................ 9.13b


The Newton polynomial of degree N that passes through the N+1 points (xk,yk) for
K=0,1,,N is given as
f(x) = D0,0 + D1,1(x x0) + D2,2(x x0)(x-x1) + DN,N(x-x0)(x-x1)(x xN-1) .......... 9.14a
Where array D is as defined in equation 9.13 and b
In compact form , equation 9.14a is written as
N k 1

f ( x) = D0, 0 + x x j Dk , k ..................................................................... 9.14b


k =1 j = 0

A Visual Basic implementation of the divided difference problem is shown in


Figure 9.12 a and b and Listing 9.12

404

Figure 9.12 a
Visual interface for
the divided difference
interpolation problem.

(b) Interface showing the


divided difference generated
from Figure 9.12a.

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Numerical Applications

405

Listing 9.12:Visual basic implementation of the divided difference problem.(Figure 9.12)


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()
9:
Dim N As Integer, X() As Double, Y() As Double
10: Dim I As Integer, P As Double, K As Integer
11: Dim Prod As Double
12: Dim J As Integer, D() As Variant, Sum As Double
13: If lstXdata.ListCount <> lstYdata.ListCount Then
14:
MsgBox "X and Y data list must contain equal" & _
"number of data"
15:
Exit Sub
16: End If
17: N = lstXdata.ListCount - 1
18:
ReDim X(N) As Double
19:
ReDim Y(N) As Double
20:
ReDim D(N, N) As Variant
21:
For I = 0 To N
22:
X(I) = lstXdata.List(I)
23:
Y(I) = lstYdata.List(I)
24:
Next I
25:
P = txtInterpolationPoint.Text
26:
For K = 0 To N
27:
D(K, 0) = Y(K)
28:
Next K
29:
For J = 1 To N
30:
For K = J To N
31:
D(K, J) = (D(K, J - 1) - D(K - 1, J - 1)) / _
(X(K) - X(K - J))
32:
Next K

406

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Private Sub cmdRemoveX_Click()


52: If lstXdata.ListIndex > -1 Then
53:
lstXdata.RemoveItem lstXdata.ListIndex
54: End If
End Sub
Private Sub cmdRemoveY_Click()
57: With lstYdata
58: If .ListIndex > -1 Then
59:
.RemoveItem .ListIndex
60: End If
61: End With
End Sub
Private Sub CmdViewDifference_Click()
64: frmDivide.Show vbModal
End 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.

Introduction to Matrix Algebra


A rectangular array of information is called a matrix. Common matrix operations are
matrix addition, multiplication, inverse and determinant. Fortunately, Microsoft Excel
has functions which can be used to carry out all these matrix operations. However, more
sophisticated matrix operation involving iterative improvements still need custom
program.

Using Excel Functions to Evaluate Matrices


The Excel Evaluate method discussed at the beginning of this chapter could also be used
to evaluate matrices. However, the matrices must be configured to match the syntax of
excel array function. For instance, given the matrix

3 5 8

A = 9 3 2
2 4 7

To write it in Excel like form you express it in linear form as follows


A={3,5,8;9,3,2;2,4,7}
With the matrix in linear form we can evaluate the determinant using excel evaluate
method as follows
Dim str As String
Str = MDETERM({3,5,8;9,3,2;2,4,7})
Determinant = objExcel.Evaluate(str)
Other matrix related functions can also be evaluated using the same principle.
For functions which return matrices, we need to assign result to a variant variable or a
dynamic array without dimension. For example to evaluate matrix inverse we implement
it as follows.

408

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Dim Result As Double


Dim Str As String
str = MINVERSE({3,5,8;9,3,2;2,4,7})
Result = objExcel.Evaluate(str)
To access the data in the array, you use the normal matrix (or 2 dimensional array)
technique of using a pair of subscripts. However, you have to note that the result array
has a lower bound of 1 instead 0. Since we are sure that the array is a two dimensional
array but not sure of the lower and upper bound it will be better to work with the matrix
in terms of the lower and upper bound as follows:
For I = Lbound(Result,1) To Ubound(Result,1)
For J = Lbound(Result,2) To Ubound(Result,2)
Flexgrid1.TextMatrix(I+1,J+1) = Result(I,J)
Next J
Next I

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

CHAPTER

10
Database Access
Data Control
The Recordset Object
The Visual Data Manager
Structured Query Language
Visual Basic Data Applications

414

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

The DatabaseName property enables the data control to establish a connection to a


particular database file in the system.This property is set in much the same way like the
picture property(i.e clicking the ellipsis that appear after selecting the property). The
recordset property on the other hand enables the data control to specify the name of the
table(or stored query) in the database in which the data control can access.This is
important because some data base might have more than one table(or query or both).
Once these properties are set, the DataControl has sufficiently finished its connection to
the database. You can now bound the database to the bound controls. In the same way,
before you can bind a bound control to a particular field, you need to set two properties.
These are the

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.

Creating a Simple Database Application


In order to make you appreciate the terms we have been discussing, we need to create a
simple application using the Data control and some bound controls. Luckily Visual Basic
ships with two data base files, these are the Biblio and the NWind database. This saves us
all the headache of creating our own database file. The Biblio database has five tables
with each table having its own set of fields and records. The NWind Database is however
a larger database with twenty seven tables and a total of more than hundred fields. Each
of this field has a large number of records.
For our application we will use the Biblio data base file which is a relatively small
database file consisting of the names of computer books and their authors. Figure 10.3
shows the form(at runtime) used for this design. To create the application and the Form
we take the following steps.


Create a new Standard Exe application.

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




Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Displaying Multiple Records In Bound Controls


The data-aware intrinsic PictureBox, Label, TextBox, CheckBox, Image, OLE, ListBox
and ComboBox controls can only be bound to a single field of a Recordset managed by
the Data control. To display or manipulate several records at a time we use ActiveX
controls from the component dialog. The controls capable of managing sets of records
when bound to a Data control include but not limited to the following:


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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Set the DataSource property of the MSHFlexGrid to Data1

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

The Recordset Object


A set of records in the database is called a Recordset. A RecordSet can have 0,1,2 or
more records. Though the RecordSet is a property of the data control, it is also considered
as an object with properties and methods. Some of the methods of the RecordSet object
are already familiar. These are the Move method and the other four navigational methods.
Apart from the navigational methods, the RecordSet object has 19 other methods. Some
of these methods are considered below.

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

These methods have the same syntax


Data1.Recordset.Findx

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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]

Like 'C++*' "

the record displayed would be as shown in Figure 10.8.

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]

Like '*C++' "

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

[Year Published]> #10/01/1990#

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

The Visual Data Manager


The Visual Data Manager is a tool used to design databases in Visual Basic. Other tools
commonly used to create databases are Microsoft Access and Microsoft SQL Server.
Creating database with Microsoft Access and SQL Server will be discussed in Volume 2
of this text. Before delving into designing databases with Visual Data Manager, we first
of all ponder on the problem stated below.
A Petroleum development company(PDC) based in Port Harcourt is currently producing
water along side oil. This mixture often coalesce together and hence posses serious
oilfield problem to the company and loss of value of the crude produced. In order to
break this oil/water mixture, the company decided to employ the services of some
chemical manufacturing firms(CMF). Each accredited CMF manufactures chemicals that
are capable of breaking different types of water/oil mixtures and updates the PDC
database with the properties of the chemicals manufactured on regular basis. These
information are stored in the PDCs database and are accessed periodically by the
PDC. The best three chemicals that optimally break a given sample of oil/water mixture
are selected. The manufacturers of such Chemicals are contacted and asked to make
supplies accordingly. The PDC calls the oil/water mixture Emulsion and the chemical
used to break the oil/water mixture the demulsifier. The information needed by the PDC
include the Supplier ID , the Demulsifier Tag, Demulsifier PH, demulsifier
Hydrophile/Lipohile Balance(HLB), the Demulsifier Dilectric constant(X), the Cost of the
Demulsifier and the date manufactured. The PDC recently employed a developer to
develop a web based database application that would keep tract of this transaction.
From the statement of problem, we immediately know that the developer would not use
one table for this design. This is because the companys profile would be supplied during
accreditation and would be stored first before the company is allowed to enter the

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

that the tables are related by the manufacturer ID Fields. Figure 10.9 shows a schema

indicating the relationship between both tables.


Figure 10.9
Defining relationship
between tables.

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.


Start a New standard Exe application

Click the save project icon on the standard toolbar. This opens the Save As dialog as
shown in Figure 10.10

Click the create folder icon

Rename the folder as Chemicals Data project

Click Open

Database Access

427

Figure 10.10
Creating a folder for a
database application
from The Save file As
dialog.

Create Folder Icon





Save the Form as frmMain and Click Open.


Save the Project as Chemical Data.

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.

Click Save to close the dialog.

428

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

On the Field Type ComboBox, select Text.

On the Validation rule TextBox type Like [a-zA-Z]*

430

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

On the Validation Text TextBox, type Manufacturer name must begin with an
alphabetic character.

Click OK to add this Field to the Table Structure Field List

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)

Type the name ManufacturerNameIndex in the Name TextBox.

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Click the Add Index button to show the Add Index to dialog.

Type DemulsifierTagIndex in the name TextBox

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.

Type the second index name as ManufacturerIDIndex

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.

Adding Records to Tables Using Visdata


Open the Chemical Data project if it is not already open and make sure the window looks
like the window shown in Figure 10.22. To Add Accredited Chemical manufacturing
Firms, follow the steps outlined below.


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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Click Close to return to the Default windows of VisData.

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).

Manipulating Records in Visual Basic with Visdata Data


Form Designer
The method that would be used to view the demulsifier properties in a Standard Exe
application is same as the method used to view the BIBLIO computer books discussed in
the early part of this chapter. We can use TextBoxes to view one record at a time and
navigate to other records using the data control navigation buttons or view multiple
records using grids or DataBound Combo/List. If we choose to use TextBoxes, VisData
provides a simple technique used to create the basic user interface and code used to drive
the interface. We enjoy this utility after going through the steps outlined below


Open the VisData and the Chemical application

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.

In the RecordSource ComboBox, we select the table of interest.(This ComboBox


contains a List of all the Tables/Querydef in the database file). For our purpose select
tblManufacturer. On selecting this option, the Data Form Designers available fields
List is filled with all the fields in the table as shown in Figure 10.27

438

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Click Close to close Data Form Designer

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

Run the program by pressing F5(Make sure it is the start up object)

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

Click the navigation buttons to navigate between records

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

Listing 10.2: Code generated by Visdata Data Form designer


Private Sub cmdAdd_Click()
1: Data1.Recordset.AddNew
End Sub
Private Sub cmdDelete_Click()
4: 'this may produce an error if you delete the last
5: 'record or the only record in the recordset
6: Data1.Recordset.Delete
7: Data1.Recordset.MoveNext
End Sub
Private Sub cmdRefresh_Click()
10: 'this is really only needed for multi user apps
11: Data1.Refresh
End Sub
Private Sub cmdUpdate_Click()
14: Data1.UpdateRecord
15: Data1.Recordset.Bookmark =Data1.Recordset.LastModified
End Sub
Private Sub cmdClose_Click()
16: Unload Me
End Sub
The code generated by the VisData Data Form designer is as shown in Listing 10.2 and is
actually self explanatory

440

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Structured Query Language


Simply put, queries are database commands used to retrieve and manipulate records in
databases. In Visual Basic as well as other relational database systems, queries are
written with the Structured Query language (SQL). SQL is a fourth generation language
used for manipulating data in database tables and to create as well as change the
structure of database tables. Queries written with SQL can be grouped into two
categories. These are


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

Data Manipulation Language Queries


The simplest queries that can be written with SQL are those which are used to retrieve
records from specified fields in a specified table. For example in the database created in
the last section, you can write a simple query to retrieve the demulsifier Tag, the pH,
and Dielectric constant of all the demulsifier in tblDemulsifier as follows
SELECT [Demulsifier Tag], [pH] FROM tblDemulsifier
The command above is the simplest form of an SQL query. It retrieves two fields from a
specified database table. In the command above, you observe that the fields names were
enclosed in square brackets and immediately follows the SELECT clause. Also, the table
name immediately follows the FROM clause.

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

SELECT * FROM tblDemulsifier


The wildcat operator (*) means all the fields in tblDemulsifier.
The SQL select statement is very powerful and infact very simple to apply though it
could be more than a little complex when its full syntax is adopted. For the purpose of
this book, we restrict ourselves to the basic structure which has the following syntax.
SELECT <field_list> FROM <recordset_list> <join_type> JOIN <join_condition>
WHERE
<selection_criteria> GROUP BY <group_by_field_list>
HAVING
<selection_criteria> ORDER BY <order_by_field_list> [ASC/DESC]
In the syntax, the fields list is a list of one or more fields in the recordset list. These field
list can also comprise of one or more fields not in the table(recordset). As demonstrated
earlier, the SELECT clause and the FROM clause are the two clauses that must be
included in the SQL SELECT statement. Others are optional.

Using the Select and From clauses to designate a


Recordsource in code
We earlier demonstrated how to display records in grids. We will use this technique to
test all the queries in this section. Lets create a simple one form application to display
records in grids. The following steps are required:


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.

Set the DataSource property of the MSFlexGrid control to Data1

Unlike in the previous section, we are going to set the RecordSource using an SQL
SELECT statement as shown in Listing 10.3

Listing 10.3: Designating a RecordSource in code


Private Sub Form_Load()
1: Data1.RecordSource = Select * FROM tblDemulsifier
2: Data1.Refresh
End Sub
In Listing 10.3 the SQL statement was used to retrieve all the records in tblDemulsifier.
It was assigned as a string to the RecordSource property. A more popular method is to

442

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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.

Using the SQL Where Clause


The SQL where clause is used to limit the amount of data retrieved by the SQL
statement. For example, to display all the records with pH greater than 7.0 invoke the
command
SELECT * FROM tblDemulsifier WHERE pH > 7.0
You can test this by replacing the SQL SELECT statement in Line 1 with the command
above. This should display only the records with pH greater than 7

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

* FROM tblDemulsifier WHERE pH IN (7,7.9,8.5,9.2)

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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)

Specifying Multiple Criteria With the Where Clause


In the conventional decision structures, the Logical operators (OR and AND) are used to
perform a logical conjunction/disjunction on two relational expressions. Likewise, in
SQL the Logical operators are used to perform logical conjunction/disjunction on two

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.

Visual Basic Data Applications


Instead of using the constants as test values in the SQL WHERE clause, we can use
variables so that our SQL statement can be incorporated in the conventional Visual Basic
programs. An example on how this is done is as shown in Listing 10.5
Listing 10.5: Using the SQL WHERE clause with Test Values in a TextBox
Private Sub Form_Load()
1: Dim xpH As Double
2: xpH = Text1.Text
3: Data1.RecordSource =SELECT * FROM tblDemulsifier _ &
WHERE HLB < = & cstr(xpH)
End Sub
In the code above, Line 1 declares a double variable while line 2 assigns the text in Text1
to the variable. Line 3 uses the SQL select statement with the WHERE clause to restrict
records to only those that are less than or equal to the text in Text1. Notice how the
concatenation operator was used to concatenate the variable to the SQL select staement.
This is usually the syntax adopted when using text fields to restrict records retrieved from
a Recordset. Also notice how the line was continued over the next.
The code in Listing 10.5 appears quite simple. This is because the field being compared is
a numeric field. The syntax takes a rather funny form when working with dates or text(or
string) fields. Two SQL statements are written to illustrate how the date and string fields
are used with text values in a TextBox. For date it is written as
SELECT * FROM tblDemulsifier WHERE
> # & Text1.Text & #

[Date Manufactured]

and with string, it is written as


SELECT * FROM tblDemulsifier WHERE [Manufacturer ID] = &
Text1.Text &

446

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

mean that the variable could have been declared as string. Doing otherwise could at times
invoke a runtime error due to incorrect SQL syntax.

Using the SQL Order By Clause


The ORDER BY clause is the simplest of all the SQL clauses. This is used to Sort the
resultset in ascending(ASC) or descending(DESC) order. This clause can be used
without the WHERE clause as
SELECT * FROM tblDemulsifier ORDER BY [pH] DESC
Or with the WHERE clause as
SELECT * FROM tblDemulsifiers WHERE
[Dielectric Constant] DESC

[HLB] > 4 ORDER BY

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.

Using the SQL As Clause


The SQL AS clause is commonly used to alias a field name for cases where the field
names are too long or not well understood. For example you can choose to display the
field name [Manufacturer ID] as [MCode] and the [Demulsifier Tag] as [DTag] as
follows
"Select [Manufacturer ID] As [MCode],[DemulsifierTag] As
[DTag],[Ph],[HLB],[Dielectric
Constant]
As
[Kd]
From
tblDemulsifier Where [HLB] > 12.5 ORDER BY [pH]

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

you can obtain this using SQL as follows


"Select [Manufacturer ID] As [MCode],[DemulsifierTag] As
[DTag],[Ph],[HLB],[Dielectric
Constant]
As
[Kd],(3
*
[Dielectric Constant]/HLB) As Eo From tblDemulsifier Where
[HLB] > 12.5 ORDER BY [pH]

Using the SQL Aggregate Functions


The SQL aggregate functions are used to obtain various mathematical/statistical
parameters from a database Field is shown in Table 10.6
Table 10.6: SQL aggregate functions
S/No Aggregate Function
Remark
1
MAX
Maximum Value
2
MIN
Minimum Value
3
AVE
Average
4
STD
Standard Deviation
5
COUNT
Gets the count of data.
6
SUM
Calculates the sum
7
VAR
Calculates the variance of a population sample
8
VARP
Calculates the variance of a population
9
STDEV
Calculates the Standard Deviation of a population Sample
10
STDEVP
Calculates the Standard Deviation of a population
For example to get the number of demulsifiers in the database table with pH greater
than 7 you use the SQL aggregate function with the SQL HAVING clause as follows
SELECT COUNT(pH) As [number of Chemicals] From
tblDemulsifier HAVING [pH] > 7

450

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Where E = Efficiency Ratio


Xd =Dielectric Constant of Demulsifier
P = 1.77641 + 0.64025A
A is a constant = HLB of the emulsion
Question 10.3
Design a Two table student academic database with the following fields and tables
Table 1
Table 2
Mat No
Mat No
Assesment Score
Surname
Exams Score
First name
Credit Unit
State of Origin
Course No
Department
Semester
Address
Session
Populate the database table with up to 80 records such that up to ten courses are
considered and up to 15 students are considered. Design a user interface that would
enable one get results from the following queries.
a) Display
Mat No Course No Total Score
Grade
b) Display
Surname, Firstname, Dept.
Grade
c) Mat No.
No of As
No of Bs
No of Cs

d)Surname, Firstname GPA

Database Access

451

e)Surname, Firstname and Mat No of all the students with at least 1 F


f)Display the Department with the highest number of As
g)Number of students with Total Score greater than the Average Score for a particular
Course.
Question 10.4
Using the database created in Figure Q10.3, write queries that display the
Surname,Firstname,Mat No of all the students offereing some specified courses. The
Courses should be specified by selecting them from a checkbox ListBox as showm in
Figure Q10.4
Figure Q10.4
Checkbox used to
select courses to be
displayed by the queries

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

|
}
~

These characters aren't supported by Microsoft Windows.


* *Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return
characters, respectively. They have no graphical representation but, depending on the
application, can affect the visual display of text.

Character Set (128 255)

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

These characters aren't supported by Microsoft Windows.


The values in the table are the Windows default. However, values in the ANSI character
set above 127 are determined by the code page specific to your operating system.

Database Access

455

456

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Left mouse button

vbKeyRButton

Right mouse button

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

vbKeyCancel

CANCEL key

vbKeyMButton

Middle mouse button

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

CAPS LOCK key

vbKeyEscape

27

ESC key

vbKeySpace

32

SPACEBAR key

vbKeyPageUp

33

PAGE UP key

vbKeyPageDown 34

PAGE DOWN key

vbKeyEnd

35

END key

vbKeyHome

36

HOME key

vbKeyLeft

37

LEFT ARROW key

vbKeyUp

38

UP ARROW key

vbKeyRight

39

RIGHT ARROW key

vbKeyDown

40

DOWN ARROW key

vbKeySelect

41

SELECT key

459

Database Access

vbKeyPrint

42

PRINT SCREEN key

vbKeyExecute

43

EXECUTE key

vbKeySnapshot

44

SNAPSHOT key

vbKeyInsert

45

INS key

vbKeyDelete

46

DEL key

vbKeyHelp

47

HELP key

vbKeyNumlock

144

NUM LOCK key

KeyA Through KeyZ Are the Same as Their ASCII


Equivalents: 'A' Through 'Z'
Constant

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Key0 Through Key9 Are the Same as Their ASCII


Equivalents: '0' Through '9
Constant

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

Keys on the Numeric Keypad


Constant

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

MULTIPLICATION SIGN (*) key

vbKeyAdd

107

PLUS SIGN (+) key

vbKeySeparator

108

ENTER (keypad) key

462

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

vbKeySubtract

109

MINUS SIGN (-) key

vbKeyDecimal

110

DECIMAL POINT(.) key

vbKeyDivide

111

DIVISION SIGN (/) key

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

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

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

Biblio, 507, 508, 509


BODMAS, 88
Body, 60

Boolean property, 5, 77, 517


Browser, 77, 106, 412
Buddy, 38
Build, 528, 530, 535
Business, 20, 21
ButtonGroup, 41
Byte, ii, 65, 70, 71, 180, 287, 339
ByVal, 335, 337, 338, 339, 341, 342,
344, 346, 357, 360, 362, 416, 444,
449, 463, 467, 478

Calculate, 47, 194


Calculator, 323, 372, 373, 381, 400,
427
Cancel, 4, 19, 27, 77, 222, 254, 307,
308, 311, 319, 320
Caption, iii, 4, 19, 24, 27, 45, 76, 81,
Case Alternative, 148
CellFontColor, 246
CellFontName, 246
CellFontStrikeThrough, 246
CellFontUnderline, 246
CellFontWidth, 246
Celsius, 49, 139, 148, 153, 160
Change, 19, 20, 21, 100, 183, 187,
225, 236, 239, 275, 375
Check, 26, 41, 191, 307, 313, 383,
471
CheckBox, 16, 27, 77, 133, 190, 191,
194, 230, 231, 386, 401, 411, 431,
511, 529
Choose, iv, 156, 158, 190, 256
Choose function, 156, 158, 256

466

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

CHR, 238, 241, 275, 276, 279, 281,


288, 290, 291, 313, 314, 539
CHR function, 276, 279, 281, 291,
313
Class, 72, 351
Click, iii, vi, 20, 37, 38, 39, 95, 96,
Click Event, iii, 95, 108, 109, 187,
188
Close, 34, 39, 43, 55, 80, 104, 107,
109, 110, 188, 223, 234, 254, 255,
365, 416, 417, 526, 527, 529, 530,
533, 535
Code, ii, xi, 61, 62, 74, 93, 95, 96,
102, 108, 110, 113, 221, 223, 274,
275, 283, 306, 321, 373, 431, 433,
436, 455, 457, 536, 556
Combo Box, i, ii, 23, 24, 51, 95
Command Buttons, 3
Comment, 60, 115, 124, 194
Comments, iii, 115
Common, i, 12, 20, 25, 32, 34, 89,
106, 172, 174, 177, 200, 305, 340,
497
Comparison, iii, 87
Computer, i, 20, 84
Concatenation, v, 263
Constant, xi, 18, 47, 69, 109, 246,
249, 251, 275, 293, 304, 311, 312,
521, 545, 547, 548, 549, 556, 557,
559, 561, 562
Constants, ii, 68, 69, 137, 304, 311,
556
Control, i, iii, ix, 16, 17, 26, 34, 36,
37, 38, 39, 56, 81, 104, 122, 127,
175, 183, 188, 227, 234, 366, 377,
386, 446, 455, 456, 459, 460, 461,
506
Control Structures, i, iii, 127, 183

Controls, ii, i, ii, viii, xi, 1, 3, 4, 9,


10, 16, 22, 23, 26, 31, 32, 42, 49,
215, 251, 369, 370, 371, 372, 374,
377, 400, 461, 506, 511
Conversion, ii, 54, 160, 177, 179,
180, 190, 194, 286, 299, 391, 396
Copy, 243, 244, 259, 390
COS, 90
Count, 72, 282, 374, 379, 380, 382,
384, 388, 420, 422, 423, 505, 506
Counter, 162
Currency, ii, 66, 70, 71, 72, 396, 519,
520
Cut, 243, 259
D

Data, i, ii, iii, iv, v, vii, xi, 12, 16, 28,


31, 61, 64, 65, 66, 68, 69, 76, 79,
81, 84, 108, 120, 199, 200, 220,
227, 238, 239, 244, 251, 252, 253,
259, 260, 290, 316, 317, 382, 386,
409, 411, 438, 471, 504, 506, 507,
509, 511, 512, 518, 521, 522, 523,
532, 534, 535, 536, 537, 538, 539,
543
Data Control, i, xi, 31, 504, 506, 511,
512, 538
Data Control Language, 538
Data Definition Language, 538
Data Manipulation Language, xi, 538
Data Structure, i, iv, 199, 200, 386
Data Types, ii, 61, 64, 68
Database, ii, xi, 267, 504, 505, 507,
508, 519, 522, 523, 524, 528, 531,
532
Date, ii, 29, 67, 70, 71, 73, 78, 79,
90, 91, 92, 220, 304, 366, 519,
520, 521, 543, 544

467

Database Access

Date Data Type, ii, 67

Dates, 79
Day, 92
Debug, 13
Decision Statement, iv, 155
Default, vii, 18, 19, 27, 41, 72, 77,

130, 148, 222, 302, 312, 347, 533


Default argument, 347
Demulsifier, 518, 519, 538, 543,
545, 548, 549
DESC, 539, 547
Desktop, i
Determinant, 414, 497
Dialog, ix, 3, 4, 23, 96, 409, 410,
411, 417, 426, 433, 441, 443, 523,
524, 525
Dialog Box, ix, 4, 23, 426, 443
Dialog Boxes, ix, 426, 443
Dim, 69, 73, 74, 77, 78, 79, 80, 82,
92, 108, 110, 111, 112, 114, 120,
129, 131, 133, 135, 136, 140, 143,
146, 150, 153, 158, 160, 161, 162,
175, 179, 180, 189, 201, 202, 204,
205, 206, 209, 210, 213, 219, 221,
223, 224, 225, 226, 228, 230, 233,
243, 245, 253, 254, 255, 263, 264,
269, 270, 272, 274, 276, 282, 283,
285, 286, 287, 289, 291, 294, 296,
307, 309, 311, 313, 314, 317, 318,
321, 328, 330, 335, 339, 340, 341,
342, 344, 346, 348, 349, 350, 351,
352, 354, 359, 360, 362, 363, 364,
366, 373, 376, 377, 378, 379, 380,
382, 384, 385, 387, 388, 391, 396,
416, 423, 429, 430, 438, 441, 443,
444, 448, 449, 458, 461, 464, 465,
470, 471, 474, 475, 478, 479, 481,
484, 485, 489, 494, 497, 498, 514,
544, 546

Division, 84, 85, 87, 88


dm3, 47, 109
Do, iv, 22, 127, 147, 161, 166, 167,

169, 170, 171, 172, 175, 177, 179,


180, 181, 182, 183, 209, 213, 255,
289, 321, 340, 341, 356, 464, 465,
485, 534
Do Loop, iv, 166, 170, 172, 175, 177,
179, 180, 183, 255
Do Until, 169, 170, 175, 179, 180,
183, 255, 340, 341
Do While, 167, 169, 170
Double, ii, 65, 69, 70, 71, 72, 93,
100, 108, 110, 112, 113, 120, 129,
131, 133, 135, 140, 143, 146, 150,
153, 158, 160, 200, 201, 202, 204,
206, 207, 209, 210, 213, 223, 224,
225, 226, 239, 253, 283, 317, 318,
335, 337, 339, 340, 342, 348, 349,
350, 351, 358, 359, 360, 362, 363,
391, 421, 429, 430, 458, 461, 463,
464, 465, 466, 470, 471, 474, 478,
479, 484, 489, 494, 498, 520, 527,
530, 544, 546
Double click, 93, 527, 530
Drive C, 20
DropDown, 41, 42
Dynaset, 518
E

Edit, 13, 43, 95, 100, 259, 416, 433,


452, 533
Element, viii, 377
Else, iii, iv, 128, 129, 130, 131, 132,
133, 134, 140, 142, 143, 145, 147,
148, 155, 157, 158, 181, 182, 190,
210, 224, 225, 232, 257, 317, 318,

468

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

321, 349, 365, 379, 381, 384, 388,


396, 416, 431, 464, 465, 470, 485
Elseif, 144
Enable, 322, 354
Enabled, 77, 122, 223, 224, 225,
355, 366
End, iv, 104, 107, 108, 109, 110, d
function, 421
End IF, 239, 318, 361, 416, 464
End select, 148, 150, 153, 154
End Sub, 108, 109, 110, 119, 120,
129, 131, 133, 135, 141, 145, 150,
175, 179, 180, 187, 188, 189, 207,
209, 210, 214, 218, 222, 223, 224,
225, 227, 230, 233, 234, 250, 254,
270, 274, 276, 279, 283, 287, 289,
291, 295, 296, 298, 311, 315, 318,
320, 335, 340, 341, 358, 359, 360,
361, 362, 363, 365, 366, 376, 377,
379, 381, 384, 385, 388, 391, 396,
429, 431, 433, 435, 438, 439, 443,
444, 445, 449, 450, 458, 461, 464,
465, 466, 470, 474, 475, 481, 488,
489, 490, 494, 495, 496, 514, 536,
537, 540, 544, 546
End With, 118, 217, 228, 233, 236,
239, 250, 319, 377, 384, 388, 435,
437, 438, 439, 444, 445, 449, 450,
465, 466, 474, 475, 479, 490, 496,
546
EOF function, 255
Equal to, 87, 541
Equation, 128, 132, 149, 164, 174,
175, 180, 186, 192, 286, 287, 377,
393, 414, 451, 468, 480, 481
Errors, vii, 314
Evaluate, ix, 285, 430, 431, 455, 456,
458, 460, 497, 498

Event, iii, vi, vii, viii, 61, 93, 96, 98,

100, 102, 104, 106, 109, 111, 236,


254, 278, 327, 364, 371, 427, 514
Excel, i, viii, ix, 3, 26, 28, 29, 32,
234, 246, 247, 405, 406, 407, 408,
409, 410, 411, 412, 413, 414, 415,
416, 417, 418, 419, 426, 430, 431,
432, 433, 435, 436, 437, 439, 441,
442, 443, 445, 446, 448, 452, 453,
455, 458, 460, 461, 497, 499, 500
Execute, 47, 55, 104, 191, 195, 488
Exercise, 191, 193, 425, 451
Exit, iv, 43, 47, 127, 147, 181, 195,
196, 210, 211, 259, 309, 311, 318,
421, 474, 478, 485, 489, 494, 531
Exit Do, 181, 485
Exit For, 181, 210, 211, 474
Exit Property, 181
Exit Sub, 181, 318, 489, 494
EXP, 90, 462
Exponential point number, 66
Exponentiation, 84, 85, 87, 88
Exponentiation operator, 88
F
f, iii, viii, 30, 59, 60, 81, 108, 109,

122, 123, 139, 142, 192, 194, 200,


257, 259, 283, 318, 338, 390, 397,
456, 463, 465, 468, 470, 471, 472,
474, 476, 478, 479, 480, 490, 491,
492, 550, 552
F5, 25, 56, 104, 136, 236, 509, 511,
536, 562
Factor, 174, 340
Fahrenheit, 49, 136, 139, 140, 153,
158, 160
Fibonacci, 177

469

Database Access

Field, 519, 524, 525, 526, 527, 530,

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,

247, 248, 251, 257, 390, 391, 399,


405, 459, 499, 512
H
Height property, 122
Help, 3, 4, 19, 196, 259
Hour, 92

Icon, 227

IIF, 155, 157, 158


Image, 4, 16, 511
Image Control, 4
Index, ii, viii, 106, 189, 200, 211,

217, 229, 371, 372, 373, 384, 388,


396, 526, 527, 528, 530
Input Validation, 279, 295, 314, 319
InputBox, 79, 129, 131, 133, 175,
179, 180, 207, 209, 210, 211, 213,
239, 340, 438, 439
Insert Object, 446
Instr Function, 292, 299
INT, 90
Integer Division, 85, 89, 383
Inverse, 414, 564, 565
Italics, 245
ItemData, 214, 228, 229, 230
Iterative, 172, 501
J

George Bool, 68
Join function, 282, 288, 289
K

Kelvin, 49, 53, 66, 134, 135, 139,


153, 159
KeyCode Constants, ii
KeyDown, 101, 122
Keypressed, 100
Kodak, 42
L
Label, iii, 4, 16, 26, 100, 107, 108,

116, 122, 219, 227, 298, 511


Label control, 26, 107, 219
Label Control, 4

470

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Lbound, 200, 201, 203, 205, 206,


209, 226, 343, 348, 350, 374, 376,
383, 387, 480, 498
Len Function, 269, 328, 353
Less Than, 541
Like, 65, 87, 152, 155, 171, 181,
201, 235, 238, 251, 263, 264, 265,
266, 279, 296, 297, 298, 310, 358,
360, 370, 461, 507, 513, 514, 515,
516, 519, 520, 525
Like operator, 264, 265, 266, 279, 298
Line, i, iii, 16, 26, 78, 80, 108, 110,
112, 115, 116, 117, 120, 130, 131,
133, 135, 136, 141, 150, 162, 164,
179, 204, 207, 211, 214, 219, 234,
250, 270, 277, 281, 284, 285, 289,
291, 295, 296, 307, 311, 319, 335,
340, 342, 344, 349, 350, 363, 365,
366, 373, 374, 375, 377, 379, 381,
382, 387, 391, 423, 429, 431, 433,
436, 437, 439, 442, 445, 450, 458,
464, 475, 479, 482, 484, 490, 514,
516, 540, 541, 544, 546, 547, 549
Line feed, 281
Linear, ix, 210, 325, 392, 414, 452,
453, 454, 462, 472, 476
Linear Search, 210
Link, 27
List Box, 369, 452
List Property, 30, 217
Local, iii, 83, 84, 111, 164, 166
Local window, 164
LOG, 90, 456, 460
logarithmic scale, 437
Logical If, 257
Long, ii, 65, 70, 71, 72, 76, 77, 78,
82, 91, 219, 237, 243, 337, 339,
341, 344, 346, 352, 353, 354

Loop, iv, 128, 161, 162, 163, 164,

166, 167, 169, 170, 171, 172, 175,


179, 180, 181, 182, 183, 200, 203,
205, 206, 207, 209, 213, 214, 254,
255, 289, 321, 340, 341, 356, 370,
376, 379, 387, 407, 419, 423, 431,
464, 465, 485
Loop control variable, 162
Loop Counter, 163
Loop Until, 170, 209, 213, 464
Loop While, 321, 465, 485
LostFocus, 100
Lower Bound, 200
LowerBound, 349
Ltrim function, 270, 272
M

Macros, ix, 404, 415, 426, 431, 433,


435
Manufacturer, 519, 520, 521, 525,
527, 530, 542, 544, 548
Mass, 55, 56
Max, 38, 81, 221, 224, 225, 226,
298, 330, 333, 334, 335, 337, 339,
341, 463, 464, 465, 467
MDI, 405, 408, 410, 426, 432, 522,
523
Menu, ii, 7, 9, 16, 43, 45, 77, 195,
236, 259, 370, 406, 411, 415, 426,
431, 523
Menu Bar, 9
Menu Editor, ii, 43, 45
Menu Items, 259
MergeCell, 249
Message Box, vi, vii, 4, 122, 179,
207, 307, 308, 310, 311, 312, 313,
316
Message Boxes, 307, 311

471

Database Access

Metafiles, 20
Method, v, ix, 108, 109, 241, 330,

420, 422, 425, 514, 517


Methods, viii, xi, 243, 351, 420, 513
Microsoft, i, 7, 20, 23, 26, 27, 34, 36,
37, 42, 82, 183, 188, 234, 236,
247, 275, 293, 307, 365, 393, 394,
411, 426, 432, 441, 455, 461, 497,
505, 518, 522, 523, 553, 554
Microsoft Windows Common
Controls, 394
Mid, vi, 284, 285, 287, 288, 290,
291, 292, 297, 298, 300, 321, 341,
344, 353, 355, 485
Mid Function, vi, 284, 287, 290, 341
Mid Statement, vi, 290
Min, 38, 81, 224, 225, 226
Minute, 92
Mismatch, 73, 78, 316
Modal, 120
Modifying, iii, 106
Module level variable, 112, 113
Modulus, 85, 89
Mol, 401
momentum, 59
Month, 92
MonthName, 92
MS Chart, 42, 261
MS FlexGrid, 234, 405
MS Word, 3, 41, 59, 275, 405, 499
MSHFlexGrid, 239, 511
Multiple Integral, ix, 482
Multiplication, 84, 85, 87, 88

282, 284, 285, 286, 297, 300, 301,


322, 333, 340, 354, 367, 368, 382,
383, 384, 399, 400, 402, 425, 434,
437, 474, 475, 476, 477, 478, 479,
481, 482, 483, 484, 485, 490, 491,
500, 510, 511, 521, 552
Name, viii, 19, 24, 27, 45, 72, 76,
104, 106, 183, 259, 308, 317, 359,
371, 401, 406, 421, 436, 519, 520,
525, 526, 529, 535
Name Constant, 308
Nested Loop, iv, 182
Next, iv, 55, 98, 119, 125, 127, 161,
162, 163, 164, 169, 170, 181, 182,
183, 200, 203, 205, 206, 207, 209,
210, 211, 213, 214, 224, 225, 226,
233, 236, 238, 239, 240, 243, 254,
255, 257, 285, 287, 288, 291, 339,
342, 343, 344, 346, 348, 349, 350,
353, 355, 376, 377, 379, 381, 383,
384, 385, 387, 388, 396, 401, 407,
408, 409, 410, 419, 420, 421, 423,
431, 438, 442, 443, 444, 449, 450,
474, 475, 479, 484, 489, 494, 495,
498, 513
Nothing, 73, 442, 458
Now, 22, 92, 228, 315, 353, 366,
372, 375, 417
Numeric, 64, 65, 72, 78, 79, 148,
150, 252, 361, 561
Numerical Differentiation, ix, 454,
468, 471
Numerical Integration, ix, 454, 476
Nwind, 508

n, 4, 28, 47, 53, 71, 92, 110, 111,


125, 148, 158, 175, 207, 211, 212,
237, 242, 243, 254, 255, 256, 272,

O
Object, ii, iii, vii, viii, ix, xi, 61, 62,

68, 73, 75, 77, 95, 96, 98, 102,

472

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

104, 106, 217, 335, 351, 353, 373,


400, 420, 421, 422, 425, 427, 439,
448, 458, 504, 512
Object Browser, 77, 106, 354
Object List, 95, 96
Objects, vii, 70, 71, 77, 78, 352, 360
OLE, viii, ix, 16, 31, 404, 439, 446,
448, 450, 453, 499, 511
OLE Control, ix, 446
Open, 22, 29, 38, 43, 80, 95, 96, 102,
104, 114, 202, 215, 236, 253, 254,
255, 256, 259, 332, 364, 375, 390,
415, 417, 521, 522, 523, 532, 534
Option Base, 201, 205, 206, 209,
213, 214, 266, 343, 348, 488, 494
Option Button, 4, 19, 24
Option Compare, v, vi, 266, 268, 291,
292, 293, 296, 298
Option Explicit, 95, 96, 113, 122,
129, 130, 132, 135, 140, 143, 149,
153, 175, 179, 180, 187, 189, 201,
206, 209, 213, 223, 266, 270, 291,
296, 298, 311, 335, 337, 340, 341,
342, 352, 366, 429, 430, 474, 478,
488, 494
Optional argument, vii, 343
Ordinate, 397
Orientation, 24, 38
Overflow, 74

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,

188, 236, 313, 332, 334, 364, 405,


427, 440, 522, 539
Properties, i, iii, iv, v, viii, 6, 10, 11,
12, 29, 37, 62, 102, 106, 188, 215,
237, 245, 351, 364, 370, 374
Properties Window, i, iv, 10, 12, 29,
62, 188, 215
Property, i, ii, v, ix, 11, 37, 39, 61,
62, 76, 147, 217, 227, 228, 238,
239, 240, 242, 243, 249, 251, 355,
392, 395, 420, 422, 507
Property Pages, i, 37
Public, iii, 111, 112, 113, 114, 329,
330, 333, 337, 338, 339, 344, 346,
357, 358, 359, 361, 362, 416
PVT, 47
Q

Parallel array, 202, 203


Parameter, 201, 282, 514
Pascal, 53
Petroleum, i, 14, 518
Picture, i, 4, 12, 20, 26
Picture Box, 12

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,

180, 289, 340, 341, 438, 552, 557,


560
Rankine, 49, 53, 135, 139, 140, 160
Re, 60, 342, 438
Read Only, iii, 106
Records, xi, 511, 532, 534, 542, 543
Recordset, xi, 504, 506, 507, 510,
511, 512, 513, 514, 516, 536, 537,
540, 544
Recursive, iv, vii, 172, 174, 355, 357
Redo, 43
Relationship, 139
Rem, 115
Resize, 236, 394, 396
Right Function, vi, 296
RND, 90
Round, vi, 89, 120, 121, 305
Round Function, vi, 120, 305
Rtrim function, 269, 272
Rule, 505, 519
Run Time, v, 25, 217
Runtime, viii, ix, 108, 374, 455, 458
S

Save, 43, 104, 259, 334, 521, 522,


523
Saving, ii, 253
Scale, 12, 18, 411
Scale Mode, 18
Scope, iii, 61, 110, 333, 432
Score, 256, 401, 550, 551
Script control, 455, 461, 462, 480
Scroll, i, 16, 27, 34, 62, 77, 125, 188

Second, 92, 107, 142, 254, 312, 346,

368, 383
Select case, iv, 147, 150, 152, 153,

154
Selected Property, v, 231
Selection, v, viii, ix, 231, 400, 420,

421, 422, 423


SGN, 90
Shut Down, 3, 19, 22
SI, 49, 54, 191
Simultaneous, 414, 500
SIN, 90
Single, ii, 65, 70, 71, 72, 73, 77, 79,
90, 227, 321, 520
Slider, 16, 42, 122, 194
Snapshot, 518
Sort, iv, 208, 251, 259, 420, 547
Splash Screen, 4
Split function, 285, 292
SQL, xi, 518, 524, 538, 539, 540,
541, 542, 543, 544, 545, 546, 547,
548, 549
SQL Server, 518
SQR, 90, 115, 129, 131, 133, 155,
157, 226, 317, 318, 418
Standard Exe, 7, 14, 19, 118, 136,
188, 375, 427, 428, 508, 534
Standard Toolbar, 12, 412
Start, 7, 19, 104, 188, 191, 197, 198,
220, 222, 292, 293, 299, 365, 383,
431, 521
Startup Object, 364
Str, vi, 269, 456, 481, 497, 498
StrConv function, 275
Stretch, 20
String function, vi, 272, 281
Style, 24
Subtraction, 84, 85, 88
Switch, 155, 157, 158, 190, 257

474

Visual Basic 6.0 for Engineers and Scientists:ThankGod Egbe

Syntax, 91, 181, 278, 346

Tab, 183, 188, 241, 392, 480


Table Structure dialog, 526, 527
Tables, xi, 512, 518, 532, 534, 535
Tabstrip, i, 16, 36, 188, 189, 196,
392, 394, 396
Tag, 76, 354, 355, 518, 520, 521,
530, 538, 543, 548, 549
TAN, 90
Technique, 210, 316, 464
Temperature, 47, 55, 56, 109, 134,
139, 191, 192, 319
Text Box, i, 27, 369
Time, vi, 29, 90, 92, 303, 304, 366,
368, 390, 399, 519
Timer, 16, 100, 366, 367, 368, 461
Title, 275, 410, 509, 513, 514, 515,
516
Tool Box, 9, 36
Toolbar, i, 12, 13, 38, 39, 41, 426
Toolbar, 16, 104, 407, 436
Transpose, 27, 414
Trim function, 272, 274
Twip, 18
U

Ubound, 200, 201, 202, 203, 206,


209, 226, 287, 292, 342, 343, 348,
350, 374, 376, 383, 387, 480, 498
Ucase function, 275
Undo, 43
Unload, 100, 109, 121, 254, 261, 365,
376, 385, 438, 537
Until, 166, 167, 169, 170, 171, 172
UpperBound, 349

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,

49, 62, 66, 68, 72, 73, 74, 77, 78,


79, 80, 81, 83, 84, 90, 111, 112,
133, 134, 136, 140, 150, 156, 157,
158, 162, 163, 164, 175, 187, 188,
189, 198, 207, 215, 247, 269, 283,
285, 291, 295, 297, 305, 308, 309,
310, 311, 322, 328, 330, 337, 338,
339, 340, 341, 344, 350, 351, 353,
358, 359, 360, 363, 419, 420, 431,
436, 437, 453, 456, 462, 463, 466,
472, 476, 480, 486, 487, 490, 505,
507, 509, 518, 541, 545
Value property, 4, 77, 81
Variable, 69, 70, 72, 80, 111, 112,
113, 163, 200, 268, 316, 421
Variant 65, 68, 70, 71, 73, 90, 91,
150, 151, 204, 205, 213, 276, 277,
290, 291, 296, 297, 317, 348, 349,
350, 382, 421, 423, 463, 465, 494
VisData, 523, 524, 528, 531, 532,
533, 534, 535, 536, 537
Visible, 4, 5, 77, 105, 220, 227, 354,
375, 377, 379, 380, 384, 442, 443,
444, 449, 450, 475, 545, 546
Visual Data Manager, 504, 518, 522
Visual Studio, 3, 7, 20

Volume, 47, 55, 56, 109, 191, 205,


390, 518, 538
W
Watch, iii, 83

475

Database Access

Watch Window, iii, 83


Week, 92
WeekDayName, 91
Wend, 167, 168
While, 3, 62, 166, 167, 170, 171, 358
Width 5, 6, 19, 22, 24, 62, 63, 76, 77,

105, 375, 379, 380, 384


With block, 118, 217, 319, 436, 437

X
XY Scatter, 435

Y
Year, 92, 516

You might also like