Visual Basic Environment - Shahab Mohaghegh

Transcription

Visual Basic Environment - Shahab Mohaghegh
VISUAL BASIC
For
Engineers & Scientists
Shahab D. Mohaghegh, Ph.D.
Professor
Petroleum & Natural Gas Engineering
West Virginia University
March 1997
TABLE OF CONTENTS
Chapter 1:
Problem Solving with Visual Basic
Introduction
1.1
Solving Problems with Visual Basic
1.2
Using a Five-Step Problem-Solving Process
1.3
The Five-Step Problem-Solving Process in Visual Basic
Summary
References
Chapter 2:
An Introduction to Visual Basic
Introduction
2.1
Event Driven Programming
2.2
Visual Basic Environment
2.2.1 Menu Bar
2.2.2 Toolbar
2.2.3 Toolbox
2.2.4 The Form Window
2.2.5 Project Window
2.2.6 Properties Window
2.2.7 Code Window
2.2.8 Debug Window
2.3
Creating Graphical user Interface (GUI)
2.4
Objects and Controls
2.4.1 Object / Control Properties
2.4.2 Object / Control Procedures
2.5
Menus and Dialog Boxes
2.6
File Access
2.6.1 Opening and Closing Files from within a Program
2.6.2 Reading from a File
2.6.3 Writing to a File
2.7
Writing Code
2.6.1 General Declaration
2.8
Using On Line Help
2.9
Conventions
Summary
References
Chapter 3:
Engineering Computation with Visual Basic
Introduction
3.1
Writing your First Program (Windows Application)
The Hello Program
3.1.1 Writing Visual Basic Code
3.1.2 Improving the First Program
The New Hello Program
3.1.3 Try It!
3.2
Visual Basic Variables and Operators
3.2.1 Data Types
3.2.2 Variable Declaration
3.2.2.1 Local and Global Variables
3.2.2.2 Constants
3.2.3 Operators in Visual Basic
The Operator Program
3.2.3.1 Code Interpretation
3.2.4 Operators Combination and Formulas
3.2.4.1 Operator Precedence
3.2.4.2 Mathematical Functions
The Functions program
3.2.4.3 Code Interpretation
3.2.5 Other Operators
3.2.6 Try It!
3.3
Visual Basic Decision Structures
3.3.1 If ... Then Decision Structure
The New Operator Program
3.3.1.1 Code Interpretation
3.3.2 Select - Case Decision Structure
The Enhanced Operator Program
3.3.2.1 Code Interpretation
3.3.3 Try It!
APPLICATION: Electrical Engineering
APPLICATION: Chemical Engineering
Summary
References
Chapter 4:
File Access and Engineering Graphs with Visual Basic
Introduction
4.1
Visual Basic Loops and Arrays
4.1.1 For...Next Loops
4.1.2 Do Loops
4.1.3 Try it!
4.2
File Access in Visual Basic
2.6.1 Opening and Closing Files from within a Program
2.6.2 Reading from a File
2.6.3 Writing to a File
4.3
Engineering Graphs with Visual Basic
4.3.1 Histograms
4.3.2 Pie Charts
4.3.3 XY plots
4.3.4 Try It!
APPLICATION: Petroleum Engineering
APPLICATION: Mechanical Engineering
Summary
References
Chapter 5:
Engineering Applications with Visual Basic
APPLICATION: ELECTRICAL ENGINEERING
Equipment Reliability
Simulation Data
Electric Circuit Model
Spacecraft Data Analysis
APPLICATION: CHEMICAL ENGINEERING
Temperature Conversion
Waste Water Treatment
APPLICATION: CIVIL ENGINEERING
Simply Supported Beams
Earthquake Measurements
APPLICATION: MECHANICAL ENGINEERING
Stride Estimation
Composite Materials
Accelerometer Model
APPLICATION: PETROLEUM ENGINEERING
Oil Well Production
Oil and Gas Property Evaluation
APPLICATION: AEROSPACE ENGINEERING
Wind Tunnel
Computation of Lift and Drag Forces
Terrain Navigation
APPLICATION: ENVIRONMENTAL ENGINEERING
Timber Growth
SCIENTIFIC APPLICATIONS
Bacteria Growth (Biology)
Carbon Dating (Archeology)
Light Pipes (Physics)
Climatology Data (Meteorology)
Roots of Equations (Mathematics)
Visual Basic for Engineers & Scientists
1
Visual Basic Environment
Learning a programming language is an essential part of any
engineering education. Much can be said about usefulness and necessity
of programming languages in an Engineering curriculum. One thing
that usually cannot be said about programming languages such as
Fortran, C, or C++ is that, “they are exciting”. What sets Visual Basic
apart from other high level programming languages, is the excitement it
initiates in those that are learning it. This is of special importance to
freshman engineering students, since it contributes to the very
important issue of retention. Visual Basic provides a rich set of
technically oriented commands and functions that will prove more than
sufficient for solving any engineering problems during a 4 year
engineering program, as well as a graduate program.
Visual Basic Environment
In this chapter you will explore the Visual basic environment. A unique programming
environment that at the beginning can be a bit intimidating, but once you have completed
this chapter, you will find that it is actually a rich and user friendly environment. Lets us
start with the first dialog box that you will encounter once you start Visual Basic. Figure
1-1 shows the Visual Basic’s New Project dialog box.
Using this dialog box you will initiate your first project in Visual Basic. As you can see
this dialog box has three tabs. The New tab lets you initiate a new application. In this
course you will mostly create Standard.EXE applications, i.e. stand alone windows
programs.
Shahab D. Mohaghegh
Chapter ONE -1
Visual Basic for Engineers & Scientists
Figure 1-1. Visual Basic’s New Project dialog box.
Visual Basic also allows you to create other applications such as ActiveX controls and
DLLs (Dynamic Link Libraries – sharable subprograms used by other programs) or other
applications as viewed in this dialog box.
There are two other tabs. Existing tab lets you open existing Visual Basic projects to
edit or modify, while the Recent tab provides you with a list of most recently created or
edited Visual Basic projects. To start a new project, click on the Standard.EXE icon and
then click on the Open button. The window shown in Figure 1-2 will open.
We now explore the components of this window one by one. The Menu bar is at the very
top. Menu bar contains most of the utilities that are available to you in the Visual Basic
environment. Such as File, Edit, View, etc. Click on each of these items to see the
available utilities.
Shahab D. Mohaghegh
Chapter ONE -2
Visual Basic for Engineers & Scientists
Figure 1-2. New project environment.
Under the Menu bar is the Tool bar. Tool bar contains some of the most often used items
from the Menu bar in small icons. Move the mouse pointer on each icon and leave it for a
moment and the function of the icon will appear in a small sidebar.
Figure 1-3. Visual Basic Environment Menu bar.
Shahab D. Mohaghegh
Chapter ONE -3
Visual Basic for Engineers & Scientists
Figure 1-4. Visual Basic environment Tool bar.
The Toolbox in the Visual Basic environment contains the controls (also referred to as
objects) that are most often used in developing applications. Throughout this textbook
you will learn how to use all these controls.
Figure 1-5. Visual Basic environment Toolbox.
In the following table the controls in the toolbox will be introduced one at a time. In the
following chapters these controls will be used in different applications and their
properties will be explored.
Pointer
It does not draw a control. Pointer, lets you select,
resize or move a control already on a form.
Picture Box
Displays graphics, as a container that receives output
from graphics and print methods.
Label
Displays text that can not be changed, like caption
under a graphic. It can be changed by program codes.
Shahab D. Mohaghegh
Chapter ONE -4
Visual Basic for Engineers & Scientists
Text Box
Holds text that the user can either enter or change, or
text generated by application.
Frame
Allows you to create a visual or functional grouping
for controls. Draw the Frame first, and then draw
controls inside the frame, to form a group.
Command Button
Creates a button the user can choose (click) to carry
out a sequence of instructions.
Check Box
To choose between yes/no, true/false, and include/
exclude or multiple choices when more than one item
may be chosen.
Option Button
This control is used to select one item from a group
of items.
Combo Box
Combines the features of list box and text box. The
user can either choose an item from the list or enter a
value in the text box.
List Box
Displays a list of items from which the user can
choose one.
Timer
Used to activate a specific event at set intervals. This
control is invisible at run time.
VScrollBar (vertical
Provides a graphical tool for moving through lists or
scroll bar)
selecting data ranges.
HScrollBar
Provides a graphical tool for moving through lists or
(horizontal scroll bar)
selecting data ranges.
DriveListBox
Displays valid disk drives at run time.
DirListBox (directory
Displays directories and paths at run time.
list box)
Shahab D. Mohaghegh
Chapter ONE -5
Visual Basic for Engineers & Scientists
FileListBox
Displays a list of files at run time.
Shape
Used to draw a variety of shapes such as a rectangle,
square, rounded square, oval, or circle, etc.
Line
Used to draw a variety of line styles on your form at
design time.
Image
Displays a graphical image from a bitmap, icon,
metafile as well as JPG or GIF files. It is decorative
and uses fewer resources than a PictureBox.
Data
Provides access to data in databases through bound
controls on your form.
OLE
Allows you to link and embed objects from other
applications in your Visual Basic application.
Table 1-1. Most frequently used controls in the Visual Basic environment.
There are three other windows that appear in the Visual Basic environment. They are
Project window, Properties window and the Layout window. Project window provides
an explorer type view of all the forms and modules in the project, while Properties
window provides a list of all the properties available for each control with their
corresponding value.
Shahab D. Mohaghegh
Chapter ONE -6
Visual Basic for Engineers & Scientists
Figure 1-6. Visual Basic’s Project window.
Layout window shows the relative location of the forms on the screen. As you change
the location and size of the forms the changes are reflected in the Layout window.
Figures 1-6 and 1-7 shows Visual Basic’s Project, Properties and Form Layout windows.
You can change the location of the application window (the form) by moving its location
in the Form Layout window. To change the location of the form in the Form Layout
window simply click on it (where its written Form1) and drag it to any location in the in
the monitor’s picture.
Figure 1-7. Visual Basic’s Properties and Form Layout windows.
Shahab D. Mohaghegh
Chapter ONE -7
Visual Basic for Engineers & Scientists
Form window, shown in Figure 1-8, is the main window in the Visual Basic environment.
This is the window within which the application interface is developed. You develop the
application interface by placing controls in the Form.
Figure 1-8. Visual Basic’s Form window.
You can change the size of the form by clicking on the handles and dragging them.
Once the controls are placed in this window and their properties are assigned in the
Properties window it is time to attach codes to each control as needed. Attaching code to
the control means writing the sequence of instructions that pertains to each control.
In order to write the code for each control you must first bring up the code-editing
window for that control. You can do that by double clicking on the control. If you wish
to attach code to a Form, you should double click on the Form itself.
Shahab D. Mohaghegh
Chapter ONE -8
Visual Basic for Engineers & Scientists
Figure 1-9. Visual Basic’s code editing window.
Once the code edit window appears, the control that the code is being written for is
shown in the top left Combo Box and the event procedure is shown in the top right
Combo Box. Visual Basic is an event driven programming language. This simply means
that the applications that are developed using Visual Basic, much like any other windows
applications, will act upon the users actions (event procedures) such as Click,
DoubleClick, DragDrop, MouseDown, etc. Whenever you want the control in your
application to respond to an event, you put the instructions in the appropriate event
procedure. Of course the user does not initiate all the events. Sometimes events are
consequence of other events. For example as you start an application the main Form is
loaded in the memory and shows up on the screen. This is a Form_Load event, which
simply means that the Load event procedure is activated on the Form control. Using the
Shahab D. Mohaghegh
Chapter ONE -9
Visual Basic for Engineers & Scientists
arrow in the left Combo Box will show all the controls that are used in the application
and clicking on the arrow of the right Combo Box shows all the available procedure for
the control that is shown on the left Combo Box.
Control Properties
Every control in a Visual Basic application has certain characteristics called properties.
These properties dictate the way a control looks, size, color, and screen location among
other things. When you place a control in your application (either by drag and drop or by
double clicking on it) the property window will display the properties corresponding to
that control. There is a default value for each property. You may change these values to
fit the purposes of your application.
Once a control is placed on a Form, Visual Basic automatically will issue a name for that
control. This is the name that the control will be known by, to the rest of the application.
When you write codes for that control you notice that the name that Visual Basic has
given to this control appears in the top left Combo Box of the code edit window. This
name can be changed, just like any other property of the control, from the Properties
window. The Name property is the first property that appears in the Property window.
Figure 1-10 shows a form that has a Command Button control placed in it. The Property
window for the Command Button control is also shown in this Figure.
Shahab D. Mohaghegh
Chapter ONE -10
Visual Basic for Engineers & Scientists
Figure 1-10. Properties of the Command Button
Once a control like the Command Button control is placed on the Form, it has
“Command1” written on it. This is called the caption. This may become a little
confusing since the Name property of the control that is also “Command1”. In other
word, both the Name and the Caption (what appears on the Command Button control)
properties have the same value. To distinguish between them , the Caption on the
Command Button control was changed to “Click on Me”, and the Font property was
changed too. Another note worthy item is that when there are more than one control
present in the application during the design time, the properties of the control that is
selected will appear in the Properties window. Note the handles around the Command
Shahab D. Mohaghegh
Chapter ONE -11
Visual Basic for Engineers & Scientists
Button control in Figure 1-10. These handles are indicators that Command Button
control has been selected.
Try It!
Open Visual Basic and start a Standard.EXE project. In the Form that appears
place a Command Button control by double clicking on it in the Toolbox. Change the
properties of the control by making it larger. Now try to change the Caption on the
control, then change the Font.
Repeat this operation for the Text Box control and the Label control.
What If?
Write your first program by following these steps:
•
Open Visual Basic and start a Standard.EXE project.
•
Place a Command Button on the Form.
•
Change the Caption property to “Click on me to end the Program”.
•
Using the handles on the control, change its size until the above Caption
appears on a single line.
•
Change the Font to Arial (Bold).
•
Double click on the Command Button control to bring up the code-editing
window.
•
In the “Command1_Click()” event procedure, between the two provided lines
(they read “Private Sub Command1_Click()” and “End Sub”) type “end”.
Shahab D. Mohaghegh
Chapter ONE -12
Visual Basic for Engineers & Scientists
•
Then run the program by clicking on
the (Play Button) in the Tool
bar.
First Visual Basic Program
In this application you are asked to write a program that only consists of a
Form and a Command Button. When the application starts it should show the
Form with the Command Button in the center of it. The wording on the
Command Button should read “Click on Me to End the Program”. When that
Button is clicked the application should close.
1
Problem Statement
Write an application that can be closed (terminated) click of a button.
2
Input/Output Description
There are no particular inputs and out puts in this application. There are
actions and outcomes instead. The action is the click of the Command Button by
the user and the outcome should be the termination of the program.
3
Application Development
•
Open the Visual Basic and choose the Standard.EXE from the opening window.
•
Double Click on the Command Button control in the Toolbox. This will place a
Command Button control on the empty Form. The Command Button is now selected
on the Form. You can see the handles around it. Also, the Properties window is
displaying the properties of the Command Button that it has given the Name
Command1.
Shahab D. Mohaghegh
Chapter ONE -13
Visual Basic for Engineers & Scientists
•
Click on the Caption property in the Property window and change its value from
Command1 to “Click on Me to End the Program”.
•
Using the handles of the Command Button increase the size of the Command button
so the text can be shown on a single line.
•
Now click on the form itself to select it. You will notice that the Property window is
now displaying the Form properties.
•
Change the Caption property value from Form1 to First Program.
•
Double click on the Command Button. This will bring up the code-editing window.
•
Make sure that the word “Command1” appears in the top left Combo Box and the
word “Click” is displayed in the top right Combo Box. First line of this window
should read” Private Sub Command1_Click()” and there is an amply line and then
“End Sub”. In the empty line just type “end”.
•
Close the code-editing window by clicking on the cross (X) on the top right corner of
the window.
•
The code-edit window should look like Figure 1-11.
Figure 1-11. Code-editing window
•
Click on the Play Button to run your program. When you program is running, by
clicking on the Command Button the program will terminate.
Shahab D. Mohaghegh
Chapter ONE -14
Visual Basic for Engineers & Scientists
•
Now click on File on the Menu bar, and then click on “Save Project As…” This will
bring up a dialog box that asks you to name each form involved in your project and at
the end name the entire project. Give your project the proper name (Project 1 for
example).
•
Click on File again and then on “Make Project1.EXE”. This will generate an
executable file called Project1.EXE, which you can click on to run your program in
the Windows operating system environment.
The program interface should look like this.
Figure 1-12. First program interface.
The Hello World Program
In this application you are asked to write a program that consists of a Form a
Label and a Command Button. When the application starts it should show the
Form with a large “Hello World” written on it in blue. The Command Button is for
termination of the application.
1
Problem Statement
Write an application that displays “Hello World” and can be closed by click
of a button.
Shahab D. Mohaghegh
Chapter ONE -15
Visual Basic for Engineers & Scientists
2
Input/Output Description
There are no particular inputs and out puts in this application. There are
actions and outcomes instead. The action is the click of the Command Button by
the user and the outcome should be the termination of the program.
3
Application Development
•
Open the Visual Basic and choose the Standard.EXE from the opening window.
•
Double Click on the Label control in the Toolbox. This will place a Label control on
the empty Form. The Label is now selected on the form . You can see the handles
around it. Also, the Properties window is displaying the properties of the Label that it
has given the Name Label1.
•
Click on the Caption property in the Property window and change its value from
Label1 to “Hello World”.
•
Click on the Font Property. This will cause a small button with three dots on it to
appear on the left of the Font value. Click on that button to bring up the Font dialog
box. Use the dialog box and choose the font of your choice in bold and size of around
20. Then click on the ForeColor property to change the Font color.
•
Double click on the Command button control in the Tool box to place a Command
Button control on the Form
•
Click on the Caption property in the Property window and change its value from
Command1 to “&Exit”. This will cause the word Exit to appear on the Command
Button in this Form “Exit”. The fact that E is underlined simply means clicking on
this button is the same as clicking <control> E on the keyboard.
•
Use the Font property of the Command Box to change the caption’s Font.
•
Now click on the form itself to select it. You will notice that the Property window is
now displaying the Form properties. Change its caption to “Hello World Program”
•
Double click on the Command button. This will bring up the code-editing window.
Shahab D. Mohaghegh
Chapter ONE -16
Visual Basic for Engineers & Scientists
•
Make sure that the word “Comand1” appears in the top left Combo Box and the word
“Click” is displayed in the top right Combo Box. First line of this window should
read ”Private Sub Command1_Click()” and there is an empty line and then “End
Sub”. In the empty line just type “end”.
•
Close the Code Editing window by clicking on the cross (X) on the top right corner of
the window.
•
Click on the Play Button to run your program. When you program is running, by
clicking on the Command Button the program will terminate.
•
Now click on File on the Menu bar, and then click on “Save Project As…” This will
bring up a dialog box that asks you to name each form involved in your project and at
the end name the entire project. Give your project the proper name (Project 2 for
example).
•
Click on File again and then on “Make Project2.EXE”. This will generate an
executable file called Project2.EXE, which you can click on to run your program in
the Windows operating system environment.
Your interface should look like this.
Figure 1-13. “Hello World” program interface.
Shahab D. Mohaghegh
Chapter ONE -17
Visual Basic for Engineers & Scientists
Summary
In this chapter you learned about the Visual Basic development environment. You learnd
about Menu bar, Tool bar, Toolbox, Project window, Properties window, Layout
window, Form window, Code Editing window, and different controls that appear in the
Toolbox. You also learned how to write simple Visual Basic applications.
Keywords
Menu bar
Tool bar
Toolbox
Project window
Properties window
Control
Code
Application
Exercises
1.
Write a Visual Basic program (Develop a Visual
Basic Application) that displays your name in full and
terminates with click of a button.
2.
Write a Visual Basic program (Develop a Visual
Basic Application) that displays your name, your
University’s Name and your Major. This information should
appear in three different sizes, colors and fonts. Your
program (application) should terminate with click of a
button.
Shahab D. Mohaghegh
Chapter ONE -18
Visual Basic for Engineers & Scientists
2
Basic Computations with Visual Basic
In this chapter you will be introduced to several basic computation
methods using Visual Basic. In this chapter you will learn about
variables, data types, operators, two different types of decision
structures. You will also be writing more sophisticated Visual Basic
programs. It is important that you follow the path provided by this
manuscript and complete the exercises at the end of the chapter.
Introduction
In this chapter you will start by writing your first program. This will be a very simple
program, and does not require writing any code. You will write your first line of code
once you try to improve this program. In writing this first program you will use the
knowledge that you have acquired during the previous chapter.
After writing the first program you will be introduced to other concepts in Visual Basic
such as variables, operator, and decision structure. Each one of these concepts are
introduced in detail and new windows applications (programs) will be developed at each
stage.
WRITING VISUAL BASIC CODE
One of the outstanding features of Visual Basic is that you can accomplish a lot by
writing only a few lines of code. In Visual Basic, code is also referred to as program
statement.
A program statement can be as simple as a single word;
Shahab D. Mohaghegh
Chapter TWO - 19
Visual Basic for Engineers & Scientists
Example:
Beep
This statement causes the computer speaker to make a beep sound. A program statement
can also be quite sophisticated. One of the most usual forms of the program statements is
as follows:
Object name. property name = value
Example:
Label1.Caption = “Hello World”
This program statement assigns the words “Hello World” to the Caption property of an
object called Label1.
This format is used when you are trying to assign or change a property of an object or
control from within a program. Many of the properties for each object is usually set at
the beginning of a program, not by writing any code, rather by using the properties
window as was mentioned in the previous chapter.
IMPROVING THE FIRST PROGRAM
In the previous chapter you wrote your first program, it is time to use other
objects/controls to improve this program. We will use Command Button and Text Box
controls to improve the Hello Program.
The New Hello Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "New Hello" in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Shahab D. Mohaghegh
Chapter TWO - 20
Visual Basic for Engineers & Scientists
Project1.vbp in the File Name window. Type "New Hello" in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Object
Form
Text Box
Command Button
Command Button
Command Button
Property
Value
Caption
The New Hello Program
Name
frmHello
Name
txtHello
Multiline
True
Alignment
Center
Text
{Delete the Text1}
Caption
&Display
Name
cmdDisplay
Caption
&Clear
Name
cmdClear
Caption
&Exit
Name
cmdExit
In order to make the text appear in the center of the Text Box control the Alignment
property of the Text Box is changed to “center”. This change will only take place if the
Multi-line property of the Text Box control is changed to “True”. Also note that we have
added a “&” before letter “D” in the Display Command Box Caption properties. This
will cause Visual Basic to execute this command (same as clicking on the Command
Button) when the user uses the keyboard (holding the Control button and pushing the
letter D). The form will look like Figure 2-1:
Shahab D. Mohaghegh
Chapter TWO - 21
Visual Basic for Engineers & Scientists
Figure 2-1. The New Hello Program Interface.
4. Attach code to the Interface
Now its time to attach some code to the objects. For instance the program should end
once the command button exit is clicked. Codes for each object or control is written in
that control’s code-editing window. To view and write code in the code-editing window
you can either double click on the control or click once and then click on “View Code” in
the project window.
To attach code to the “Exit” Command Button, double click on this button, you will see
the following window:
Figure 2-2. Code-editing window for the Exit Command Button.
Shahab D. Mohaghegh
Chapter TWO - 22
Visual Basic for Engineers & Scientists
Please notice a few things about this window, which is true for all code windows:
•
The name of the form where the control is located is printed in the top left corner.
This tells you that you are writing the code for this Form.
•
In the object drop-down list (Combo Box), at top left, you will see a list of all
controls in this Form. The form (frmHello) contains 4 controls (Exit Command
Button, Display Command Button, Clear Command Button, and Text Box). In
addition to these controls you can see two more entries, namely, Form and General.
•
This is a complete listing of controls and objects that you can attach code to.
•
In the procedure drop-down list (Combo Box) at the top right there is a list of
available procedures for each object.
•
Depending on what object and procedure is displayed at these two drop-down lists,
two lines of codes is written in the body of the window. These lines are not to be
interfered with. Visual Basic provides you with starting and ending code lines for
each object and its procedure.
•
Write the desired code for that object and procedure between the provided starting
and ending lines.
In most of the programs that are developed throughout this book, there will be an Exit
button that terminates the program. This button is always programmed the same as it
appears above. Therefore whenever in this book you see an Exit button, you may assume
it simply has an “End” in its Click event procedure, unless mentioned otherwise.
Writing Code for the Display Button
•
Double click on the Display button.
•
Type the following statements in the code-editing window.
Shahab D. Mohaghegh
Chapter TWO - 23
Visual Basic for Engineers & Scientists
txtHello.Text = “Hello....World....”
Figure 2-3 shows the code-editing window for the Display command button after the
code has been written.
Figure 2-3. Code-editing window for the Display button.
Please note that three different text colors is used.
•
Black for the code.
•
Green for comments, specified by ‘ (single quote)
•
Blue for reserved words. These are words used by Visual Basic, such as commands,
key words, and functions.
With this code you are simply changing the Text property of the “txtHello” Text Box
object to “Hello....World...”. This code is executed whenever the Display Command
Button is clicked. Hence the first line in the Code Window provided by Visual Basic is:
Private Sub cmdDisplay_Click()
Shahab D. Mohaghegh
Chapter TWO - 24
Visual Basic for Engineers & Scientists
Which corresponds to cmdDisplay control and Click procedure. Now add the following
code to the Clear Command Button.
txtHello.Text = “ ”
Which means whenever this Command Button is clicked, change the text property of the
txtHello Test Box to “
” (blank). You have now completed the new and improved
Hello program.
5. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “New Hello.exe”.
Accept by clicking “O.K”.
Anatomy of an Event Procedure
Looking at Figure 2-3 one notices several distinct features. These features are common
among all the event procedures. Let’s visit each component of the even procedure in
more detail. The first component is the word “Private”. This means that this procedure is
private to this form and can only be seen by procedures in this form. The alternative of a
“Private” procedure is a “public” procedure. A public procedure can be seen and used by
all the forms and modules in a project.
The second word after “Private” is the word “Sub”. This indicates that this is a subprocedure as opposed to a function. If it were a function then the second word would be
“Function” instead. A sub-procedure in Visual Basic is equivalent to a sub-program or a
subroutine in other high level programming language.
Shahab D. Mohaghegh
Chapter TWO - 25
Visual Basic for Engineers & Scientists
Next in Figure 2-3 we see the term “cmdDisplay_Click()”. This is the name of the
procedure. Every procedure within a form must have a unique name. It includes three
parts. First is the name of the control (cmdDisplay in this case) followed by a “under
score” character. The second part immediately after the under score character is the
event. In Figure 2-3 the click event is identified. The last part is the empty parentheses ().
This means that the procedure does not expect to receive any information from the
procedure or event that calls it. Such information is usually in the form of parameters or
arguments that are passed to the event procedure.
The last component in the Figure 2-3 is the word “End Sub”. This indicates that the
procedure has reached its end.
Try It!
Writing a program in Visual Basic that displays different information about you when
different Command Buttons are clicked. You may start with Name, Last Name, Address,
and Telephone Number. Make sure your program contains a Clear Command Button.
VISUAL BASIC VARIABLES AND OPERATORS
Variables are temporary memory locations that can contain different types of data. In
computer programming data is stored in variables for later retrieval. In Visual Basic
variables are also used to transfer information to an object property. When naming
variables in your Visual Basic programs you should adhere to the following conventions:
Shahab D. Mohaghegh
Chapter TWO - 26
Visual Basic for Engineers & Scientists
Keep it as short as possible without making it too cryptic.
It should be intuitive and descriptive.
It should start with a letter.
There should be no periods in the variable name.
It should be less than 256 characters long.
You may use upper and lower case characters (Visual Basic is not case sensitive).
You may use numbers.
You should not use reserved names such as Visual Basic Keywords, Objects or
properties.
DATA TYPES
It is a common practice in computer programming to declare the type of the
variable that is being used. Variable type refers to the type of data that the variable is
hosting. Following is a list of data types used in Visual Basic:
Data Type
Size
Range
Integer
2 bytes
-32,768 Through 32,767
Long Integer
4 bytes
-2,147,483,648 through 2,147,483,648
Single(precision floating point)
4 bytes
-3.042823x1038 through 3.042823x1038
Double (precision floating point)
8 bytes
-1.79769313486232x10308 through
1.79769313486232x10308
Currency
8 bytes
-922,337,203,685,477.5808 through
922,337,203,685,277.5808
String
Shahab D. Mohaghegh
1 byte/character
0 through 65,535 characters
Chapter TWO - 27
Visual Basic for Engineers & Scientists
Boolean
2 bytes
true/false
Date
8 bytes
January 1,100 through December 31,9999
Variant
16 bytes(number)
All data type range
22 bytes+1 byte/Character(string)
Table 2-1. Data types in Visual Basic.
When you do not specify the type of a variable in a declaration statement it takes the
default type which is a variant. As you can see in the above table, variant type allows the
variable to take both text (string) and number. Variables with variant data type can store
all the data types mentioned above and switch format automatically. It is highly
recommended that you use specific data types for specific tasks and variables. For
example a counter should always be an integer. Declaring variables at the beginning of
each program emphasizes discipline, and saves memory and increases program
efficiency. As you can see from the above table using variant data types, although
convenient, is not the most efficient way of programming.
VARIABLE DECLARATION
There are two ways to declare variables in Visual Basic. “Implicit” declaration is
when you start using a variable simply by assigning a specific data type to it. “Explicit”
declaration is when you declare each variable at the beginning of the program. Using
“Option Explicit” statement in the general declaration section of a program forces Visual
Basic to generate an error message if a variable is not declared. This way you make sure
that you are using only explicit form of variable declaration.
To declare a variable as a specific data type use the following format:
Shahab D. Mohaghegh
Chapter TWO - 28
Visual Basic for Engineers & Scientists
Dim Counter As Integer
Dim Velocity As Single
Dim Distance As Single
Dim LastName As String
Local and Global Variables
If a variable is declared in a specific event procedure, i.e. cmdDisplay_Click(), then it is a
local variable and can only be used in that event procedure with the declared format. If
you want to use this variable in another event procedure, then you must declare it again.
In order to make a variable available to all the controls and procedures in your program,
you need to declare it as a global variable. This is done by declaring the variable in the
General (declaration) event procedure. This event procedure is available through the
Code Window as the first item in the “Object” drop-down list and first item in the
“Proc:” drop-down list as seen in the following figure.
Figure 2-4. The Code Editing Window.
Constants
Constants are numbers that their value does not change throughout your project. In many
engineering problems there are constant numbers that are used quite often. In Visual
Shahab D. Mohaghegh
Chapter TWO - 29
Visual Basic for Engineers & Scientists
Basic you can declare a constant by using the keyword "Const". One of the more familiar
constants is π. To declare π as a constant in Visual Basic use the following format.
Const pi= 3.14159265
OPERATORS IN VISUAL BASIC
Mathematical operations in Visual Basic take place by the use of operators. Operators
will help us add, subtract, multiply, divide and exponentiate numerical values. Following
is a list of mathematical operations used in Visual Basic.
Operator
Meaning
Example
^
Exponentiation
3 ^3=27
*
Multiplication
3 * 3=9
/
Division
3 / 3=1
\
Integer Division
7 \ 2=3
-
Subtraction
3 - 3=0
+
Addition
3+3=6
Remainder Division
9 Mod 2=1
Mod
Table 2-2. Operators in Visual Basic.
The Operators Program
Now lets try writing a Visual Basic program to examine each of the operations mentioned
above.
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
Shahab D. Mohaghegh
Chapter TWO - 30
Visual Basic for Engineers & Scientists
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Operators" in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "Operators" in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Object
Property
Value
Name
frmOperators
Caption
The Operators Program
Name
txtNumber1
Multilin
True
Alignment
Center
Name
txtNumber2
Multiline
True
Alignment
Center
Name
txtResult
Multiline
True
Alignment
Center
Forecolor
Red
Label
Caption
First Number
Label
Caption
Second Number
Label
Caption
Result
Command Button
Name
cmdExit
Caption
&Exit
Name
cmdAdd
Caption
&Add
Form
Text Boxe
Text Box
Text Box
Command Button
Shahab D. Mohaghegh
Chapter TWO - 31
Visual Basic for Engineers & Scientists
Command Button
Command Button
Command Button
Command Button
Name
cmdSubtract
Caption
&Subtract
Name
cmdMultiply
Caption
&Multiply
Name
cmdDivide
Caption
&Divide
Name
cmdInteger
Caption
&IntegerDivide
Your program’s interface should look like this:
Figure 2-5. The Operators program interface.
4. Attach code to the Interface
Declarations of variables
Click on the "View Code" in the Project Window
In the "Object"drop-down list select "General" and in the "Proc:"drop-down list select
“(declarations)”
Type the following codes in this window
Shahab D. Mohaghegh
Chapter TWO - 32
Visual Basic for Engineers & Scientists
Dim x As Single
Dim y As Single
Dim z As Single
Or you may type:
Dim x, y, z As Single
Your Code Window should look like this:
Figure 2-6. Variable declaration in Visual Basic.
Addition
♦ Double click on the Add Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
x = Val (txtNumber1.Text)
y = Val (txtNumber2.Text)
z=x+y
txtResult.Text = z
Shahab D. Mohaghegh
Chapter TWO - 33
Visual Basic for Engineers & Scientists
Figure 2-7. Code Editing window for cmdAdd Command button.
Subtraction
♦ Double click on the Subtract Command Button
♦ Write the following code in cmdSubtract Code Window
x = Val (txtNumber1.Text)
y = Val (txtNumber2.Text)
z=x-y
txtResult.Text = z
As you can see this code is identical to the code that was typed in the cmdAdd_Click()
event procedure. The only difference is that the value assigned to variable z is the
subtraction of x and y and not the addition.
Other Operations
♦ Do the same as you did for the add and the subtract Command Buttons for the
other Command Buttons namely, Multiply, Divide and Integer Divide. Only
change the operator for each Command Button as applicable.
Shahab D. Mohaghegh
Chapter TWO - 34
Visual Basic for Engineers & Scientists
5. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Operators.exe”. Accept
by clicking “O.K”.
Code Interpretation
In the first line you are assigning the user input or the value of the Text property of the
txtNumber1 Text Box to the variable x. While the program is running, user will type the
first number for the operation in this Text Box. Your code will instruct Visual Basic to
retrieve this value and assign it to the Text property of the txtNumber1 object. The same
is true for txtNumber2 object in the second line of the code . Then the two variables x
and y are added together and the result is assigned to the variable z. The variable z is then
assigned to the Text property of the txtResult object that will consequently be displayed
in the interface.
OPERATOR COMBINATION AND MATHEMATICAL FORMULAS
Combining the mathematical operators that were discussed above carries out many
engineering calculations. By combining mathematical operators with mathematical
functions (that will be covered in this section), you can handle majority of the
engineering calculations. These combinations are called mathematical formulas that
describe certain behaviors. For example following mathematical formula describes the
distance of the center of gravity from a reference plane in a hollow cylinder sector:
C=
Shahab D. Mohaghegh
38.1972
(r
(r
2
3
3
)
− s sin a
2
)
−s a
Chapter TWO - 35
Visual Basic for Engineers & Scientists
Operator Precedence
A mathematical formula processes a combination of variables and operators. Following
is a valid Visual Basic program statement:
X = 12 + 8 / 4 - 1 * 3^2
Above calculation may have several different results depending on which operator is
executed first. For example is 12 added to 8 and the result is then divided by 4 or 9 is
first divided by 4 and the result is added to 12? Visual Basic executes mathematical
operators in a specific order. Following is the order of precedence that operators are
executed in Visual Basic.
Operator
Order of Precedence
^
First
* and /
Second
\
Third
Mod
Forth
+ and -
Fifth
Table 2-3. Operators order of precedence in Visual Basic.
In the above expression 3^2 is executed first. Then 9 (the result of 3^2) is multiplied by 1
and 8 is divided by 4. The above expression reduces to:
X = 12 + 2 - 9
Which will add up to 5.
Shahab D. Mohaghegh
Chapter TWO - 36
Visual Basic for Engineers & Scientists
When writing formulas in Visual Basic, it is recommended to use parentheses to separate
calculations. In Visual Basic, parentheses take precedence over everything else.
Innermost parentheses are always executed first regardless of the operators they contain.
Therefore use of parentheses forces precedence in calculations. Consider the following
expression:
Y = 3 + 5^2 / 9 * 2^3 – 10
If we present this expression in this format to Visual Basic the result will be 15.2222, but
this expression should resemble the following formula:
3 + 52
Y=
9 × 23 − 10
Above expression has a value of 0.4516. To make sure that the formula is presented to
the Visual Basic correctly, we must use parentheses. So the expression should be written
as:
Y = (3 + 5^2) / (9 * 2^3 - 10)
which will result in the correct answer.
Shahab D. Mohaghegh
Chapter TWO - 37
Visual Basic for Engineers & Scientists
Mathematical Functions
For more number crunching power, Visual Basic provides a set of mathematical
functions. Functions operate on a variable, an expression or a value that is provided as an
argument (n). Following is a list of some of the Visual Basic functions.
Function
Purpose
Sin(n)
Returns the sine of the angle n. the angle is expressed in radians
Cos(n)
Returns the cosine of the angle n. the angle is expressed in radians
Tan(n)
Returns the tangent of the angle n. the angle is expressed in radians
Atn(n)
Returns the arctangent of n, in radians
Abs(n)
Returns the absolute value of n
Exp(n)
Returns the constant e to the power n
Rnd(n)
Generates a random number between 0 and 1
Sgn(n)
Returns -1 if n is less than zero, 0 if n is zero, and +1 if n is greater than zero
Sqrt(n)
Returns the square root of n
Str(n)
Converts a numeric value to a string
Val(n)
Converts a string value to a number
Table 2-4. Pre-defined functions in Visual Basic.
You will find that majority of the mathematical formulas in engineering are a
combination of the above functions and mathematical operators. We will now write a
program that uses some mathematical operators as well as mathematical functions.
Shahab D. Mohaghegh
Chapter TWO - 38
Visual Basic for Engineers & Scientists
The Function Program
Now we will write an application that allows user to change the angle from 0 to 360
degrees using a sliding horizontal scroll bar. In 4 different Text Boxes user will see the
current value of the angle, as well as the sine, cosine and the tangent of that angle.
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Functions" in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type " Functions" in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Object
Form
Text Box
Text Box
Text Box
Text Box
Shahab D. Mohaghegh
Property
Value
Name
frmFunctions
Caption
The Functions Program
Name
txtAngle
Multiline
True
Alignment
Center
Name
txtSine
Multiline
True
Alignment
Center
Name
txtCosine
Multiline
True
Alignment
Center
Name
txtTan
Chapter TWO - 39
Visual Basic for Engineers & Scientists
Multiline
True
Alignment
Center
Label
Caption
ANGLES in Degrres
Label
Caption
Sine
Label
Caption
Cosine
Label
Caption
Tangent
Label
Caption
0
Label
Caption
360
Label
Caption
Angles in Degrees
Command Button
Name
cmdExit
Caption
&Exit
Name
hsbFunctions
Min
0
Max
360
Value
180
Horizontal Scroll Bar
Your program’s interface should look like this:
Figure 2-8. The Functions Program Interface.
Shahab D. Mohaghegh
Chapter TWO - 40
Visual Basic for Engineers & Scientists
In the Horizontal Scroll Bar control, we have changed the settings on three properties
other than the Name property. These are Min, Max and Value properties. Min and Max
properties set the lower and upper limits of the scroll bar and Value property determines
the initial location of the sliding thumb. You may use the Font and ForeColor properties
in the Label and the Text Box controls to change the typeface, size, and the color of the
fonts.
4. Attach code to the Interface
Declaration of variables
♦ Click on the "View Code" in the Project Window
♦ In the "Object"drop-down list select "General" and in the "Proc:" dropdown list select “(declarations)”
♦ Type the following codes in this window
'Declare Variables and Constants
Dim x As Single
Dim y As Single
Dim w As Single
Dim z As Single
Const pi = 3.1416
♦ Write the code for the Horizontal Scroll Bar control
♦ Double click on the Horizontal Scroll Bar control to bring up its Code
Window.
♦ Write the following code in the hsbFunctions_Change() event procedure.
Shahab D. Mohaghegh
Chapter TWO - 41
Visual Basic for Engineers & Scientists
'Read The angle from the Scroll Bar and
x = hsbFunctions.Value
txtAngle.Text = x
'Change it to radians
a = x * pi / 180
'Calculate the Functions and show them
y = Sin(a)
txtSine.Text = y
w = Cos(a)
txtCosine.Text = w
z = Tan(a)
txtTan.Text = z
5. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Functions.exe”. Accept
by clicking “O.K”.
Code Interpretation
In the first line you are assigning the current value of the scroll bar to the variable x. In
the second line value of x is displayed in the txtAngle Text Box. Then the angle is
changed to radians, since the functions we will be using will need their arguments to be
in radians. In the next six lines we first calculate the sine, cosine and tangent of the angle
and then they are displayed in the proper Text Box control.
Shahab D. Mohaghegh
Chapter TWO - 42
Visual Basic for Engineers & Scientists
OTHER OPERATORS
Visual basic has other operators beside mathematical operators that were just covered.
These are called comparison operators and logical operators. Next section will be
devoted to these kinds of operators.
Try It!
Write a program that accepts user’s inputs in Centimeters and provides inches,
feet and meters as output.
VISUAL BASIC DECISION STRUCTURES
Visual Basic allows you to add logic to your program as well as to control the flow of
your program. Using the decision structure you can evaluate any given situation and take
the appropriate action. In other words Visual Basic’s decision structure allows you to
examine a condition and use the outcome of the condition to decide which program
statements to execute next. You can do this in Visual Basic using two different types of
decision structures. If...Then decision structure and Select Case decision structure.
IF ... THEN DECISION STRUCTURE
Using comparison operators within an If ... Then decision structure you can
control the order in which the program statements are executed. An If ... Then decision
structure has one of the following formats:
If condition Then statement
or
If condition Then
Shahab D. Mohaghegh
Chapter TWO - 43
Visual Basic for Engineers & Scientists
statement1
statement2
End If
or
If condition Then
statement1
Else
statement2
End If
or
If Condition1 Then
Statement1
Statement2
ElseIf Condition2 Then
Statement3
Statement4
ElseIf Condition3 Then
Statement5
Statement6
End If
As you see the If ... Then decision structure can have several formats. You should use the
comparison operators to evaluate the conditions such as “Greater Than”, “Less Than”,
and others. Following table shows Visual Basic’s comparison operators.
Shahab D. Mohaghegh
Chapter TWO - 44
Visual Basic for Engineers & Scientists
Comparison Operator
Meaning
=
Equal to
<>
Not Equal to
>
Greater Than
<
Less Than
>=
Greater Than or Equal to
<=
Less Than or Equal to
Table 2-5. Comparison operators in Visual Basic.
Example:
If Option1.Value=True Then Label1.Caption=”First Option Is Selected”
or
Dim TempFahrenheit As Single, TempCelsius As Single
If TempCelsius<>100.0 Then
TempFahrenheit=(9.0/5.0)*TempCelsius+32
Text1.Text=TempFahrenheit
End If
or
Dim interval As Integer, Counter As Integer
If interval<100 Then
Counter=Counter+1
Else
Counter=Counter+2
End If
Shahab D. Mohaghegh
Chapter TWO - 45
Visual Basic for Engineers & Scientists
or
Dim Temperature As Single
If Temperature<50 Then
Text1.Text= “The Temperature is too Low”
ElseIf Temperature>50 and Temperature<100 Then
Text1.Text= Temperature
ElseIf Temperature>100 Then
Text1.Text= “The Temperature is too High”
End If
As you probably have noticed there are times that you have to combine more than one
condition to make a new condition. In the last example the second “ElseIf” condition
states that “If Temperature is between 50 and 100 Then ...” which needs more than one
condition to be met. In such cases you should use logical operators.
Following is a list of logical operators and their meaning in Visual Basic.
Logical Operator
And
Meaning
If both conditional expressions are True,
then the result is True.
Or
If either conditional expressions are True,
then the result is True.
Not
Shahab D. Mohaghegh
If the conditional expressions is False, then
Chapter TWO - 46
Visual Basic for Engineers & Scientists
the result is True.
If the conditional expressions is True, then
the result is False.
Xor (Exclusive Or)
If one and only one of the conditional
expressions is True, Then the result is
True. If both are True, or if both are False,
then the result is False.
Table 2-6. Logical operators in Visual Basic.
Following table displays the result of combination of comparison and logical operators in
a compact form:
A
B
Not A
A or B
A and B
False
False
True
False
False
False
True
True
True
False
True
False
False
True
False
True
True
False
True
True
Table 2-7. Combination of logical operators in Visual Basic.
Now lets use the if ... Then decision structure in a program.
The New Operators Program
This program is a different version of the program that was developed in the last section.
Now instead of using a separate command button for mathematical operations we will try
to implement the same idea through the If ... Then decision structure and use of the
Frame and the Option Button objects or controls.
Shahab D. Mohaghegh
Chapter TWO - 47
Visual Basic for Engineers & Scientists
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "New Operators" in place of Form1 and click "O.K."
(Make sure you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "New Operators" in place of Project1
and click "O.K."
3. Develop the interface using the following information.
Object
Property
Value
Name
frmNewOperators
Caption
The New Operators Program
Name
txtNumber1
Multiline
True
Alignment
Center
Name
txtNumber2
Multiline
True
Alignment
Center
Name
txtResult
Multiline
True
Alignment
Center
Forecolor
Red
Label
Caption
First Number
Label
Caption
Second Number
Label
Caption
Result
Command Button
Name
cmdExit
Caption
&Exit
Form
Text Box
Text Box
Text Box
Shahab D. Mohaghegh
Chapter TWO - 48
Visual Basic for Engineers & Scientists
Command Button
Frame
Option Button
Option Button
Option Button
Option Button
Option Button
Option Button
Name
cmdCalculate
Caption
&Calculate
Name
frmNewOpt
Caption
Pick an Operator
Name
OptAdd
Caption
Add (+)
Value
True
Name
OptSubtract
Caption
Subtract (-)
Name
OptMultiply
Caption
Multiply (*)
Name
OptDivide
Caption
Divide (/)
Name
OptInteger
Caption
Integer Division (\)
Name
OptExponent
Caption
Exponentioation (^)
At this point few notes on the use of Option Buttons and Frames should be mentioned.
Usually, Option Button controls are used in a group of options from which the user
selects only one. In this problem all mathematical operators are grouped together. You
group Option Button controls by drawing them inside a container such as a Frame
control. To group Option Button controls in a Frame, draw the Frame first, and then
draw the Option Button controls inside the Frame control. All Option Button controls
within the same container act as a single group.
Shahab D. Mohaghegh
Chapter TWO - 49
Visual Basic for Engineers & Scientists
When a user selects an Option Button or a mathematical operation, the other Option
Button controls or mathematical operations in the same group are automatically
unavailable. Also making the Value property of the OptAdd Option Button to be True,
this Option Button will become the default choice in the group.
The interface that you just developed should look like this:
Figure 2-9. The Enhanced Operators program interface.
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
♦ In the "Object"drop-down list select "General" and in the "Proc:"drop-down
list select “(declarations)”
♦ Type the following codes in this window
Dim x As Single, y As Single, z As Single
Calculate Command Button
Shahab D. Mohaghegh
Chapter TWO - 50
Visual Basic for Engineers & Scientists
♦ Double click on the Calculate Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
'Read in the first and the second numbers
x = Val (txtNumber1.Text)
y = Val (txtNumber2.Text)
'Find which option is selected and then take appropriate action
If OptAdd.Value = True Then
z=x+y
ElseIf OptSubtract.Value = True Then
z=x-y
ElseIf OptMultiply.Value = True Then
z=x*y
ElseIf OptDivide.Value = True Then
z=x/y
ElseIf OptInteger.Value = True Then
z=x\y
ElseIf OptExponent.Value = True Then
z=x^y
End If
'Write the Result in the txtResult Text Box
txtResult.Text = z
Shahab D. Mohaghegh
Chapter TWO - 51
Visual Basic for Engineers & Scientists
5. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “NewOperators.exe”.
Accept by clicking “O.K”.
Code Interpretation
As in the previous program, in the first two lines you are assigning the values of the Text
property of the txtNumber1 and txtNumber2 (user input) to the variables x and y. The If
... Then decision structure will identify which mathematical operation should be executed
by examining the Value property of all the six Option Buttons available. The Option
Button with a True Value property, which will be the option selected by the user at run
time, will be executed and the result of the operation is assigned to the variable z. The
variable z is then assigned to the Text property of the txtResult object that will
consequently be displayed in the interface.
SELECT CASE DECISION STRUCTURE
Flow of a program can also be controlled using the Select Case decision structure. Select
Case decision structure lets you execute one of the several statements or group of
statements. Select Case decision structure has the following format:
Select Case Variable
Case value1
Statement1
Statement2
Case value2
Statement3
Statement4
Shahab D. Mohaghegh
Chapter TWO - 52
Visual Basic for Engineers & Scientists
End Select
When a Select Case decision structure is used, the process begins with the Select Case
keyword followed by the variable that is going to be examined. Value1, value2, ... refer
to the variable. Once a Case value matches that of the variable the statement or
statements following that Case value are executed and then the decision structure is
completed.
Example:
Dim SemestersCompleted As Integer
Select Case SemestersCompleted
Case 1
Label1.Caption=”You are a Freshman”
Case 3
Label1.Caption=”You are a Sophomore”
Case 5
Label1.Caption=”You are a Junior”
Case 7
Label1.Caption=”You are about to Graduate Soon”
End Select
Select Case decision structure supports comparison operators. There are two keywords
that you must use while using comparison operators with the Select Case decision
structure. These keywords are “Is” and “To”. Following example illustrate their use.
Example:
Dim SemestersCompleted As Integer
Shahab D. Mohaghegh
Chapter TWO - 53
Visual Basic for Engineers & Scientists
Select Case SemestersCompleted
Case Is < 3
Label1.Caption=”You are a Freshman”
Case 3 To 6
Label1.Caption=”You are half Way There”
Case Is > 6
Label1.Caption=”You are About to Graduate”
End Select
Now the use of Select Case decision structure is illustrated through a program.
The Convert Program
This program accepts values in degrees Celsius and converts them to degrees Fahrenheit,
Rankin, and Kelvin as requested by the user.
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Convert" in place of Form1 and click "O.K." (Make sure
you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "Convert" in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Object
Form
Shahab D. Mohaghegh
Property
Name
Value
frmConvert
Chapter TWO - 54
Visual Basic for Engineers & Scientists
Caption
TheConvert Program
Name
txtCelsius
Multiline
True
Alignment
Center
Name
txtNew
Multiline
True
Alignment
Center
Caption
Temperature Conversion
Font
{As you wish}
Label
Caption
Degrees Celsius
Label
Caption
Convert To:
Label
Caption
{Blank}
Name
lblResult
Name
cmdExit
Caption
&Exit
Name
cmdConvert
Caption
&Convert
Name
cmbConvert
List
Fahrenheit
Text Box
Text Box
Label
Command Button
Command Button
Combo Box
Rankin
Kelvin
Text
{Blank}
A Combo Box control combines the features of a Text Box control and a List Box
control. A Combo Box control displays a list of items from which the user can make a
selection. The first item in the list is ListIndex 0, and the value of the ListCount property
is always one more than the largest ListIndex value. In the Combo Box of this program
Shahab D. Mohaghegh
Chapter TWO - 55
Visual Basic for Engineers & Scientists
you entered three words, namely, Fahrenheit, Rankin, and Kelvin. These words will
show up in the Combo Box in the order that they appear in the List property, once the
arrow in the Combo Box is clicked. Each of them has an associated index number that
starts from 0 for Fahrenheit, and ends with 2 for Kelvin.
Also note that we have left the Caption property of lblResult control “Blank”. This is the
label that refers to the converted temperature. Since we do not know in advance which of
the three available temperature systems are going to be selected for conversion, we will
assign the proper Caption to this label once the selection is made. The program interface
will look like this:
Figure 2-10. The Convert program interface.
Please note that upon the start of the program “Fahrenheit” is shown in the Combo Box
as default. We will see how that is accomplished.
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
Shahab D. Mohaghegh
Chapter TWO - 56
Visual Basic for Engineers & Scientists
♦ In the "Object"drop-down list select "General" and in the "Proc:" drop-down
list select “(declarations)”
♦ Type the following codes in this window
Dim x As Single, y As Single
Initialization
Remember that you were asked to leave the Text property of the cmbConvert control
blank. In order to make the cmbConvert control to display its default value (Fahrenheit),
we instruct the Visual Basic to do it upon loading the interface or the main Form, by
assigning the List(0) property to the Text property of the Combo Box cmbConvert.
♦ Double click on the main Form (frmConvert)
♦ Visual basic responds by opening the Code Window
♦ Write the following code in the Form_Load () event procedure.
'Initialize the Combo Box
cmbConvert.Text = cmbConvert.List(0)
Convert Command Button
Double click on the Calculate Command Button
Visual basic responds by opening the Code Window
Type the following lines in the Code Window
'Read the user input in the Text Box
x = txtCelsius.Text
Shahab D. Mohaghegh
Chapter TWO - 57
Visual Basic for Engineers & Scientists
'Use the appropriate formula to convert the Temperature
'and change the Label Caption accordingly
Select Case cmbConvert.Text
Case cmbConvert.List(0)
y = (9 / 5) * x + 32
lblResult.Caption = "Degrees Fahrenheit"
Case cmbConvert.List(1)
y = (9 / 5) * x + 492
lblResult.Caption = "Degrees Renkin"
Case cmbConvert.List(2)
y = x + 270
lblResult.Caption = "Degrees Kelvin"
End Select
'Write the result in the Text Box
txtNew.Text = y
5. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Convert.exe”. Accept
by clicking “O.K”.
Shahab D. Mohaghegh
Chapter TWO - 58
Visual Basic for Engineers & Scientists
Code Interpretation
As in the previous programs, first line is for assigning the value of the Text property of
the txtCelsius to the variables x. The Select Case decision structure will identify which
conversion should be executed by examining the Text property of all the cmbConvert
control. Since the selectable alternatives in the Combo Box each have an index assigned
to them such as List(0), List(1) and List(2) from the List property of the cmbConvert
control, this identification is quite easy. The Case with the matching index of the List
property will be executed and the result of the operation is assigned to the variable y.
Furthermore in each case the Caption property of the lblResult Control is updated with
the proper string that reflects the conversion.
The variable y is then assigned to the Text property of the txtNew object that will
consequently be displayed in the interface.
Try It!
Write a program that accepts user’s age as inputs and returns your opinion of the user’s
age (Young, Old, ...) as output. Try it once with the Text Box control for the output and
once with the Label control.
What If?
Write an application that uses both Check Box controls and Option Button
controls.
Shahab D. Mohaghegh
Chapter TWO - 59
Visual Basic for Engineers & Scientists
Electrical Engineering Application
In this application you will create an application that calculates circuit equivalent
resistance as well as voltage drop.
1
Problem Statement
Determine the line current, the circuit equivalent resistance, and the
I1
16V +
-
R1=1.0 Ω
I2
R3=4.0 Ω
I3
R2=2.0 Ω
R4=3.0 Ω
voltage drop across the R4 for the following circuit.
2
Input/Output Description
The following diagram shows the input and the output of the program.
The inputs are resistance of all the resistors and the voltage of the battery and
the outputs are line current, circuit equivalent resistance and the voltage drop.
Equivalent
Resistances
Resistances
Line Current
Voltage
Voltage Drop
Shahab D. Mohaghegh
Chapter TWO - 60
Visual Basic for Engineers & Scientists
3
HAND EXAMPLE
Lets use the values given in the diagram to calculate our desired outputs.
V=RI
Parallel Resistors:
1/RP = 1/R2 + 1/R3 = 1/2.0 + 1/4.0
RP = 4.0/3.0 Ω
Series Resistors:
RT = R1 + RP + R4 = 1.0 + 4.0/3.0 + 3.0 = 16.0/3.0 Ω
RT = 5.3 Ω
Line Current:
V=RI
I = V (1/RT) = 16 (3.0/16) = 3.0 A
Voltage Drop:
V4 = R4 I = 3.0 * 3.0 = 9.0 V
4
ALGORITHM DEVELOPMENT
To calculate the desired output we need to follow these steps:
1. Read the resistance of each resistor
2. Read the voltage of the battery
3. Calculate the equivalent resistance of the resistors in parallel
4. Calculate the total equivalent resistance
5. Calculate the line current
6. Calculate the voltage drop
7. Display the results
Shahab D. Mohaghegh
Chapter TWO - 61
Visual Basic for Engineers & Scientists
5
TESTING
Input the values from section 3 above (hand example) and check the
results. Then input new values for resistors and voltage and check the results.
APPLICATION DEVELOPMENT
Following the steps in part 4 as applied to the Visual Basic, we follow the five-step
procedure for the application development.
The Circuit Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Circuit" in place of Form1 and click "O.K." (Make sure
you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "Circuit" in place of Project1 and click
"O.K."
3. Use the following objects to build the interface. Only the minimum information
about the interface is provided in this table. It is expected that you be able to
complete the interface using only the provided information.
Object
Property
Value
Form
Name
frmCircuit
Text Box
Name
txtR1
Text Box
Name
TxtR2
Text Box
Name
TxtR3
Text Box
Name
TxtR4
Shahab D. Mohaghegh
Chapter TWO - 62
Visual Basic for Engineers & Scientists
Text Box
Name
txtVolt
Label
Caption
W
Font
Symbol
Command Button
Name
cmdcalculate
Command Button
Name
cmdexit
Text Box
Name
txtEquivResist
Text Box
Name
txtLineCurrent
Text Box
Name
txtVoltageDrop
The interface should look like this:
Figure 2-11. The circuit program interface.
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
Shahab D. Mohaghegh
Chapter TWO - 63
Visual Basic for Engineers & Scientists
♦ In the "Object"drop-down list select "General" and in the "Proc:"drop-down
list select “(declarations)”
♦ Type the following codes in this window
Dim R1 As Single, R2 As Single, R3 As Single
Dim R4 As Single, V As Single
Dim Rt As Single, I As Single, VD As Single
Calculation
♦ Double click on the Calculate Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
'Read the Resistors and Voltage
R1 = Val (txtR1.Text)
R2 = Val (txtR2.Text)
R3 = Val (txtR3.Text)
R4 = Val (txtR4.Text)
V = Val (txtVolt.Text)
'Calculate the parallel resistance
Rp = 1 / ((1 / R2) + (1 / R3))
Rt = R1 + Rp + R4
'Display the total Resistance
txtEquivResist.Text = Rt
Shahab D. Mohaghegh
Chapter TWO - 64
Visual Basic for Engineers & Scientists
'Calculate the Line Current
I = V / Rt
'Display the Line Current
txtLineCurrent.Text = I
'Calculate the Voltage Drop
VD = R4 * I
'Display the Voltage Drop
txtVoltageDrop.Text = VD
5. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Circuit.exe”. Accept by
clicking “O.K”.
Biomedical Engineering Application
In this application you are asked to compute the growth of a colony of bacteria in
a petri dish. It is a widely used assumption that bacteria growth follows an
exponential model. It is a function of three different parameters, namely, initial
bacteria population, time and the medium in which the bacteria is growing. It is
also known that the wetter the medium, the easier will be for the bacteria to grow.
The effect of the medium in the mathematical equation is modeled by a time
coefficient. The exponential equation governing this phenomenon looks like this:
Shahab D. Mohaghegh
Chapter TWO - 65
Visual Basic for Engineers & Scientists
Ynew = Yold * [Exp (coef. * Time)]
In this application you are asked to develop an application that gives the user the
option of inputting medium time coefficient, initial bacteria population and the
time of growth. The program should calculate the new bacteria population given
the media and time.
1
Problem Statement
Provide the user with final bacteria population using the initial population,
media time coefficient and the growth time.
2
Input/Output Description
Inputs to this application will be initial bacteria population, media time
coefficient and the growth time. The output of this program will be the final
bacteria population after the growth time elapsed.
3
HAND EXAMPLE
Lets calculate the new bacteria population after 2 days in a medium with a
time coefficient of 1.380. Lets asume that initial bacteria population in the colony
was 15.
Ynew = Yold * [Exp (coef. * Time)]
New population will be:
Ynew = (15) * [Exp (1.380 * 2)]
Ynew = 237
Shahab D. Mohaghegh
Chapter TWO - 66
Visual Basic for Engineers & Scientists
4
ALGORITHM DEVELOPMENT
To calculate the desired output we need to follow these steps:
1.
Read the initial population and time
2.
Read the media time coefficients
3.
Calculate the new population of bacteria
4.
Each time check and see if the values of time and initial population has
changed.
5.
Only the results of those media that has been checked should be visible.
5
TESTING
Input the values from section 3 above (hand example) and check the
results. Then input new values for initial population, time and media time
coefficient and check the results.
APPLICATION DEVELOPMENT
Following the steps in part 4 as applied to the Visual Basic, we follow the 5 step
procedure for the application development.
The Biomedical Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Biomedical" in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "Biomedical" in place of Project1 and
click "O.K."
Shahab D. Mohaghegh
Chapter TWO - 67
Visual Basic for Engineers & Scientists
3. Use the following objects to build the interface. Only the minimum information
about the interface is provided in this table. It is expected that you be able to
complete the interface using only the provided information.
Object
Frame
-Text Box
-Text Box
-Text Box
Frame
-Text Box
-Text Box
Frame
-CheckBox
-CheckBox
-CheckBox
Frame
Shahab D. Mohaghegh
Property
Value
Caption
Media Time Coefficients
Name
txtdefDry
Text
1.386
Name
txtdefWet
Text
1.594
Name
txtdefMod
Text
1.449
Caption
Input Data
Name
txtyold
Text
10
Name
txttime
Text
2
Caption
Medium type
Name
chkdry
Caption
Dry medium
Value
1- Checked
Name
chkmoderate
Caption
Moderate medium
Name
chkwet
Caption
Wet medium
Caption
Number of bacteria
Chapter TWO - 68
Visual Basic for Engineers & Scientists
Name
txtdryynew
Text
{Blank}
-Text Box
Name
txtmoderateynew
-Text Box
Name
txtwetynew
Command Button
Name
cmdcalculate
Command Button
Name
cmdexit
-Text Box
The interface should look like this:
Figure 3.12. The biomedical engineering application interface.
4. Attach the following codes to the interface.
Variable declaration
Dim D As Single, M As Single, W As Single
Shahab D. Mohaghegh
Chapter TWO - 69
Visual Basic for Engineers & Scientists
Private Sub txtyold_Change()
txtdryynew.Text = ""
txtmoderateynew.Text = ""
txtwetynew.Text = ""
End Sub
Private Sub txttime_Change()
txtdryynew.Text = ""
txtmoderateynew.Text = ""
txtwetynew.Text = ""
End Sub
Private Sub chkdry_Click()
If chkdry.Value = 1 Then
txtdryynew.Visible = True
lbldrymedium.Visible = True
Else: txtdryynew.Visible = False
lbldrymedium.Visible = False
End If
End Sub
Private Sub chkmoderate_Click()
If chkmoderate.Value = 1 Then
txtmoderateynew.Visible = True
lblmoderatemedium.Visible = True
Else: txtmoderateynew.Visible = False
lblmoderatemedium.Visible = False
Shahab D. Mohaghegh
Chapter TWO - 70
Visual Basic for Engineers & Scientists
End If
End Sub
Private Sub chkwet_Click()
If chkwet.Value = 1 Then
txtwetynew.Visible = True
lblwetmedium.Visible = True
Else: txtwetynew.Visible = False
lblwetmedium.Visible = False
End If
End Sub
Private Sub cmdcalculate_Click()
'Read the Time Coefficients
D = Val(txtdefDry.Text)
M = Val(txtdefMod.Text)
W = Val(txtdefWet.Text)
'Calculate new Bacteria population
txtdryynew.Text = Format(txtyold.Text * Exp(D * _
txttime.Text), "###.##")
txtmoderateynew.Text = Format(txtyold.Text * _
Exp(M * txttime.Text), "###.##")
txtwetynew.Text = Format(txtyold.Text * Exp _
(W * txttime.Text), "###.##")
End Sub
Shahab D. Mohaghegh
Chapter TWO - 71
Visual Basic for Engineers & Scientists
Private Sub cmdexit_Click()
End
End Sub
5. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Biomedical.exe”.
Accept by clicking “O.K”.
Summary
In this chapter you learned about objects or controls such as Label, Text Box, Command
Button, Frame, Check Box, Combo Box, Horizontal Scroll Bar, and Option Button. You
also learned about variables and operators, data types, local and global variables, and
operator combination and mathematical functions. You now know how to write Visual
Basic code. Furthermore you learned about If… Then decision structure, Select Case
decision structure and logical operators.
Keywords
Operators
Decision Structure
Local
Global
Variables
Shahab D. Mohaghegh
Chapter TWO - 72
Visual Basic for Engineers & Scientists
Exercises
1.
Write an application that can convert length, area and
volume units in metric system to English units, and visa
versa.
2.
Write an application that given a person’s date of
birth will calculate his/her age in years, months, weeks,
days, hours, minutes, and seconds.
3.
Write an application that calculates the molecular
weight of hydrocarbons, given the number of carbon and
hydrogen atoms.
4.
Write an application that calculates the area and
perimeter of many different geometric shapes.
5.
Write an application that as input gets the speed of a
car in miles per hour from a sliding bar and converts it to
kilometer per hour. Your application must display the speed
in new units as the slide bar moves.
Shahab D. Mohaghegh
Chapter TWO - 73
Visual Basic for Engineers & Scientists
3
Engineering Computation with Visual Basic
In this chapter you will be introduced to several engineering
computation methods using Visual Basic. These methods include
reading data from and writing data into files, performing sophisticated
computations using loop structures and arrays. By the end of this
chapter you will also be able to graph functions and data to visualize the
results of your computations.
Introduction
In this chapter we will start by loops in Visual Basic that allows the user to repeat a
sequence of instructions many times. We will visit two kinds of loop structures in Visual
Basic. Arrays and their similarities and differences with regular variables, how to declare
them and when to use them is the subject of the next section. You will see why loops and
arrays naturally go together. The Chapter will continue by introducing you to data access
through files, and how to read and import data files and also how to write the results of
your calculations into data files.
The last part of the Chapter will be about graphs. You will learn how to use graphs in
your applications to help you visualize the data that you are working with. You will learn
different numerical methods and how a graph make these methods more useful. As we
progress through this chapter we introduce different concepts and go into details on at
least one particular application on each topic. Each section will build on the subjects
learnt from the past topics. In order to provide you with more practice on the covered
topics, applications that are introduced will have components of the previous topics.
Shahab D. Mohaghegh
Chapter THREE - 74
Visual Basic for Engineers & Scientists
Loops in Visual Basic
Loops are one of the most important topics in programming. This section will introduce
you to the implementation of loops in Visual Basic. Loop structure is employed
whenever the programmer tries to repeat a series of instructions and statements over and
over. There are several kinds of loops in Visual Basic. We will cover three different
kinds of loops in this section.
For … Next Loop
The first kind of loops in Visual Basic that is going to be discussed is the For … Next
loop. The For … Next loop has the following general structure:
For counter = start To end [Step step]
[statements]
Next [counter]
Where
"counter" is an integer that keeps track of the loop operation,
the number for "start" should be smaller than the number for "end" in the case of
positive steps, and visa versa in the case of negative steps.
[Step step] is an optional argument, if missing the step is considered to be +1, this
argument becomes important when we want to increment using different steps.
Example:
x=0
For i = 2 To 10 Step 2
x=x+i
Next i
Shahab D. Mohaghegh
Chapter THREE - 75
Visual Basic for Engineers & Scientists
In this example the x starts with being equal to 0. The loop is executed 5 times. It starts
with i = 2 and steps by 2 until it reaches 10, therefore values of i will be 2, 4, 6, 8, and 10.
During the first cycle 2 will be assigned to x since it had the value of 0 and i = 2 was
added to it. During the second cycle where the value of i = 4, and the value of x = 2 (from
the last cycle) the new value of x becomes 4 + 2 = 6. During this operation the value of i
is incremented by 2 at each cycle and added to the previous value of x. What would be
the value of x at the end of this operation?
In the above example the value of the counter i was increasing during each cycle. This
was due to the fact that we specified a positive step of 2. The value of the step can be
negative which would cause a decrement in the value of the counter instead of an
increment.
Example:
x=0
For i = 10 To 2 Step -2
x=x+i
Next i
What would be the value of x at the end of this operation?
EXIT FOR Statement
There will be occasions that you wish to exit the loop under certain circumstances. The
"Exit For" statement provides means for such circumstances. It goes without saying that
you will choose to exit the loop when a particular condition is met before all the cycles of
a loop are completed. Therefore a conditional statement such as an If statement will be
necessary for this operation. The "Exit For" statement has the following syntax.
For counter = start To end [Step step]
Shahab D. Mohaghegh
Chapter THREE - 76
Visual Basic for Engineers & Scientists
[statements]
If [condition] Then
Exit For
End If
Next counter
Following example will demonstrate the use of "Exit For" statement.
Example:
x=0
For i = 2 To 10 Step 2
x=x+i
If (x > 10) Then
Exit For
End If
Next i
In the above example you can see that only three out of the five cycles are implemented.
During the third cycle the value of x becomes 12 which causes the condition of the If
statement to be true. At this pint the "Exit For" statement is executed and the program is
kicked out of the loop. The fourth cycle will never take place. The "Exit For" is a
powerful statement. It has the potential to save time by preventing inutile calculations.
Shahab D. Mohaghegh
Chapter THREE - 77
Visual Basic for Engineers & Scientists
Do While … Loop
The second type of loop covered in this book is the Do While … Loop. This loop is used
to execute statements while a certain condition is true. It will stop operation as soon as
the condition becomes false. The syntax of this loop is presented bellow:
Do While condition
[ statements ]
Loop
Following example shows how this loop operation works.
Example:
m=0
x=0
Do While m<20
x=x+i
m = m +1
Loop
Recall that in the previous section (the For … Next loop) the counter was incremented
automatically. In this loop implementation you must increment the counter within the
loop. In the above example we used "m" as a counter and incremented it within the loop.
Just as the "Exit For" statement in the previous section there is a "Exit Do" statement in
the Do While … loop. The operation of the do loops is very similar.
Do While …Loop is considered to be a condition based loop. It may not be connected to
any counter. The best use of this method is when a statement must be executed over and
over but the final number of loops is unknown. Practically the loop is executed until the
condition is satisfied.
Shahab D. Mohaghegh
Chapter THREE - 78
Visual Basic for Engineers & Scientists
Example:
Do While ( input_value > 0 )
Input_value = InputBox ( “ Enter a negative number “)
Loop
In the above example the programmer wants the user to input a negative number. But
users can make mistake and that might make the entire program to malfunction. In order
avoid such incidents the programmer may use the above Do While … loop. Such
precautions are sometimes called error handling and are routinely used by programmers.
The instruction is repeated while the user enters a positive number and the rest of the
program is not executed until the user does what the programmer wants, which is
entering a negative number.
Shahab D. Mohaghegh
Chapter THREE - 79
Visual Basic for Engineers & Scientists
Arrays in Visual Basic
As an engineer you will be working with large amounts of data. Most of the information
that engineers deal with is in the form of numeric data. As an effective engineer you
should be able to manipulate data to infer conclusions, to recognize patterns, or to
visualize trends. So far you have learned that in order to use data in a Visual Basic
program you have to store them in variables. The question is that what will you do when
the number of data points increase. It is going to be very inefficient and impractical to
declare a different variable for each data point. Imagine that you have a file that contains
average daily temperature for the entire 1997, and you are going to write a Visual Basic
Program to calculate the average annual temperature for the year 1997. It is going to be
hard and inefficient to declare 365 different variables and store the data one by one. And
then calculate the average. There must be a better way. Well, there is.
In this section you will learn about arrays in Visual Basic. You will use arrays to develop
new applications. Arrays can be defined as a group of variables that share the same name
and the same data type. Different elements in this group of variables are distinguished by
a unique integer called an “index” or a “subscript”. The index or subscript that identifies
a particular element of an array appears in front of the array’s shared name enclosed in a
set of parentheses. Following is an example of an array with corresponding values for
average temperature for the past 4 days.
AveTemp(1) = 65.5
AveTemp(2) = 68.2
AveTemp(3) = 63.9
AveTemp(4) = 64.5
Shahab D. Mohaghegh
Chapter THREE - 80
Visual Basic for Engineers & Scientists
As you see all the above variables share the same name “AveTemp” and are
distinguished from one another through the index 1 through 4. Arrays occupy
consecutive locations in the computer memory once they are declared. Array is a
powerful tool for programmers that make writing codes easier.
In order to demonstrate the use of arrays a problem will be solved first without and then
with the use of arrays. The problem is in the field of engineering economics. Engineering
economics is an important component of all engineering disciplines. It is hard to find an
engineering program that does not require a course in engineering economics. In a
nutshell, engineering economics is the application of economic principals in engineering.
After all, as engineers your job is to find the best solutions to problems and some time
what distinguishes the best solution from others is the economic feasibility. In the
engineering economics one of the fundamental issues is the time value of the money. It
emphasizes on the fact that one dollar today have a higher value than one dollar at a
future time, say one year from now.
When evaluating engineering projects for their feasibility one needs to have a yardstick
to compare two similar projects to one another. One of the most used and wellrecognized yardsticks that incorporate the time value of money is the Net Present Value
or NPV. Net Present Value is the overall economic value of the project with today’s
dollar. This is due to the fact that usually each project requires a certain amount of
investment in the beginning and has the potential to make money in the years ahead. The
algebraic summation of in-flow (revenue) and out-flow (cost) of the money during the
life of the project is called Net Cash Flow. In such summation any kind of income such
as sales is denoted as positive cash flow and money spend such as operating cost, payroll
and maintenance are denoted as negative cash flow.
Shahab D. Mohaghegh
Chapter THREE - 81
Visual Basic for Engineers & Scientists
In the problem being discussed below, we look at a certain project that has a certain net
cash flow and we try to calculate a net present value for this project.
Net Present Value Calculations
Let’s see how Net Present Value of a project is calculated. This way it would easier for
you to follow the logic of the program. Let’s assume that a particular engineering project
will result in the following Net Cash Flow (NCF).
Net Cash Flow Year 0 (investment)
-$500,000
Net Cash Flow Year 1
$130,000
Net Cash Flow Year 2
$230,000
Net Cash Flow Year 3
$148,000
Net Cash Flow Year 4
$180,000
Net Cash Flow Year 5
$193,000
Table 3-1. Net cash flow of a potential project.
Net Cash Flow (NCF) for each year is calculated by subtracting all the money spent in
that year from the total income for the year. For example if the project makes $250,000 at
the end of the year but $120,000 were spend during the year on labor, and maintenance
then the NCF for that year would be $130,000. Let's further assume that the interest rate
will remain the same throughout the life of the project as 7.5%.
In order to calculate the Net Present Value of this project we have to convert the NCF for
each year to its value at today's dollar. Following formula is used to calculate the present
value of any future lump sum.
Shahab D. Mohaghegh
Chapter THREE - 82
Visual Basic for Engineers & Scientists
presentValue =
futureValue
(1 + i ) n
In the above equation “i” denotes the interest rate in fractions (in this case i = 0.075) and
exponent “n” represent the number of years of the cash flow. So the “present value” of
the NCF for the first and second years are calculated as:
(130,000) / (1+0.075)1 = 120,930.23
(230,000) / (1+0.075)2 = 199,026.50
Net Cash Flow
Present Value
Net Cash Flow Year 0 (investment)
-$500,000
-$500,000
Net Cash Flow Year 1
$130,000
$120,930.23
Net Cash Flow Year 2
$230,000
$199,026.50
Net Cash Flow Year 3
$148,000
$119,134.16
Net Cash Flow Year 4
$180,000
$134,784.09
Net Cash Flow Year 5
$193,000
$134,435.82
Table 3-2. Net cash flow and present value for the potential project.
The present value of all of the Net Cash Flow values are added together to calculate the
Net Present Value of the project.
We will first try to solve this problem without using the concept of arrays. We will then
use the concept of arrays and solve the problem again. This way you can clearly see the
advantages of using arrays in solving engineering problems. Another point that will be
Shahab D. Mohaghegh
Chapter THREE - 83
Visual Basic for Engineers & Scientists
discussed in the following problem is the power of Visual Basic in handling control
arrays (object arrays), which are an array of Visual Basic objects.
The Net Present Value Calculator Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "NPV Calculator” in place of Form1 and click "O.K."
(Make sure you are in the directory that you want to be). Another dialog box appears
with Project1.vbp in the File Name window. Type "NPV Calculator " in place of
Project1 and click "O.K."
3. Develop the interface using the following information.
Please note that starting now, no information will be provided regarding the font
selection for different controls. Selection of the font type, font size, font attributes, and
font color will be left to you to choose them per your taste.
Object
Form
Label
Label
Label
Label
Shahab D. Mohaghegh
Property
Value
Caption
NPV Calculator
Name
frmMain
Caption
Net Present Value Calculator
Name
lblTitle
Caption
Net Cash Flow
Name
lblNCF
Caption
Year 0
Name
lblY0
Caption
Year 1
Chapter THREE - 84
Visual Basic for Engineers & Scientists
Name
lblY1
Caption
Year 2
Name
lblY2
Caption
Year 3
Name
lblY3
Caption
Year 4
Name
lblY4
Caption
Year 5
Name
lblY5
TextBox
Name
txtNCF0
TextBox
Name
txtNCF1
TextBox
Name
txtNCF2
TextBox
Name
txtNCF3
TextBox
Name
txtNCF4
TextBox
Name
txtNCF5
Label
Caption
Annual Interest Rate %
Name
lblRate
TextBox
Name
txtInterestRate
CommandButton
Caption
&Calcualte
Name
cmdCalculate
Caption
Annual Interest Rate %
Name
lblRate
Caption
Net Present Value
Name
lblNPVTilte
Label
Label
Label
Label
Label
Label
Label
CommandButton
Shahab D. Mohaghegh
Caption
Name
lblNPValue
Caption
&Exit
Chapter THREE - 85
Visual Basic for Engineers & Scientists
Name
cmdExit
Please note that the caption property of label named “lblNPValue” is blank. This
has been done on purpose as you will see. The result of the calculation will be assigned to
the caption of this label. Once the development of the interface is completed the
interface of the application should look like that of Figure 4-1 below.
Figure 3-1. The Net Present Value Calculator Program Interface.
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
♦ In the "Object" drop-down list select "General" and in the "Proc:" drop-down
list select “(declarations)”
♦ Type the following codes in this window
‘Declaring variables
Shahab D. Mohaghegh
Chapter THREE - 86
Visual Basic for Engineers & Scientists
Dim NCF0 As Single, NCF1 As Single, NCF2 As Single
Dim NCF3 As Single, NCF4 As Single, NCF5 As Single
Dim PV0 As Single, PV1 As Single, PV2 As Single
Dim PV3 As Single, PV4 As Single, PV5 As Single
Dim InterestRate As Single, Factor As Single, NetPV As Single
Calculate Command Button
♦ Double click on the Calculate Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
‘Reading the Net Cash Flow values from the Text Boxes
NCF0 = Val(txtNCF0.Text)
NCF1 = Val(txtNCF1.Text)
NCF2 = Val(txtNCF2.Text)
NCF3 = Val(txtNCF3.Text)
NCF4 = Val(txtNCF4.Text)
NCF5 = Val(txtNCF5.Text)
'Calculating the interest factor
InterestRate = Val(txtInterestRate.Text) / 100#
Factor = InterestRate + 1#
'Calculating Net Present Value
PV0 = NCF0
PV1 = NCF1 / (Factor ^ 1)
Shahab D. Mohaghegh
Chapter THREE - 87
Visual Basic for Engineers & Scientists
PV2 = NCF2 / (Factor ^ 2)
PV3 = NCF3 / (Factor ^ 3)
PV4 = NCF4 / (Factor ^ 4)
PV5 = NCF5 / (Factor ^ 5)
NetPV = PV0 + PV1 + PV2 + PV3 + PV4 + PV5
'Assigning the calculated NPV to label for display
lblNPValue.Caption = NetPV
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...". The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “NPVCalculator.exe”.
Accept by clicking “O.K”.
Code Interpretation
Once the involved variables are declared in the “general” “declaration”, the net cash flow
values are read and assigned to NCF0 to NCF5 variables respectively. Then the interest
rate is read and assigned to the variable InterestRate. The interest rate is provided in
percent and must be converted to fraction before it is used in the program. Dividing the
interest rate by 100 would change it into a fraction. Then the variable "Factor" is
calculated by adding the integer number 1 to the interest rate.
The present value of a future lump sum is calculated as was demonstrated in the previous
section. The Net Present Value is then assigned to the Caption property of the
lblNPValue, which will be displayed on the interface.
Shahab D. Mohaghegh
Chapter THREE - 88
Visual Basic for Engineers & Scientists
Now we will rewrite the code for the NPV Calculator program using arrays. You will
notice that the code for this program is much more compact and easier to follow. We will
show you more than one way of writing this code at the end of the program in the “code
interpretation” section.
The Net Present Value Array Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "NPV Array” in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "NPV Array " in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Looking at the Figure 3-2 you will see that the interface for this program is very much
like the NPV Calculator program. There are two differences between these two
interfaces. First is that the NPV Array program has slots for 7 years while the previous
program has slots for 5 years. The second difference will be discussed after the following
table.
Object
Label
TextBox
Shahab D. Mohaghegh
Property
Value
Caption
Year 0
Name
lblYear
Name
txtNCF
Chapter THREE - 89
Visual Basic for Engineers & Scientists
For this program instead of creating seven separate Text Box controls one at a time and
giving each of them a unique name, only one Text Box is created. Then we copy the Text
Box control six times to have a total seven Text Box controls. We copy the control by
either pressing the copy icon on the toolbar or press “<control> c” or click on “Edit” and
then select copy from the menu. Then paste it by either pressing the paste icon on the
toolbar or press “<control> v” or click on “Edit” and then select paste from the menu. At
this point a dialog box will appear containing the following message: "You already have
a control named “txtNCF”. Do you want to create a control array?" Answer yes. You
will see that the newly copied Text Box has all the properties of the previous Text Box
but one. Scroll down the "properties window" until you see the “index” property. The
index property of this new Text Box has a value of 1 while the index property of the
original Text Box has a value of 0. You just created a control array. Each of the elements
in this array is a Text Box control with the common name of “txtNCF” and is
distinguished from other elements in the array by the index. The control array is shown as
“txtNCF( )”. Repeat this step six more times.
Shahab D. Mohaghegh
Chapter THREE - 90
Visual Basic for Engineers & Scientists
Figure 3-2. The Net Present Value Array Program Interface.
You will see that you have created a Text Box control array that has a total of eight
elements indexing from 0 to 7. Repeat this operation for the label “lblYear”. You may
change the caption property of each element of the label control array as it is shown in
the Figure 3-2.
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
♦ In the "Object" drop-down list select "General" and in the "Proc:" drop-down
list select “(declarations)”
♦ Type the following codes in this window
Dim NCF(7) As Single, PV(7) As Single
Dim InterestRate As Single, Factor As Single, NetPV As Single
Calculate Command Button
♦ Double click on the Calculate Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
‘Initializing the Net Present Value for new calculation
NetPV = 0
Shahab D. Mohaghegh
Chapter THREE - 91
Visual Basic for Engineers & Scientists
‘Reading the Net Cash Flow values from the TextBoxes
For i = 0 To 7 Step 1
NCF(i) = Val(txtNCF(i).Text)
Next i
'Calculating the interest factor
InterestRate = Val(txtInterestRate.Text) / 100#
Factor = InterestRate + 1#
'Calculating Net Present Value
For i = 0 To 7 Step 1
PV(i) = NCF(i) / (Factor ^ i)
NetPV = NetPV + PV(i)
Next i
'Assigning the calculated NPV to label for display
lblNPValue.Caption = NetPV
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “NPVArray.exe”. Accept
by clicking “O.K”.
Shahab D. Mohaghegh
Chapter THREE - 92
Visual Basic for Engineers & Scientists
Code Interpretation
Starting with the declaration,
Dim NCF(7) As Single, PV(7) As Single
We are declaring an array named NCF that has a total of 8 elements starting from 0 to 7.
The elements are NCF(0), NCF(1), NCF(2), … , NCF(7). As you can see the code is
much more compact and implicit.
Next we initialize the NPValue to zero. This is to make sure that every time we are
performing a new calculation the Net Present Value from the previous calculation is not
being carried over to the new problem.
Next is the following set of statements:
For i = 0 To 7 Step 1
NCF(i) = Val(txtNCF(i).Text)
Next I
This is a "For … Next" loop structure. The variable “i” is the counter as was explained in
the previous section. It also plays the role of the index in this case. As “i” steps from 0 to
7 every single element in the NCF( ) array is assigned a value. Each element of the NCF
array takes the value of the Text property of the corresponding TextBox control array
“txtNCF( )”. The second loop calculates the present value of each entry and then
calculates the summation of the present values, which is the Net Present Value.
Actually there is an even easier way of writing the code for this program. Following is
another – shorter – version of this program. Test it and see how it works.
Shahab D. Mohaghegh
Chapter THREE - 93
Visual Basic for Engineers & Scientists
‘Initializing the Net Present Value for new calculation
NetPV = 0
'Calculating the interest factor
InterestRate = Val(txtInterestRate.Text) / 100#
Factor = InterestRate + 1#
'Reading the Net Cash Flow values from the TextBoxes
For i = 0 To 7 Step 1
NCF = Val(txtNCF(i).Text)
PV = NCF / (Factor ^ i)
NetPV = NetPV + PV
Next i
'Assigning the calculated NPV to label for display
lblNPValue.Caption = NetPV
Data and File Access in Visual Basic
As an engineer you will be working with large amounts of data. Most of the information
that engineers deal with is in the form of data that is stored in files and/or databases. In
this section you will learn how to create a file, read data form the file and write into a
file.
The sequence for file access in Visual Basic includes the following three steps:
1. Opening an existing file, or creating a non-existing file.
Shahab D. Mohaghegh
Chapter THREE - 94
Visual Basic for Engineers & Scientists
2. Reading the data in the file and assigning them to variables, or writing the content
of some variables into the file.
3. Closing the file.
Reading from Sequential Files
When reading data from a file, the first step to is open an existing file where data resides.
Files in Visual Basic are opened using the Open statement. The syntax for opening a file
is:
Open pathname For mode As [ # ] filenumber
Where
pathname
includes the drive, directory or folder and the file name
mode
specifies the file mode: Append, Binary, Input and Output
filenumber
a valid file number. Each file when opened has a proper number.
Two files can not have the same filenumber in the same program.
Example:
Open "c:\my documents\datafile.txt" For Input As # 1
In above statement the programmer is opening an existing file called "datafile.text".
According to the path that is identified in the statement this file resides on the “c:” drive
in a directory called "my documents". The file has been identified as an input file and
given a number 1. Since most of the data in engineering applications is stored in ASCII
(numbers and characters as opposed to binary) the focus of this book will be on
manipulation of ASCII files.
Now that the file has been opened, in order to read from it the Input statement should be
used. The Input statement has the following syntax:
Shahab D. Mohaghegh
Chapter THREE - 95
Visual Basic for Engineers & Scientists
Input # number, expressionlist
Where
number
is the file number define when we opened the file.
expressionlist is the list of variables the data will be stored in.
And finally the file is close using the Close statement.
Example:
Open "c:\my documents\datafile.txt" For Input As # 1
Input # 1, x, y
Close # 1
In the above example the data in the file is apparently in three columns. The programmer
has chosen to assign the data in first column to a variable called "x", the data in the
second column to variable "y". Please note that the programmer must declare these
variables before using them. Once the file has been given a number it would be referred
to using that number throughout the program. This way you don't have to type all the
information about the file every time you are going to use it. Note that both Input and
Close statements refer to the file using its number.
Writing to a Sequential Files
There are two statements used to write in a sequential file. The syntax of these two
statements is given below:
Print # number, expressionlist
Write # number, expressionlist
Shahab D. Mohaghegh
Chapter THREE - 96
Visual Basic for Engineers & Scientists
Please note that all the three steps mentioned before are needed here too. In this case the
Open statement will create a new file called outputfile.txt if it already does not exist in
the "my document" directory.
Example:
‘ Using the Print statement or
Open "c:\my documents\outputfile.txt" For Output As # 1
Print # 1, x, y
Close # 1
or
‘ using the Write statement or
Open "c:\my documents\outputfile.txt" For Output As # 1
Write # 1, x, y
Close # 1
EOF Function
Lets assume that we know the number of columns in a data file. We assumed that there
were two columns of data in the "datafile.txt" file in the previous example. This is quite
common because we usually know what type of problem we are solving and what kind of
information is available for solving the problem. What is usually unknown is number of
data or records that are available for each parameter. In other words we usually know
how many columns we have but we seldom know how many lines of data exists in a file.
If we have that information the work is easy. Lets assume that we have prior knowledge
that the file "datafile.txt" includes two columns and 20 lines of data. In order to read all
the data in that file we may write the following code.
Shahab D. Mohaghegh
Chapter THREE - 97
Visual Basic for Engineers & Scientists
Example:
'Declare variables
Dim x (20) as double, y (20) as double
Open "c:\my documents\datafile.txt" For Input As # 1
For i = 0 to 20
Input # 1, x (i), y (i)
Next i
Close # 1
If the number of lines (rows) of data is not known you should use the "End Of File" EOF
function in the Visual Basic. This function detects the ending of the file and flags Visual
Basic that the end of the file has been reached there are no more data. The syntax of the
EOF function is as follows:
EOF (# number)
Where
Number
is the number assign to the file.
This function can be used as a stand-alone function or in conjunction with "Not" as the
negation.
Example:
'Declare variables
Dim x as Double, count as Integer
'Initialize variables
x=0
count = 0
'Open the file and read the data
Open “ c:\ temp\ data.txt” For Input As # 1
Shahab D. Mohaghegh
Chapter THREE - 98
Visual Basic for Engineers & Scientists
Do While Not EOF (1)
Input # 1, x
count = count + 1
Loop
Close # 1
In this example the data is only one column and is included in a file named "data.txt" that
resides in the 'temp" directory in the "c:" drive. We do not know how many pieces of data
are in the file and we would like to find the total number of data in the file. In other
words we want to count the number of lines in this file without actually opening it. The
variable "count" is declared as an integer and will hold the number of lines in the file.
After opening the file we start reading the data in the file and each time we read a data
we increment the variable count by 1. By the time we reach the End Of File (EOF) we
have counted all the lines in the file.
The Read Write Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "ReadWrite” in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "ReadWrite" in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Figure 3-3 presents the interface developed for this application. Use the table below and
try to develop an interface similar to that shown in Figure 4-3. Please note that the label
Shahab D. Mohaghegh
Chapter THREE - 99
Visual Basic for Engineers & Scientists
controls are not being shown in this table. At this point in the course you are expected to
know how to use the label control and make it look the ways you want.
Figure 3-3. The Net Present Value Array Program Interface.
Object
Property
Value
Text Box
Name
txtNumber
Text Box
Name
txtxvalmin
Text Box
Name
txtxvalmax
Text Box
Name
txtyvalmin
Text Box
Name
txtyvalmax
Command Button
Name
cmdRead
Command Button
Name
cmdWrite
Command Button
Name
cmdMinMax
Command Button
Name
cmdExit
Shahab D. Mohaghegh
Chapter THREE - 100
Visual Basic for Engineers & Scientists
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
♦ In the "Object" drop-down list select "General" and in the "Proc:" drop-down
list select “(declarations)”
♦ Type the following codes in this window
Option Explicit
Dim x(20) As Single, y(20) As Single
Dim i As Integer, j As Integer
Dim counterf As Integer
Read From File Command Button
♦ Double click on the Read From File Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
Open "c:\My Documents\Input.txt" For Input As 1
i=1
Do While Not EOF(1)
Input #1, x(i), y(i)
i=i+1
Loop
Close #1
Shahab D. Mohaghegh
Chapter THREE - 101
Visual Basic for Engineers & Scientists
counterf = i - 1
txtNumber.Text = counterf
Write To File Command Button
♦ Double click on the Write To File Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
Open "c:\My Documents\Output.txt" For Output As 2
For i = 1 To counterf Step 1
Print #2, x(i), y(i)
Next
Close #2
Determine Min and Max Command Button
♦ Double click on the Determine Min and Max Command Button
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
Dim k1 As Single, k2 As Single
For i = 1 To counterf Step 1
For j = i + 1 To counterf Step 1
If x(i) >= x(j) Then
k1 = x(i)
Shahab D. Mohaghegh
Chapter THREE - 102
Visual Basic for Engineers & Scientists
x(i) = x(j)
x(j) = k1
End If
Next
Next
For i = 1 To counterf Step 1
For j = i + 1 To counterf Step 1
If y(i) >= y(j) Then
k2 = y(i)
y(i) = y(j)
y(j) = k2
End If
Next
Next
txtxvalmin.Text = x(1)
txtxvalmax.Text = x(counterf)
txtyvalmin.Text = y(1)
txtyvalmax.Text = y(counterf)
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “ReadWrite.exe”. Accept
by clicking “O.K”.
Shahab D. Mohaghegh
Chapter THREE - 103
Visual Basic for Engineers & Scientists
Code Interpretation
After declaring all the necessary variables, following code is written for the “Read”
command button. It starts by opening the file that contains the data we are trying to read.
Open "c:\My Documents\Input.txt" For Input As 1
The above code uses the “open” statement and provides the absolute path to the data file
“Input.txt”. Absolute path refers to a path that goes as far back as the disk drive to
provide the address for the file. The “For Input As 1” indicates the file as one to read
from and assigns a number to the file for future reference.
i=1
Do While Not EOF(1)
Input #1, x(i), y(i)
i=i+1
Loop
Close #1
counterf = i - 1
txtNumber.Text = counterf
Above code first initializes the index “i” to one, and then using a “Do While” loop starts
reading the data one at a time. The condition “Not EOF (1)” indicates that the statements
following in the body of the loop are to be executed until the End Of the File is reached
and the number “1” in the parentheses refers to the file “Input.txt” as it was numbered in
the “open” statement. In the body of the loop the code “Input #1, x(i), y(i)” indicated that
data from file number 1 is to be assigned to arrays "x" and "y" . Note that at the
beginning the value of “i” is initialized to one. Therefore, the two numbers in the first
Shahab D. Mohaghegh
Chapter THREE - 104
Visual Basic for Engineers & Scientists
line will be assigned to x (1) and y (1). The statement "i = i + 1" is then executed. This
will increment the index “i” to two. The statement "Loop" indicates the closure of the
"Do While Loop" structure. Since after reading the first line of the data from the data file
"Input.txt" the EOF is not reached and thus the condition is not met, then the loop
continues. Now “i” has a value of 2, and the next line (line 2) of the data file is read and
assigned to x (2) and y (2) and then “i” is incremented again and so on, until the End Of
the File is reached and the loop ends.
At this point the file "#1" is closed since we no longer need this file. Note that by
incrementing the index “i” every time that we moved to a new line we have actually
counted the number of lines in the data file. We now pass this value to an integer variable
called "counterf" using the statement " counterf = i - 1", and subsequently assign
"counterf" to the text property of " txtNumber" text box to be displayed on the interface.
Next is the code for the "Write" command button. The same logic works here but this
time we write to a new file. Following line of code opens the file "Output.txt" if it already
exists in the path indicated otherwise would create a file in that directory and names it
"Output.txt". It indicates that it is an "Output" file and gives it a number 2.
Open "c:\My Documents\Output.txt" For Output As 2
Then using a "For ... Next" loop structure and the command "Print" we write each value
of the arrays "x" and "y" into the file number 2. Since we now know how many numbers
are in each of the "x" and "y" arrays (counterf) we indicated it in our loop structure.
Once the loop is completed we close the file using the "Close" command and reference
number of the output file which is 2.
Shahab D. Mohaghegh
Chapter THREE - 105
Visual Basic for Engineers & Scientists
For i = 1 To counterf Step 1
Print #2, x(i), y(i)
Next
Close #2
The next part of the code is to find the minimum and maximum value in array "x" and
"y". The following code is used to accomplish this task.
For i = 1 To counterf Step 1
For j = i + 1 To counterf Step 1
If x(i) >= x(j) Then
k1 = x(i)
x(i) = x(j)
x(j) = k1
End If
Next
Next
In this code there is a nested loop structure which means that on loop structure is inside
another loop structure. The first loop starts from the first element in the array and goes to
the end. The second loop structure loops through all the remaining elements and
compares each element with the rest. For example there are 13 elements in this array. In
this nested loop structure we start with the first element "i=1" and then the inside loop
starts from "j=2" all the way to "j=13" and compares the first element of the array x (1)
with all the other elements namely x (2) through x (13). Then the outer loop is
incremented and in the next round x (2) is compared with x (3) through x (13) and so on
until all the elements are covered. At the end minimum and maximum values are saved
Shahab D. Mohaghegh
Chapter THREE - 106
Visual Basic for Engineers & Scientists
and using the following code they are passed to the interface to be displayed. This is done
for both arrays separately.
txtxvalmin.Text = x(1)
txtxvalmax.Text = x(counterf)
Try It!
Generate a data file (using any ASCII editor such as note pad) that includes numbers 1
through 10. Save the file. Write a program that reads this file and creates another file that
contains two columns of data. The first column is the same as the file you read from and
the second column includes the square of the number in the first column.
What If?
Write the same program as in Try It, but this time use the EOF function.
Graphing Data in Visual Basic
As engineers you will be working with massive amounts of data. This will be the data
that you have collected or have been collected by others and your job is to analyze them.
Making sense of the data is an important engineering task. One of the best ways to
initiate data analysis is to plot the data and look for trends and patterns. In this section
we cover one method that you can use to look at your data.
There are more than one way to display data as a graph in Visual Basic. We cover a
technique that uses the "Picture Box" control in this section. When using "Picture Box"
Shahab D. Mohaghegh
Chapter THREE - 107
Visual Basic for Engineers & Scientists
control to display data, we use the "PSet" method. A method in Visual Basic is when you
ask a control to do something. The "PSet" method sets a point on an object (in this case a
"Picture Box" control) to a specified color.
The syntax for using the "PSet" method with an object (we are going to use it with the
"PictureBox" object in this section) is as follows:
object.PSet [Step] (x, y), [color]
The terms in square brackets [ ] are optional. The optional term [Step] is a keyword
specifying that the coordinates (x, y) are relative to the current graphics position given by
the CurrentX and CurrentY properties. The term (x, y) are required. They are to be
declared "As Single" indicating the horizontal (x-axis) and vertical (y-axis) coordinates
of the point to set. The term [color] is also optional. The R (red) G (green) and B (blue)
should be declared "As Long" integer values. You can use the RGB function or QBColor
function to specify the color. If omitted, the current ForeColor property setting is used.
In order to demonstrate the use of the combination of the "PictureBox" object and the
"PSet" method we try to simply put some point on a white background. More complex
problems will be solved later in this section.
The Draw Points Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As ..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Draw Points” in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Shahab D. Mohaghegh
Chapter THREE - 108
Visual Basic for Engineers & Scientists
Project1.vbp in the File Name window. Type "Draw Points" in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Figure 3-4 presents the interface developed for this application. Use the table provided
and try to develop an interface similar to that shown in Figure 4-4. Please note that the
figure shown below represents the interface after the program has been run and the points
been drawn. Originally the "Picture Box" control had a plain white background.
Figure 3-4. The Draw Points Program Interface.
Shahab D. Mohaghegh
Chapter THREE - 109
Visual Basic for Engineers & Scientists
Object
Property
Form
Picture Box
Command Button
Command Button
Value
Name
frmDrawPoints
Caption
Draw Points Program
Name
picDrawPoints
Backcolor
White color
Name
cmdDraw
Caption
&Draw Points
Name
cmdExit
Caption
&Exit
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
♦ In the "Object" drop-down list select "General" and in the "Proc:" drop-down
list select “(declarations)”
♦ Type the following codes in this window
Dim R As Long, G As Long, B As Long
Dim x As Single, y As Single
Dim Counter As Integer
As it was mentioned earlier R, G, and B are to be declared "As Long" and the coordinates
"As Single".
♦ Double click on the "Draw Points" Command Button
Shahab D. Mohaghegh
Chapter THREE - 110
Visual Basic for Engineers & Scientists
♦ Visual Basic responds by opening the Code Window
♦ Type the following lines in the Code Window
For Counter = 1 To 10000 Step 1
'Determine point color
R = Rnd * 255
G = Rnd * 255
B = Rnd * 255
'Determine point ( x,y ) coordinate
x = Rnd * picDrawPoints.ScaleWidth
y = Rnd * picDrawPoints.ScaleHeight
'Draw the points in the picture control
picDrawPoints.PSet (x, y), RGB(R, G, B)
Next
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Draw Points.exe”.
Accept by clicking “O.K”.
Code Interpretation
After declaring all the necessary variables, a "For … Next" loop structure is opened to
repeat a set of instructions for 10,000 times. The instructions inside the loop are divided
into three sections. First section includes assigning integer values to R, G, and B using
Shahab D. Mohaghegh
Chapter THREE - 111
Visual Basic for Engineers & Scientists
the Rnd function that is Visual Basic's random number generator. Each of these variables
can have a value between 0 and 255. Since the Rnd function provides a value between 0
and 1 it should be multiplied by 255 to get a random values between 0 and 255. In the
second section of the code x and y coordinates of the point is chosen randomly. The
random number generated for x and y should be multiplied by the "ScaleWidth" and
"ScaleHeight" property of the "Picture Box" control. This is to ensure that the point being
printed falls inside the control. The "ScaleWidth" and "ScaleHeight" property of the
"Picture Box" control are set automatically as you place this control on the form and
resize it using your mouse. To check this you can click on the "Picture Box" control on
the interface to select it. Once it is selected, click on one of the six handles around it and
resize it. Look at the "ScaleWidth" and "ScaleHeight" properties in the property window
while resizing the control.
The third and last section of the code is to draw the point using the random numbers
generated for the color and position of the point in the following manner. Please note that
the RGB function is used to generate the color using the R, G, and B values.
picDrawPoints.PSet (x, y), RGB(R, G, B)
Drawing Lines
In this section you will learn how to draw lines using the "Picture Box" control. As with
the "PSet" method there is another method associated with the "Picture Box" control
called the "Line" method. Following line of code draws a line in a picture box.
PictureBoxName.Line ( x1 , y1 ) – ( x2, y2 ) , RGB ( 0, 0, 0 )
Shahab D. Mohaghegh
Chapter THREE - 112
Visual Basic for Engineers & Scientists
The line starts at coordinates x1 and y1 and continues to coordinates x2 and y2. As for
the "PSet" method the RGB function provides the color option for the method. Instead of
using the second coordinates x2 and y2 you may choose to use another way of identifying
the end point of the line. This can be accomplished by the use of "Step" keyword. The
syntax for using the "Step" keyword is as follows:
PictureBoxName.Line ( x1 , y1 ) – Step ( dx, dy ) , RGB ( 0, 0, 0 )
In this case the line starts at the same x1 and y1 location and ends at (x1+dx) and
(y1+dy). Using the Step keyword in the "Line" method one can draw polygons.
Following is an example of using this technique to draw a rectangle.
PictureBoxName.Line (10,10) - Step (90,0)
PictureBoxName.Line - Step (0,90)
PictureBoxName.Line - Step (-90,0)
PictureBoxName.Line - Step (0,-90)
The above code draws the square in Figure 3-5. Please note that the origins of the
coordinates, i.e. x = 0, and y = 0 are at top left corner.
Shahab D. Mohaghegh
Chapter THREE - 113
Visual Basic for Engineers & Scientists
Figure 3-5. The code draws this square.
The first line of code draws a horizontal line from the top left corner to the top right
corner. The second line of code draws the vertical line from the top right corner to the
bottom right corner. The third line of code draws the horizontal line form the bottom
right corner to the bottom left corner and finally the last line of the code completes the
square by drawing the vertical line from the bottom left corner to the top left corner.
This technique should be used for drawing triangles and other polygons since there is an
easier way of drawing squares and rectangles in Visual Basic. The same square could
have been drawn using the following single line of code.
PictureBoxName.Line (10,10) - (100,100), B
In the above code one specifies the top left and bottom right corners and the option "B"
instructs Visual Basic to draw a box. Furthermore adding a letter "F" instructs Visual
Basic to fill the box with the color specified in RGB Function. Following is an example
for drawing a red box.
Shahab D. Mohaghegh
Chapter THREE - 114
Visual Basic for Engineers & Scientists
PictureBoxName.Line (10,10) - (100,100), RGB (255,0,0), BF
We now develop an application that draws a line in the picture box and also draws some
random lines.
The Draw Lines Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Draw Lines” in place of Form1 and click "O.K." (Make
sure you are in the directory that you want). Another dialog box appears with
Project1.vbp in the File Name window. Type "Draw Lines" in place of Project1 and
click "O.K."
3. Develop the interface using the following information.
Figure 3-6 presents the interface developed for this application. Use the table provided
and develop an interface similar to that shown in Figure 3-6.
Object
Form
Picture Box
Command Button
Command Button
Shahab D. Mohaghegh
Property
Value
Name
frmLines
Caption
The Lines Program
Name
picDrawLines
Backcolor
White color
Name
cmdDraw1
Caption
&Draw a Line
Name
cmdDraw2
Caption
&Draw Random Lines
Chapter THREE - 115
Visual Basic for Engineers & Scientists
Command Button
Name
cmdExit
Caption
&Exit
Figure 3-6. The Draw Lines Program Interface.
4. Attach code to the Interface
Declarations of variables
♦ Click on the "View Code" in the Project Window
♦ In the "Object" drop-down list select "General" and in the "Proc:" drop-down
list select “(declarations)”
♦ Type the following codes in this window
Declarations of variables
♦ Click on the "View Code" in the Project Window
Shahab D. Mohaghegh
Chapter THREE - 116
Visual Basic for Engineers & Scientists
♦ In the "Object"drop-down list select "General" and in the "Proc:" drop-down list
select “(declarations)”
♦ Type the following code in this window
Dim Counter As Integer
Draw a line that passes through given coordinates in the PictureBox control
♦ Double click on the Draw a Line Command Button
♦ Visual basic responds by opening the Code Window
♦ Write the following code in the cmdDraw1_Click () event procedure.
picDrawLines.Line (500, 200)-(4000, 1000), RGB(120, 120, 0)
Draw 100 random lines in the Picture Box control
♦ Double click on the Draw Random Lines Line Command Button
♦ Visual basic responds by opening the Code Window
Write the following code in the cmdDraw2_Click () event procedure
For counter = 1 To 100 Step 1
picDrawLines.Line -(Rnd * picDrawLines.ScaleWidth, Rnd *_
picDrawLines.ScaleHeight)
Next
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
Shahab D. Mohaghegh
Chapter THREE - 117
Visual Basic for Engineers & Scientists
will be asked if you would like to save the executable file in “Draw Lines.exe”.
Accept by clicking “O.K”.
Code Interpretation
This code is quite simple. It includes a single line for the first command button and a loop
structure for the random lines. The single line of code for drawing a line given a certain
coordinates is as follows:
picDrawLines.Line (500, 200)-(4000, 1000), RGB(120, 120, 0)
This line simply identifies the "Line" method for the "picDrawLines" Picture Box control
and passes the point (500,200) as the starting point and (4000,1000) as the end point of
the line. The RGB function specifies the red, green, and blue values for the color of the
line.
In the second part the following "For … Next" loop structure generates 100 randomly
generated lines.
picDrawLines.Line -(Rnd * picDrawLines.ScaleWidth, Rnd *_
picDrawLines.ScaleHeight)
The above line of code is very similar to the first line of code. There is one major
difference between these two lines of code. Notice that in the previous code, both starting
and ending points of the line were specified but in the latter code only one point
(randomly generated and scaled to the width and height of the PictureBox control) is
specified. This is due to the fact that the PictureBox control has two properties called
"Current X" and "Current Y". These properties return or set the horizontal (CurrentX) or
Shahab D. Mohaghegh
Chapter THREE - 118
Visual Basic for Engineers & Scientists
vertical (CurrentY) coordinates for the next printing or drawing method. So the end point
of each line becomes the starting point of the next line and you need only to provide one
point.
Try It!
1. Modify the "Draw Lines" program such that it will accept user's input for the start and
end points of the line. Then draw the line.
2. Modify the above application by checking the user input to see if it fits in the Picture
Box control. If it does not, scale it down so it would fit, before drawing it.
Graphing Functions
In this section you will learn how to graph functions and equations using the PictureBox
control and methods. The general idea is to generate an interface that has a PictureBox
control and a command button. Start by assigning scale to the PictureBox control and
then draw the axes and then put the equation you are trying to graph in a "For … Next"
loop and draw it using the "Pset" method. Following is a simple example.
The Draw Equation Program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "DrawEquation” in place of Form1 and click "O.K."
(Make sure you are in the directory that you want). Another dialog box appears with
Shahab D. Mohaghegh
Chapter THREE - 119
Visual Basic for Engineers & Scientists
Project1.vbp in the File Name window. Type "Draw Equation" in place of Project1
and click "O.K."
3. Develop the interface using the following information.
Object
Form
Picture Box
Command Button
Command Button
Property
Value
Name
frmLines
Caption
Draw Equation
Name
picEquation
Backcolor
White color
Name
cmdRun
Caption
&Calculate
Name
cmdExit
Caption
&Exit
Figure 3-7 presents the interface developed for this application. Use the table provided
and develop an interface similar to that shown in Figure 3-7.
Shahab D. Mohaghegh
Chapter THREE - 120
Visual Basic for Engineers & Scientists
Figure 3-7. The Draw Equation Program Interface.
4. Attach code to the Interface
Draw Y = 0.25 * X2 equation in the PictureBox control
♦ Double click on the Calculate Command Button
♦ Visual basic responds by opening the Code Window
♦ Write the following code in the cmdCalculate_Click () event procedure.
Dim x As Single, y As Single
picEquation.Scale (-1, 21)-(11, -1)
picEquation.Line (0, 0)-(10, 0)
picEquation.Line (0, 20)-(0, 0)
picEquation.CurrentX = 0
picEquation.CurrentY = 0
picEquation.Print "0"
picEquation.CurrentX = 10
picEquation.CurrentY = 0
picEquation.Print "10"
picEquation.CurrentX = -1
picEquation.CurrentY = 20
picEquation.Print "20"
For x = 0 To 9 Step 0.01
y = 0.25 * x ^ 2
picEquation.PSet (x, y), QBColor(2)
Next
Shahab D. Mohaghegh
Chapter THREE - 121
Visual Basic for Engineers & Scientists
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...”. The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Draw Equation.exe”.
Accept by clicking “O.K”.
Code Interpretation
The first step in using a Picture Box control is to assign a scale to it. This is done using
the "Scale" method. "Scale" method defines the coordinate system for a Picture Box.
picEquation.Scale (-1, 21)-(11, -1)
In the above code, the picture box has been divided into 12 equal segments starting from
"-1" to "11" along the x-axis (horizontally) and into 22 equal segments starting from "-1"
to "21" along the y-axis (vertically). Again remember that the top left corner is the origin.
Next we draw two straight lines that would represent the x and y-axis of the graph.
picEquation.Line (0, 0)-(10, 0)
picEquation.Line (0, 20)-(0, 0)
Now using the "Print" method the numbers 0, 10, and 20 are written on the control. Here
the CurrentX and CurrentY properties that were covered in the previous example are
used to specify the location where the text is printed.
picEquation.CurrentX = 0
picEquation.CurrentY = 0
Shahab D. Mohaghegh
Chapter THREE - 122
Visual Basic for Engineers & Scientists
picEquation.Print "0"
picEquation.CurrentX = 10
picEquation.CurrentY = 0
picEquation.Print "10"
picEquation.CurrentX = -1
picEquation.CurrentY = 20
picEquation.Print "20"
Now that the coordinate system and the axes are set, it is time to graph the function.
Following "For … Next" loop structure is written to generate the necessary points. The
body of this loop structure includes two statements. The first statement represents the
equation being graphed. This statement generates the “y” coordinates for each “x”
coordinate generated by the loop. The second statement draws a point using the “x” and
“y” coordinates.
For x = 0 To 9 Step 0.01
y = 0.25 * x ^ 2
picEquation.PSet (x, y), QBColor(2)
Next
In the above example QBColor is used instead of the RGB function. As you can see the
loop structure provides the x value in small enough increments so the points generate the
illusion of a line.
Shahab D. Mohaghegh
Chapter THREE - 123
Visual Basic for Engineers & Scientists
Try It!
1. Use the above example as guide to generate a line representing the following equation.
Select control size and x, y ranges such that a clear view of the equation is achieved.
Y = 3.5 Sin ( 2x2)
Summary
In this chapter you learned about Arrays, loops, data access and graphs in Visual Basic.
These topics are among important tools for engineers. By now you have learned to use
Visual Basic to perform elementary engineering calculations.
Keywords
Arrays
Loop structure
Repetition
Data access
File access
Plots
Graphs
Points
Lines
Equations
Shahab D. Mohaghegh
Chapter THREE - 124
Visual Basic for Engineers & Scientists
Exercises
1.
Write an application that accesses a predetermined file
on the floppy drive. Reads the file content and plots them.
2.
Identify two non-linear equations with two unknowns.
Write an application that plots the two equations and
identify the solution of the equations as the location they
meet on the plot.
Shahab D. Mohaghegh
Chapter THREE - 125
Visual Basic for Engineers & Scientists
4
Visual Basic’s Grid Control
In this chapter you will be introduced to one of the most important
custom controls that Visual Basic provides, the grid control. The use of
this control is very helpful in most of the engineering applications. The
grid control, which is similar to a spreadsheet, allows you to visualize
and manipulate data for your applications. At the end of this chapter
you will be able to handle the grid control, its properties and methods.
In this chapter array and variable declaration will be revisited and the
idea of variable and array scope will be covered.
Introduction
This chapter is entirely dedicated to the Microsoft grid control. You will see that almost
all the operations performed with the grid control somehow involve a loop structure.
Visual Basic has two types of controls. The first type is the basic controls that appear
regularly in the toolbox and the second type is the custom controls. Custom controls are
not initially a part of the toolbox. The programmer should add them when necessary.
Since grid control is a custom control first we have to add it to our project before being
able to use it. Once added it will appear in the toolbox.
Developing an Application with Grid Control
In this section of the book we start by developing a very simple application that includes
a grid control. The main objective at this point is to see how a custom control is added to
a project and how it is used. In this application we add the grid control to the project,
Shahab D. Mohaghegh
Chapter FOUR - 126
Visual Basic for Engineers & Scientists
place it on a form and talk about its basic properties. In the next application we dive a
little deeper into the grid control and use it in a more meaningful fashion.
Grid Application
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Grid Application” in place of form1 and click "O.K."
(Make sure you are in the directory that you want to be). Another dialog box appears
with Project1.vbp in the File Name window. Type " Grid Application " in place of
Project1 and click "O.K."
3. Before developing the interface we must first add the grid control to the project. Click
on the Project in the Menu bar and Select “Components” from that menu. This will
bring up the “Components dialog box”. You can bring up the “Components dialog
box” by pressing Control + T. Figure 4-1 shows the “Components dialog box”.
Figure 4-1. Component dialog box.
Shahab D. Mohaghegh
Chapter FOUR - 127
Visual Basic for Engineers & Scientists
As indicated in Figure 4-1 Visual basic provides many custom controls. We will visit
more custom controls in the future chapters of this book. At this point you should check
the box beside the “Microsoft FelxGrid Control 6.0. Once the box is checked click OK.
You will see that the FlexGrid Control is added to your project toolbox. Figure 4-2 is the
icon representing this control.
Figure 4-2. Microsoft FelxGrid Control 6.0.
Now double click on the FlexGrid Control to place it on the form. Use the resize handles
to resize the grid control until it looks like the Figure 4-3.
Figure 4-3. The grid application interface.
As you see in Figure 4-3 the FlexGrid control displays two rows and two columns by
default. Select the grid control by clicking on it. Its properties will appear in the property
widow. Make the following modifications to the Name, Cols, and Rows properties:
Shahab D. Mohaghegh
Chapter FOUR - 128
Visual Basic for Engineers & Scientists
Object
FlexGrid
Command Button
Property
Value
Name
GrdProduction
Cols
5
Rows
10
Name
cmdExit
Caption
&Exit
By default the FlexGrid will display the first row and column in gray, these are called
FixedRow and FixedCol, respectively. They are used to display the title of rows and
columns respectively. You will see that the grid control displays the number of rows and
columns indicated in the properties. Use the handles and resize the grid control to fit the
ten rows and five columns. Figure 4-4 shows what your form should look like.
Figure 4-4. Modified grid application interface.
4. Attach code to the Interface by adding the “end” statement to the “Exit” Command
Button.
Shahab D. Mohaghegh
Chapter FOUR - 129
Visual Basic for Engineers & Scientists
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...". The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Grid Application.exe”.
Accept by clicking “O.K”.
Try It!
Go back to application you just developed. In the design mode select the grid control by
clicking on it. Now use the handle and resize the control so the ten rows and five columns
would not fit in it. What happens?
Working with Grid Control
Now that we learned how to add a custom control to our project and modify its
properties, it is time to write useful programs using the grid control. It is important to
note that the content of the grid control can be set at the design time and/or be modified
in run time. We will write applications that deal with both situations.
First lets get familiar with the grid control lay out. A grid control should be treated as a
table or a matrix. It includes rows and columns. Every cell or element of the grid control
is addressed by the row and column number it occupies. In order to modify the content of
a cell, you must first identify its row and column and then place the statement that
modifies the content of the cell. In essence the elements in a grid control are much like a
two dimensional array. Following is a table that shows how the cells or elements in a grid
control are addressed.
Shahab D. Mohaghegh
Chapter FOUR - 130
Visual Basic for Engineers & Scientists
Col #1
Col #2
Col #3
Col #4
Row #1
cell (1,1)
cell (1,2)
cell (1,3)
cell (1,4)
Row #2
cell (2,1)
cell (2,2)
cell (2,3)
cell (2,4)
Row #3
cell (3,1)
cell (3,2)
cell (3,3)
cell (3,4)
Row #4
cell (4,1)
cell (4,2)
cell (4,3)
cell (4,4)
Row #5
cell (5,1)
cell (5,2)
cell (5,3)
cell (5,4)
Lets write a program that calculates the reserve a hydrocarbon reservoir. In the FixedCol
we will write the depth interval and in the FixRow the average thickness, average
porosity and the average saturation for the corresponding depth interval. The last column
will be dedicated to calculation of the average reserve for the depth interval.
For this problem the above table will look as follows:
Depth Int.
Thickness
Porosity
Saturation
Reserve
1000-1100
cell (1,1)
cell (1,2)
cell (1,3)
cell (1,4)
1100-1200
cell (2,1)
cell (2,2)
cell (2,3)
cell (2,4)
1200-1300
cell (3,1)
cell (3,2)
cell (3,3)
cell (3,4)
1300-1400
cell (4,1)
cell (4,2)
cell (4,3)
cell (4,4)
1400-1500
cell (5,1)
cell (5,2)
cell (5,3)
cell (5,4)
Now lets implement the above table in a grid control. Since we want this to appear when
the program starts, the code has to be written under the Form_Load procedure. Also note
that the FixRow and FixCol are indexed with zero. In other words FixRow and FixCol
are the zero row and column respectively.
Shahab D. Mohaghegh
Chapter FOUR - 131
Visual Basic for Engineers & Scientists
The Reserve Calculation program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Reserve” in place of form1 and click "O.K." (Make sure
you are in the directory that you want to be). Another dialog box appears with
Project1.vbp in the File Name window. Type " Reserve Program " in place of
Project1 and click "O.K."
3. Using the process covered in the previous example add the grid control to your
project. The user interface of this program is very much the same as the previous
program. Develop the interface and make the appropriate changes so it would satisfy
the requirements of this example. Figure 4-5 provides the necessary information for
the number of columns and rows that are needed for this example.
4. Attach code to the Interface by adding the “end” statement to the “Exit” Command
Button. Also use the following code in the Form_Load procedure.
' specify the column using Col property
GrdReserve.Col = 0
' specify the row using Row property
GrdReserve.Row = 0
' write in the grid using text property
GrdReserve.Text = "Depth"
' specify the next row,( as you see the column # remains the same)
GrdReserve.Row = 1
GrdReserve.Text = "1000-1100"
GrdReserve.Row = 2
GrdReserve.Text = "1100-1200"
Shahab D. Mohaghegh
Chapter FOUR - 132
Visual Basic for Engineers & Scientists
GrdReserve.Row = 3
GrdReserve.Text = "1200-1300"
GrdReserve.Row = 4
GrdReserve.Text = "1300-1400"
GrdReserve.Row = 5
GrdReserve.Text = "1400-1500"
GrdReserve.Row = 6
GrdReserve.Text = "Total"
' same procedure applied to write in rows
GrdReserve.Row = 0
GrdReserve.Col = 1
GrdReserve.Text = "Thickness"
GrdReserve.Col = 2
GrdReserve.Text = "Porosity"
GrdReserve.Col = 3
GrdReserve.Text = "Saturation"
GrdReserve.Col = 4
GrdReserve.Text = "Reserve Estimate"
Once the above code is written in the Form_Load procedure you can run the program and
check the results. The interface now should look like Figure 4-5. Note that the title of the
last column has been truncated. Therefore we need to increase the column width in order
to accommodate large titles. This can be done using the properties that allows
programmers to modify the cell dimensions in a grid control. These properties modify the
width of a cell or the height of the cell. The syntax is as follows:
Shahab D. Mohaghegh
Chapter FOUR - 133
Visual Basic for Engineers & Scientists
ColWidth ( number as Integer )
RowHeight ( number as Integer )
The number in the parentheses specifies the row or column that is to be modified.
Figure 4-5. The Reserve calculation program interface.
Following code will provide proper width and height for the cells. Add this piece of code
to the bottom of the previous code in the Form_Load procedure.
' increase the height of the cells in all rows
For i = 0 To 6 Step 1
GrdReserve.RowHeight(i) = 300
Next
' specify the width of the column using Col property
GrdReserve.Col = 0
' increase the width of the cells in Col #4 ( FixCol )
GrdReserve.ColWidth(4) = 1400
Shahab D. Mohaghegh
Chapter FOUR - 134
Visual Basic for Engineers & Scientists
Now we add a command button to the form and use it as a means to add the desired
values to the grid control and perform the appropriate calculations. After adding the
command button (which we will name cmdReserve) the interface will look as Figure 4-6.
Remember that we have altered the cell width and height too.
Figure 4-6. The Reserve calculation program interface.
Add the following code to the cmdReserve_Click procedure.
Dim h(5) As Single, p(5) As Single, s(5) As Single
Dim res(5) As Single, reserve As Single
' First Column is the thickness
GrdReserve.Col = 1
For i = 1 To 5 Step 1
GrdReserve.Row = i
GrdReserve.Text = 100
h(i) = Val(GrdReserve.Text)
Next
Shahab D. Mohaghegh
Chapter FOUR - 135
Visual Basic for Engineers & Scientists
' Let's assume that the porosity does not change with depth
GrdReserve.Col = 2
For i = 1 To 5 Step 1
GrdReserve.Row = i
GrdReserve.Text = 0.35
p(i) = Val(GrdReserve.Text)
Next
' Let's assume that saturation increases uniformly with depth
GrdReserve.Col = 3
For i = 1 To 5 Step 1
GrdReserve.Row = i
GrdReserve.Text = 0.15 + i * 0.15
s(i) = Val(GrdReserve.Text)
Next
'Finally calcualte the reserve per depth interval per square feet
GrdReserve.Col = 4
For i = 1 To 5 Step 1
GrdReserve.Row = i
res(i) = h(i) * p(i) * s(i)
GrdReserve.Text = res(i)
Next
'Calcualte total reserve
reserve = 0
For i = 1 To 5 Step 1
Shahab D. Mohaghegh
Chapter FOUR - 136
Visual Basic for Engineers & Scientists
reserve = reserve + res(i)
Next
'Print it on the grid
GrdReserve.Col = 4
GrdReserve.Row = 6
GrdReserve.Text = reserve
5. Run the program and test it to see if it works properly.
6. Generate the executable file for this Program by clicking on “File” in the menu bar
and choosing “Make EXE File...". The “Make EXE File” dialog box appears and you
will be asked if you would like to save the executable file in “Reserve
Calcualtion.exe”. Accept by clicking “O.K”.
Try It!
Try to use nested loop structure to accomplish the task in the Reserve Calculation
program.
What If?
How would the code of the Reserve Calculation program change if instead of For
… Next loop structures, Do While loop structures are used?
Shahab D. Mohaghegh
Chapter FOUR - 137
Visual Basic for Engineers & Scientists
Filling the Grid Control from a File
In the above example the value of each cell in the grid control was set individually during
the design time. In most of the engineering problems that you will encounter data is
saved in a separate file and you need to import it into your application before
manipulating it. In this section we examine a situation that you have the data in a text
file. Your goal is to import the data into the application and display it in a grid control to
examine its accuracy. Once the accuracy of the data is confirmed, the calculation will
take place. We use the previous example and enhance it in order to achieve our goal.
The Reserve Table program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Reserve” in place of form1 and click "O.K." (Make sure
you are in the directory that you want to be). Another dialog box appears with
Project1.vbp in the File Name window. Type " Reserve Table Program " in place of
Project1 and click "O.K."
3. By now you should know how to add the grid control to your projet. Add te grid
control to this project. The interface of this example is very much like the one from
the last example. There is one minor difference and that is the addition of an other
command button. Develop the interface for this example so it would look like Figure
4-7.
Shahab D. Mohaghegh
Chapter FOUR - 138
Visual Basic for Engineers & Scientists
Figure 4-7. The Reserve table program interface.
4. The code attached to the Form_Load procedure and cmdExit_Click procedure will
stay the same. We need to attach the code for the “Import Data” command button and
modify the code for the “Calculation” command Button. First step is to declare
variables. Attach the following code to the general declaration section:
'Declaring arrays to be used by all the procedures in this form.
Private h(5) As Single, p(5) As Single, s(5) As Single
Then add the following code to the Click event of the “Import Data” command button:
'Open the data file
Open "c:\temp\data.txt" For Input As 1
i=1
For i = 1 To 5 Step 1
‘Assign data to the arrays
Input #1, h(i), p(i), s(i)
Shahab D. Mohaghegh
Chapter FOUR - 139
Visual Basic for Engineers & Scientists
‘Print them in the grid control cells
GrdReserve.Row = i
GrdReserve.Col = 1
GrdReserve.Text = h(i)
GrdReserve.Col = 2
GrdReserve.Text = p(i)
GrdReserve.Col = 3
GrdReserve.Text = s(i)
Next
Close #1
Attach the following code to the Click event of the “Calculate” command button:
Dim res(5) As Single, reserve As Single
'Finally calcualte the reserve per depth interval per square feet
GrdReserve.Col = 4
For i = 1 To 5 Step 1
GrdReserve.Row = i
res(i) = h(i) * p(i) * s(i)
GrdReserve.Text = res(i)
Next
'Calcualte total reserve
reserve = 0
For i = 1 To 5 Step 1
reserve = reserve + res(i)
Shahab D. Mohaghegh
Chapter FOUR - 140
Visual Basic for Engineers & Scientists
Next
'Print it on the grid
GrdReserve.Col = 4
GrdReserve.Row = 6
GrdReserve.Text = reserve
Code Interpretation
There is couple of important issues that should be discussed at this point. First has to do
with the variable declaration. Note that we declared the arrays h(5), p(5), and s(5) using
the “Private” statement in the general declaration segment and not in a specific
procedure.
Private h(5) As Single, p(5) As Single, s(5) As Single
In Visual Basic there are three types of variable or array declaration. They are “Dim”,
“Private” and “Public”. These declaration statements differ from on another in scope. By
scope we mean the amount of code they serve. For example “Dim” only serves a
procedure or function. In other words, when a variable is declared using the “Dim”
statement in a procedure, it can not be seen or used by other procedures and functions
even in the same form.
In Visual Basic complete programs or applications are referred to as projects. Each
project consists of one or more form and/or module. Each form or module includes one or
more procedure and/or function. The scope of variable and array declaration follows the
sequence of procedure (function), form (module), and project. As shown in Figure 4-8
the “Dim” statement’s scope is limited to a procedure or a function. The scope of the
”Private” statement is the form or module, which includes many procedures and
Shahab D. Mohaghegh
Chapter FOUR - 141
Visual Basic for Engineers & Scientists
functions, and finally the scope of the “Public” statement is the entire project that
includes one or more form or module. Therefore in this project the three arrays h(5), p(5),
and s(5) are available to all the procedures in the form.
Figure 4-8. Scope of declaration statements in visual Basic.
It also should be noted that the wider the scope of a declaration statement the more
expensive (from a memory standpoint) it is. Therefore it is a good programming practice
to use the narrowest possible scope for each array or variable. In other words, if you can
get away with using the “Dim” Statement don’t use the “Private” statement and if you
can get away with using the “Private” statement do not use the “Public” statement.
The file “data.txt” which is an ASCII file and includes all the data needed for our project
resides in the “c:\temp” directory. Figure 4-9 shows the “data.txt” file in the Windows
“NotePad” editor. As it was covered in the previous sections, we first open the file using
the “Open” statement.
Open "c:\temp\data.txt" For Input As 1
Shahab D. Mohaghegh
Chapter FOUR - 142
Visual Basic for Engineers & Scientists
Figure 4-9. The “data.txt” file used in this application.
Once the file is opened, using a “For … Next” loop structure we first assign the data to
the h, p, and s arrays:
For i = 1 To 5 Step 1
Input #1, h(i), p(i), s(i)
Then using the “Row” and “Col” properties of the grid control we write the data into the
grid control. This is for visual observation of the data. Once the process is completed the
loop structure is closed and then the data file is closed.
GrdReserve.Row = i
GrdReserve.Col = 1
GrdReserve.Text = h(i)
GrdReserve.Col = 2
GrdReserve.Text = p(i)
GrdReserve.Col = 3
Shahab D. Mohaghegh
Chapter FOUR - 143
Visual Basic for Engineers & Scientists
GrdReserve.Text = s(i)
Next
Close #1
One important issue at this point is that although you can visually inspect the data, there
is not much you can do with it. Especially if there is a problem with a data point you have
no access to it in order to alter its value. This is the subject of the next section.
Next we have to perform the reserve calculations and print the result in the appropriate
cells in the grid control. We start by declaring new variables. Since these variable are
going to be used only in this procedure there was no need to declare them at the form
level.
Dim res(5) As Single, reserve As Single
The reserves are calculated using the arrays within a loop structure. They are then placed
in the appropriate cells in the grid control.
GrdReserve.Col = 4
For i = 1 To 5 Step 1
GrdReserve.Row = i
res(i) = h(i) * p(i) * s(i)
GrdReserve.Text = res(i)
reserve = reserve + res(i)
Next
GrdReserve.Col = 4
GrdReserve.Row = 6
Shahab D. Mohaghegh
Chapter FOUR - 144
Visual Basic for Engineers & Scientists
GrdReserve.Text = reserve
Manipulating Grid Control at Run-Time
So far we have learned a lot about grid control. But almost everything we have learned
has to do with working with grid control during the design time. In this section we learn
how to change the content of a cell in the grid control when the application is running.
We will use what we have developed in the previous examples.
The Table Modification program
1. Open a new Visual Basic Project by clicking on the "New Project" on the "File"
menu, and selecting Standard.EXE from the list of icons.
2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the
File Name window. Type "Modify” in place of form1 and click "O.K." (Make sure
you are in the directory that you want to be). Another dialog box appears with
Project1.vbp in the File Name window. Type " Table Modification Program " in
place of Project1 and click "O.K."
3. Add the grid control to your projet. The interface of this example is exactly similar to
the interface of one of the previous examples as shown in Figure 4-6.
4. The code written in the Form_Load, the cmdExit_Click, and the cmdReserve_Click
procedures will stay exactly the same as the previous example. The only part of the
code that is going to change is the code that has to do with the grid control. Following
code is written in the GrdReserve_KeyPress procedure. When you choose the
KeyPress event of the grid control you notice that this procedure requires a parameter
to be passed to it. This parameter is an integer and appears in the parentheses as
Shahab D. Mohaghegh
Chapter FOUR - 145
Visual Basic for Engineers & Scientists
KeyAscii. Therefore the first line of the code (which is provided by the Visual Basic
and you do not have to write it) is as follows:
Private Sub GrdReserve_KeyPress(KeyAscii As Integer)
Then add the following code to this procedure.
Dim oldrow As Integer, oldcol As Integer
' Make rows lower than 5 and in column 4 inaccessible
If GrdReserve.Col <> 4 Then
If GrdReserve.Row < 6 Then
'Accept only numbers and decimal points
If (KeyAscii < Asc(".")) Or KeyAscii > Asc("9") Then _
KeyAscii = 0
GrdReserve.Text = GrdReserve.Text & Chr$(KeyAscii)
End If
End If
Once you save your application it is ready to be run. Run the application and while it is
running click on each cell and enter a number. Once all the cells are full, then click the
“Calculate Reserves” command button and the rest of the cells will be fills with
appropriate values. As you can see this application gives the user access to the individual
cells in the grid control. This application does two more things. First it does not accept
irrelevant user input such as alphabetical values in the cells. Try typing a letter instead of
a number in the cell. You will not be able to. Second, it does not let users have access to
the cells that are reserved for calculated values. For example you will not be able to write
Shahab D. Mohaghegh
Chapter FOUR - 146
Visual Basic for Engineers & Scientists
anything in the “Reserve Estimate” column or the “Total” row. Let’s see how we
accomplished these tasks.
Code Interpretation
Since the code in the Form_Load, the cmdExit_Click, and the cmdReserve_Click
procedures are repetitions, we will not discuss them. Instead we will concentrate on the
GrdReserve_KeyPress procedure. The first line that is provided by Visual Basic:
Private Sub GrdReserve_KeyPress(KeyAscii As Integer)
Indicated that an integer (KeyAscii) must be passed to this procedure. Since this
procedure acts on users input (from the keyboard) we have to trap users keystrokes and
make sure that the user has pushed “right” keys. The “right” keys in this application
constitutes numbers 0 to 9 and the decimal point “.”. This is accomplished by the
following IF statement.
If (KeyAscii < Asc(".")) Or KeyAscii > Asc("9") Then KeyAscii = 0
In the above statement we check the user’s keystroke and let it be passed to the routine if
it is the “right” keystroke. If it is not one of the keys that we consider to be the “right”
key we instead pass the “KeyAscii = 0” which is the same as “null”. This is the reason
nothing will appear in the cell if the user pushes any key other than 0 through 9 or the
decimal point. Moreover, once one of the “right” keys is pushed, it is trapped, and
changed to an integer using the Visual Basic’s “Asc()” function. This integer is a
standard value that can be looked up in the ASCII table.
Shahab D. Mohaghegh
Chapter FOUR - 147
Visual Basic for Engineers & Scientists
The keystroke at this point satisfies the desired condition but is not in the form that can
be shown in the grid control. In order to reflect the user’s keystroke in the grid control
the integer needs to be changes back to an ASCII character (0 through 9 and the decimal
point). This is done using Visual Basic’s “Chr$()” function and then be added to the grid
control’s “Text” property. This is achieved using the following line of code.
GrdReserve.Text = GrdReserve.Text & Chr$(KeyAscii)
In order to make sure that certain rows and column is also off limit to the user for input
we use the following nested IF statements:
If GrdReserve.Col <> 4 Then
If GrdReserve.Row < 6 Then
…
End If
End If
Try It!
Now that you have learned to add values to the grid control during run-time, develop an
application that is completely empty and user has to fill all the cells including the title of
the rows and columns at run-time. The user should be able to use any keystroke for the
title row and column and only numerical keystrokes should be allowed for the rest of the
cells.
Shahab D. Mohaghegh
Chapter FOUR - 148
Visual Basic for Engineers & Scientists
Summary
This would be some summary text.
Keywords
Custom Control
Grid Control
Column
Row
Design time
Run-time
Exercises
1.
Develop an application that has two text boxes
where user can input two numbers. Use the random number
generator function in Visual Basic and generate 100 numbers
using the numbers provided by the user as the min. and max.
Display the results in a grid control.
2.
Take the application in Exercise 1 one step
further by providing a picture box control and plot the data
in the grid control in the picture box control.
3.
Use the concept in Exercise 2 and code a
polynomial in your application. Show the form of the
polynomial on the main form of your application. Use the min
Shahab D. Mohaghegh
Chapter FOUR - 149
Visual Basic for Engineers & Scientists
and max provided by the user and the random number generator
function to generate data using the polynomial function and
then plot the result.
Shahab D. Mohaghegh
Chapter FOUR - 150
Visual Basic for Engineers & Scientists
5
Functions and Procedures in Visual Basic
In this chapter you will be introduced to modular programming in
Visual Basic. The structural programming technique brakes the
program into small subprograms. These subprograms that are designed
to perform specific tasks are called functions and/or procedures. Visual
Basic has several native functions and procedures. These are
subprograms that have been provided as part of the programming
language. A classic example is the Message dialog box. Apart from the
native functions and procedures Visual Basic allows the programmer to
define her/his own functions and procedures.
Introduction
User-Defined functions and procedures are also called subprograms. Functions and
procedures perform specific tasks that are repeated within a program. They can also be
reused in other programs. These subprograms are then “called” in the main program
whenever is needed to perform that specific task. For example once you have written a
function that calculates the area of a circle, given the radius, the function can be used in
any program that calculation of the area of a circle is needed.
The advantages that subprograms (functions and procedures) provide are two folds. First
the code is written once and can be “called” as many times, as it is needed as was
mentioned in the example on the area of a circle. Second using the “divide and conquer”
metaphor, dividing the program into smaller, more manageable subprograms makes the
debugging process much easier.
Shahab D. Mohaghegh
Chapter FIVE -
160
Visual Basic for Engineers & Scientists
So far we have been using the words function and procedure as synonyms. They are
different. There is a major distinction between a function and a procedure. A function
will always return a value, while a procedure does not return a value. In this chapter we
will be dealing with both functions and procedures and through examples show you how
to implement them in your programs. Discussion of some related topics will become
necessary throughout this chapter. We will cover each related topic, as it becomes
necessary.
Functions
A Function is a separate procedure that can take arguments, perform a series of
statements, and change the values of its arguments. You can use a Function on the right
side of an expression in the same way you use any native function, such as Sqr (square
root), Cos (cosine), or Chr (character), when you want to use the value returned by the
function.
The general form of a Function is as follows:
Private Function FunctionName (parameter1 As Type, …) As Type
Statements
FunctionName= expression
[Exit Function]
Statements
FunctionName= expression
End Function
Shahab D. Mohaghegh
Chapter FIVE -
161
Visual Basic for Engineers & Scientists
The parameter1, parameter2 … are the variables (also known as arguments) passed to the
Function. Note also that it is possible not to pass any variables to a function and still
return a value. Argument1, argument2, … are usually declared as a type such as string,
integer, single, or double. A Function is called using the function name, followed by the
argument list in parentheses, in an expression.
The “Exit Function” statement causes an immediate exit from a Function procedure.
Program execution continues with the statement following the statement that called the
Function procedure. Any number of “Exit Function” statements can appear anywhere in a
Function procedure.
Note that in the Function has started with the keyword “Private”. This indicates that the
Function is accessible to the form or module it has been written in. In order to make the
Function accessible to all the forms and modules in the program it should be declared as
“Public”. The scope of a Function follows the same logic as the scope for variables as
was explained in the previous chapter.
Use the following syntax to call a Function:
FunctionName ( argument1, argument2,… )
As mentioned before a function can also be called on the right side of an expression.
Some functions have arguments passed to them. Functions use these arguments to
perform calculations. There are two different ways to pass arguments to a function. The
arguments can be passed by reference or by value. We will first provide an example to
demonstrate how functions work and then go into detail of passing arguments by
reference and by value. The examples provided in this section are based on the GayShahab D. Mohaghegh
Chapter FIVE -
162
Visual Basic for Engineers & Scientists
Lussac’s law that establishes a relation between pressure and temperature for a constantvolume process. Let’s visit this law briefly.
The Gay-Lussac’s Law
The mathematical relation that defines this law can be written as:
P1 P 2
=
T1 T 2
Or in general
P
= constant
T
It must be specified that the temperature in the perfect gas law must be expressed as
absolute temperature (degrees Kelvin or Rankin). Any temperature given in degrees
Celsius or Fahrenheit must be converted to absolute temperature before being used in the
gas-law equations. An experiment was conducted in the laboratory. The volume was kept
constant. The initial temperature was 10 oC. The temperature was increased at increments
of 10 degrees. For each temperature step the pressure was measured in atmosphere and
both temperature and pressure were recorded.
You are given a new set of temperatures and are asked to calculate the corresponding
pressure for this constant-volume process. In the first application the calculation is made
for the data as it is provided through the interface and in later application the input data is
provided through an input file. Data is provided in ASCII and has been saved in a file
named “temperature.dat”. You should use Gay_lussac’s law to calculate the new
pressure.
Shahab D. Mohaghegh
Chapter FIVE -
163
Visual Basic for Engineers & Scientists
Pressure Function Application
1. Start a new application using the Standard.EXE option in Visual Basic.
In this application the user provides the input through the interface. The calculations
are made one pressure at a time based on data provided by the user.
2. Develop the interface based on the following information and Figure 5-3. The
interface includes three frames, two command buttons and four text boxes.
Object
Property
Value
Text Box
Name
txttemp1
Text Box
Name
txttemp2
Text Box
Name
txtpress1
Text Box
Name
txtpress2
Command Button
Name
cmdcalculate
Command Button
Name
cmdExit
Figure 5-1. Interface for the Pressure Function Program.
Shahab D. Mohaghegh
Chapter FIVE -
164
Visual Basic for Engineers & Scientists
3. Attach code to the interface.
It is highly recommended to use the “Option” in the “Tools” item in the menu bar in
Visual Basic and check the “Require Variable Declaration” box. This way you are forced
to declare any variable that will be used in the program. Figure 5-4 shows the Option
dialog box. Start by declaring variables in the General Declaration area.
Option Explicit
Private press1 As Single
Private temp1 As Single, temp2 As Single
Figure 5-2. Option dialog box. Access it using the Tools item in the menu bar.
Shahab D. Mohaghegh
Chapter FIVE -
165
Visual Basic for Engineers & Scientists
Since we are planning to use a function in this program, we use the “Add Procedure” in
the “Tools” menu to add the “Calculate_Pressure” function to our program. This will add
the first and last line of the function to the code.
Figure 5-3. Add Procedure dialog box. Access it using the Tools item in the menu bar.
Add the following code to the “Calculate” command button.
Private Sub cmdcalculate_Click()
temp1 = Val(txttemp1.Text)
press1 = Val(txtpress1.Text)
temp2 = Val(txttemp2.Text)
txtpress2.Text = Calculate_Pressure(temp1, temp2, press1)
End Sub
As you can see the Text property of “txtpress2” Text Box is assigned the outcome of the
“Calculate_Pressure” function. Therefore we shall write the following code for the
“Calculate_Pressure” function.
Shahab D. Mohaghegh
Chapter FIVE -
166
Visual Basic for Engineers & Scientists
Private Function Calculate_Pressure(t1 As Single, t2 As Single, p1 As Single) As Single
Dim p2 As Single
' Transform the temperature in Kelvin degrees
t1 = t1 + 273.15
t2 = t2 + 273.15
p2 = p1 / t1 * t2
Calculate_Pressure = p2
End Function
And of course te following code is written for the “Exit” command Button.
Private Sub cmdexit_Click()
End
End Sub
4. Save the project and make a “.EXE” file using the appropriate item in the File menu.
Code Interpretation
By using the “Private” keyword we make the variables temp1, temp2 and press1
available to all the procedures and functions in the form module. The first three lines of
“cmdcalculate_Click()” procedure assigns the user inputs to the above three variables
that have been declared as single. The last line in this procedure calls the
“Calculate_Pressure” function and passes three arguments to it. These arguments are
temp1, temp2, and press1 respectively.
txtpress2.Text = Calculate_Pressure(temp1, temp2, press1)
Shahab D. Mohaghegh
Chapter FIVE -
167
Visual Basic for Engineers & Scientists
Looking at the declaration line of the “Calculate_Pressure” function, we see that the way
this function has been written it demands three arguments that are of the type single and
it returns a value for “Calculate_Pressure” that is also a single.
Private Function Calculate_Pressure(t1 As Single, t2 As Single, p1 As Single) As Single
Once inside the “Calculate_Pressure” function, the first argument will be assigned to t1,
the second to t2 and the third to p1. Please note that the sequence by which the arguments
are passed is very important. In this example after the above function declaration line the
value of t1 will be the same as the value of temp1 in the “cmdcalculate_Click()”
procedure, t2 will be the same as temp2 and p1 will be the same as press1. Job of this
Function is first to change the units of the temperature from degrees Celsius to degrees
Kelvin for both t1 and t2. Then use the Gay_lussac’s law to calculate the new pressure.
This is accomplished using the code in the function.
Passing Variables “By Reference” and “By Value”
There are two ways to pass a variable argument to a function or procedure: passing by
reference and passing by value. The default in Visual Basic is passing by reference.
When an argument variable is passed by reference, the corresponding parameter inside
the procedure will change the value of the original argument when the procedure finishes.
In other words, it is a way of passing the address (where it resides in the memory) of an
argument to a procedure instead of passing the value. This allows the procedure to access
the actual variable. As a result, the variable's actual value can be changed by the
procedure to which it is passed. Unless otherwise specified, arguments are passed by
reference. Figure 5-1 demonstrates the “ByRef” passing of the variables.
Shahab D. Mohaghegh
Chapter FIVE -
168
Visual Basic for Engineers & Scientists
Figure 5-4. Passing variables to function By Reference.
When passed by value, the argument variable retains its original value after the procedure
terminates – regardless of what was done to the parameter inside the procedure. In other
words, it is a way of passing the value of an argument to a procedure instead of passing
the address. This allows the procedure to access a copy of the variable. As a result, the
variable's actual value can't be changed by the procedure to which it is passed
Arguments to functions and procedures are always passed by reference unless they are
accompanied by the ByVal keyword in the front of the argument. It is a good
programming practice to use the keyword ByRef in front of the arguments, even if this is
not needed, in order to have a clear idea how the variables are passed. Figure 5-2
demonstrates the “ByVal” passing of the variables. Following example applications show
the use of functions in engineering applications as well as the difference between
“ByRef” and “ByVal” passing of variables. These examples are very similar to the first
example. The interface is exactly the same. As it was explained earlier, the default for
passing variables to a function is by reference. Since we did not mention how we want
the variables to be passed in the first example therefore it should be assumed that they
Shahab D. Mohaghegh
Chapter FIVE -
169
Visual Basic for Engineers & Scientists
were passed by reference. In the following example we check to see if indeed it was
passed by reference.
Figure 5-6. Passing variables to function By Value.
Pressure Function Application – Revisited (1)
1. Start a new application using the Standard.EXE option in Visual Basic.
In this application the user provides the input through the interface. The calculations
are made one pressure at a time based on data provided by the user. We will check to
see what happens to the variables after they are passed to the function.
2. Use the same interface as the previous example.
3. Attach code to the interface.
We change the code slightly to reflect the pass by reference explicitly. We also add
couple of lines to the code to show that the pass by reference is actually taking place. The
new code will look as follows:
Shahab D. Mohaghegh
Chapter FIVE -
170
Visual Basic for Engineers & Scientists
Private Sub cmdcalculate_Click()
temp1 = Val(txttemp1.Text)
press1 = Val(txtpress1.Text)
temp2 = Val(txttemp2.Text)
txtpress2.Text = Calculate_Pressure_ByRef(temp1, temp2, press1)
‘Cheking the value of variables after they are passed.
lblTemp1.Caption = "Temperature in Kelvin"
lblTemp2.Caption = "Temperature in Kelvin"
txttemp1.Text = temp1
txttemp2.Text = temp2
End Sub
Private Function Calculate_Pressure_ByRef (ByRef t1 As Single,_
ByRef t2 As Single, ByRef p1 As Single) As Single
Dim p2 As Single
' Transform the temperature in Kelvin degrees
t1 = t1 + 273.15
t2 = t2 + 273.15
p2 = p1 / t1 * t2
Calculate_Pressure_ByRef = p2
End Function
Once you run the application enter values as shown Figure 5-1. As you see in this figure
first temperature has a value of 10 degrees Celsius and the second temperature has a
value of 200 degrees Celsius. Once you click on the “Calculate” button the interface will
look like that of Figure 5-7.
Shahab D. Mohaghegh
Chapter FIVE -
171
Visual Basic for Engineers & Scientists
Figure 5-7. Program interface after the “Calculate” button has been pushed once.
4. Save the project and make a “.EXE” file using the appropriate item in the File menu.
Code Interpretation
First thing to note is that in the name of the “cmdcalculate_Click()” procedure the
function has changed to “Calculate_Pressure_ByRef” to reflect that we are making sure
that the variables are being passed by reference. As the process continues the program
enters the function at this point. Please note that all the arguments have the “ByRef”
keyword. Within the function the values of the temp1 and temp2 (now represented by t1
and t2) is being altered. They are converted to degrees Kelvin. Then the calculation is
completed and the control of the program goes back to the “cmdcalculate_Click()”
procedure. Here we have added four lines of code as follows:
lblTemp1.Caption = "Temperature in Kelvin"
lblTemp2.Caption = "Temperature in Kelvin"
txttemp1.Text = temp1
txttemp2.Text = temp2
Shahab D. Mohaghegh
Chapter FIVE -
172
Visual Basic for Engineers & Scientists
We first change the caption property of the labels lblTemp1 and lblTemp2 to get the
user’s attention about the change that have taken place. Then we display the current
values of temp1 and temp2 variables using the Text properties of the text boxes. As you
see in the Figure 5-7 these values are now changed and no longer are the same as the user
had input.
So the passing by reference had actually taken place since the value of the variables have
been altered after they have been accessed and changed in the function.
In the next example we see how the passing by value works.
Pressure Function Application – Revisited (2)
1. Start a new application using the Standard.EXE option in Visual Basic.
This application is the same as the previous application with slight changes. We will
see what happens to the variables after they are passed to the function by value
instead of by reference.
2. Use the same interface as the previous example.
3. Attach code to the interface.
We change the code slightly to reflect the pass by value of the variables. We also change
couple of lines to show that the pass by value is actually taking place. Showing only the
part of the code that has changed, the new code will look as follows:
txtpress2.Text = Calculate_Pressure_ByVal (temp1, temp2,
press1)
Shahab D. Mohaghegh
Chapter FIVE -
173
Visual Basic for Engineers & Scientists
‘Cheking the value of variables after they are passed.
lblTemp1.Caption = "Still in Celsius"
lblTemp2.Caption = " Still in Celsius "
txttemp1.Text = temp1
txttemp2.Text = temp2
The code for the function will now look like this:
Private Function Calculate_Pressure_ByVal (ByVal t1 As Single,_
ByVal t2 As Single, ByVal p1 As Single) As Single
Dim p2 As Single
' Transform the temperature in Kelvin degrees
t1 = t1 + 273.15
t2 = t2 + 273.15
p2 = p1 / t1 * t2
Calculate_Pressure_ByVal = p2
End Function
Once you run the application enter values as shown Figure 5-1. As you see in this figure
first temperature has a value of 10 degrees Celsius and the second temperature has a
value of 200 degrees Celsius. Once you click on the “Calculate” button the interface will
look like that of Figure 5-8. As you note in this Figure the values of temperature remains
the same and does not changes although the control of the program has gone to the
function and have come back to the command button.
Shahab D. Mohaghegh
Chapter FIVE -
174
Visual Basic for Engineers & Scientists
Figure 5-8. Program interface after the “Calculate” button has been pushed.
4. Save the project and make a “.EXE” file using the appropriate item in the File menu.
Code Interpretation
First thing to note is that in the name of the “cmdcalculate_Click()” procedure the
function has changed to “Calculate_Pressure_ByVal” to reflect that we are making sure
that the variables are being passed by value. As the process continues the program enters
the function at this point. Please note that all the arguments have the “ByVal” keyword.
Within the function the values of the temp1 and temp2 (now represented by t1 and t2) is
being altered. They are converted to degrees Kelvin. Then the calculation is completed
and the control of the program goes back to the “cmdcalculate_Click()” procedure. Here
we have added four lines of code as follows:
lblTemp1.Caption = " Still in Celsius "
lblTemp2.Caption = " Still in Celsius "
Shahab D. Mohaghegh
Chapter FIVE -
175
Visual Basic for Engineers & Scientists
txttemp1.Text = temp1
txttemp2.Text = temp2
We first change the caption property of the labels lblTemp1 and lblTemp2 to get the
user’s attention about the change that have taken place. Then we display the current
values of temp1 and temp2 variables using the Text properties of the text boxes. As you
see in the Figure 5-8 these values have not changed. So the passing by value had actually
taken place since the value of the variables have not been altered after they have been
accessed and changed in the function.
Working with Functions in Arrays
Functions are used very commonly with arrays. There are two important issues to keep
in mind when using arrays in functions. First is the only way to pass arrays to a functions
is by reference. Arrays can not be passed by value. Second when passing arrays to a
function you do not need to specify the arrays dimensions. All you need to do is to make
sure that you include the set of parentheses that identifies the variable as an array.
Following example uses similar logic as the previous examples but it imports the data
from a file instead of having the user to input the data. The data is displayed in a table
(grid) and then the new pressures are calculated.
Shahab D. Mohaghegh
Chapter FIVE -
176
Visual Basic for Engineers & Scientists
Try It!
Now that you have learned to add values to the grid control during run-time, develop an
application that is completely empty and user has to fill all the cells including the title of
the rows and columns at run-time. The user should be able to use any keystroke for the
title row and column and only numerical keystrokes should be allowed for the rest of the
cells.
Summary
This would be some summary text.
Keywords
Custom Control
Grid Control
Column
Row
Design time
Run-time
Exercises
1.
Develop an application that has two text boxes
where user can input two numbers. Use the random number
generator function in Visual Basic and generate 100 numbers
Shahab D. Mohaghegh
Chapter FIVE -
177
Visual Basic for Engineers & Scientists
using the numbers provided by the user as the min. and max.
Display the results in a grid control.
2.
Take the application in Exercise 1 one step
further by providing a picture box control and plot the data
in the grid control in the picture box control.
3.
Use the concept in Exercise 2 and code a
polynomial in your application. Show the form of the
polynomial on the main form of your application. Use the min
and max provided by the user and the random number generator
function to generate data using the polynomial function and
then plot the result.
Shahab D. Mohaghegh
Chapter FIVE -
178
Visual Basic for Engineers & Scientists
6
Menus and Common Dialogs in Visual Basic
In this chapter we cover menus and common dialogs in Visual Basic. We
show you how to add menu bar to your application and add menu items
and sub-items to the menu bar. Then we show you the process of
attaching code to the menu items and sub-items. Another concept that
will be covered in this chapter is the interactive file selection dialog
boxes that provide information about the file on the computer and allow
the user to select the desired file to be open or saved.
Introduction
In order to give your application the look and feel of a professional Windows program
you need to add to it some of the commonly used Windows application features. One of
the most common features used in Windows applications is a menu. Menus provide a
wealth of functionality to the application and provide access to different segments of the
application. They are usually one of the primary ways to access different features that
have been built in to the program. Menus have been used so commonly in Windows
applications that their presence in most Windows applications are intuitively expected. In
this chapter we show you how to build a menu bar for your application and how to add
items and sub-items to it. Code will then be added to the menu items and the sub-items
in order to make them functional. Figure 6-1 shows an example of a menu. This is the
menu in the Visual Basic environment.
Up to now in all the examples and applications that we developed in this text book, any
time we wanted to access a file from within the application we had to hard code its
complete path. Look at the following example from the application in Chapter 4.
Shahab D. Mohaghegh
Chapter SIX - 179
Visual Basic for Engineers & Scientists
Open "c:\temp\data.txt" For Input As 1
The file “data.txt” must exist in the “temp” directory of the “c:” drive or the application
will get a run-time error when it tries to access that file.
Figure 6-1. Example of a menu.
In this chapter we show you how to generate dialog boxes that provide a snap shot of the
user’s computer and let him/her search in the computer and find the desired file wherever
it might be located.
Menus in Visual Basic
In this section we cover the inclusion of menus in a Visual Basic application. The
following example is very simple. The main intention of presenting this example is to
Shahab D. Mohaghegh
Chapter SIX - 180
Visual Basic for Engineers & Scientists
show you how to start implementing a menu in your application. We will revisit this
example in the future and add new features to it. Therefore, this example should be
treated as a first version of a more complex application. We will call it the menu
program.
The Menu Program
1. Start a new application using the Standard.EXE option in Visual Basic.
In this application we just include a menu and will complete the application in the
examples that follow.
2. Before we show you the table that you should use to develop the interface, lets see
how we start for inclusion of a menu in an application. In order to add a menu to the
application you need to use the “Menu Editor”. There are a total of four ways that one
can invoke the “Menu Editor”. Following Figure shows all of the four ways and has
numbered them accordingly.
Shahab D. Mohaghegh
Chapter SIX - 181
Visual Basic for Engineers & Scientists
Figure 6-2. Four different ways of invoking the Menu Editor.
The first way of invoking the “Menu Editor” is to use the “Tools” item in the Visual
Basic’s menu and then select “Menu Editor”. This is indicated as number 1 in Figure 6-2.
As indicated by the number 2 in Figure 6-2, you can also use the “<Ctrl> E” to invoke
the “Menu Editor”. The third way of invoking the “Menu Editor” is to use the right
mouse button while the cursor is placed on the form. This is indicated as the number 3 in
the Figure 6-2. Last but not least is using the Visual Basic’s tool bar. Number 4 in Figure
6-2 shows the icon for the “Menu Editor”. Figure 6-3 shows the “Menu Editor”.
Figure 6-3. The “Menu Editor” dialog box.
As you can see the “Menu Editor” includes many components and options. We try to
briefly talk about the important ones that you will use. The first information that needs to
be added to the “Menu Editor” is the “Caption”. Caption allows you to enter the menu or
Shahab D. Mohaghegh
Chapter SIX - 182
Visual Basic for Engineers & Scientists
command name that you want to appear on your menu bar or in a menu. If you want to
create a separator bar in your menu, type a single hyphen (-) in the Caption box.
Name allows you to enter a control name for the menu item. A control name is an
identifier used only to access the menu item in code; it doesn't appear in a menu. Index
allows you to assign a numeric value that determines the control's position within a
control array. We discussed the control arrays in a previous chapter. They can also be
used in a menu structure. This position isn't related to the screen position.
Shortcut allows you to select a shortcut key for each command. Checked allows you to
have a check mark appear initially at the left of a menu item. It is generally used to
indicate whether a toggle option is turned on or off. Items such as HelpContextID,
NegotiatePosition, Enabled, Visible, and WindowList are not crucial issues at this point
and are not discussed at this point.
Right arrow moves the selected menu item down one level each time you click it. You
can create up to four levels of submenus. Left arrow moves the selected menu item up
one level each time you click it. Up arrow moves the selected menu item up one position
within the same menu level each time you click it. Down arrow moves the selected menu
item down one position within the same menu level each time you click it.
The bottom part of the “Menu Editor” includes a list box known as the menu list. The
menu items that are generated are displayed in this list box. Menu List is a list box that
displays a hierarchical list of menu items. Submenu items are indented to indicate their
hierarchical position or level. The Next command button moves selection to the next line.
The Insert command button inserts a line in the list box above the currently selected line.
The Delete command button deletes the currently selected line.
Shahab D. Mohaghegh
Chapter SIX - 183
Visual Basic for Engineers & Scientists
In order to create a menu item in the form, you should start by providing the item with a
name and a caption. The caption is what shows up on the form and the name is used to
refer to the item while writing the code. As you provide a caption and a name for the
menu item it will appear on the list box on the bottom portion of the dialog box. Once
you complete the first item then click on the “Next” command button. This will save all
the information you provided for that item and allows you to put the information for the
next item.
Use the following table and generate the menu items as they appear in Figure 6-4. Once
completed the interface of the program should look like Figure 6-5.
Object
Menu Title
Menu Item
Menu Item
Menu Title
Menu Item
Menu Item
Menu Item
Shahab D. Mohaghegh
Property
Value
Caption
File
Name
mnuFile
Caption
New
Name
mnuNew
Caption
Open
Name
mnuOpen
Caption
Edit
Name
mnuEdit
Caption
Copy
Name
mnuCopy
Caption
Cut
Name
mnucut
Caption
Paste
Name
mnuPaste
Chapter SIX - 184
Visual Basic for Engineers & Scientists
Figure 6-4. Menu Editor after the items were added.
Figure 6-5. Interface of the Menu program.
There are no codes to be attached at this point to this program. The goal of this example
was to show you how to invoke the “Menu Editor” and create a menu for your
Shahab D. Mohaghegh
Chapter SIX - 185
Visual Basic for Engineers & Scientists
application. In the examples that follow, we cover more issues on this subject and show
you how to enhance your program by attaching code to the menu items.
The Note Pad Program
1. Start a new application using the Standard.EXE option in Visual Basic.
In this application we develop a note pad that lets the user to change the background
color and font size using the menu items.
2. Use the following table to develop the interface shown in Figure 6-7. The “Menu
Editor” will look like that of Figure 6-6 when you are done.
Object
Form
Text
Menu Title
Menu Item
Menu Item
Menu Item
Menu Title
Shahab D. Mohaghegh
Property
Value
Caption
My Notepad
Name
frmNotepad
Name
txtNotepad
Multiline
True
Font Size
10
Caption
File
Name
mnuFile
Caption
New
Name
mnuNew
Caption
-
Name
mnuSeparator1
Caption
Exit
Name
mnuExit
Caption
BgColors
Chapter SIX - 186
Visual Basic for Engineers & Scientists
Menu Item
Menu Item
Menu Item
Menu Item
Menu Item
Menu Item
Menu Item
Name
mnuColors
Caption
Default Colors
Name
mnuDefault
Caption
-
Name
mnuSeparator2
Caption
Red
Name
mnuRed
Caption
Green
Name
muGreen
Caption
Blue
Name
mnuBlue
Caption
-
Name
mnuSeparator3
Caption
More Colors
Name
SubMenu Item
SubMenu Item
SubMenu Item
Menu Title
Menu Item
Menu Item
Shahab D. Mohaghegh
Caption
Maroon
Name
mnuMaroon
Caption
Grey
Name
mnuGrey
Caption
Light Blue
Name
mnuLightBlue
Caption
Font Size
Name
mnuFont
Caption
Normal
Name
mnuNormal
Caption
Small
Name
mnuSmall
Chapter SIX - 187
Visual Basic for Engineers & Scientists
Menu Item
Caption
Large
Name
mnuLarge
Figure 6-6. Menu Editor after adding all the items for the Note Pad program.
Shahab D. Mohaghegh
Chapter SIX - 188
Visual Basic for Engineers & Scientists
Figure 6-7. Interface for the Note Pad program.
3. Attach code to the interface.
This application does not need any variables to be declared. We can simply start by
writing code for each menu item. To write the code for each item click on the item and
the code view window for that item will appear. Note that the click event of the menu
item appears by default, which is the event we would like to code for. To start, we write
the code for the click event of the “New” menu item. This is the first item in the File
menu title.
Private Sub mnuNew_Click()
txtnotepad.Text = ""
txtnotepad.BackColor = RGB(255, 255, 255)
txtnotepad.ForeColor = RGB(0, 0, 0)
Shahab D. Mohaghegh
Chapter SIX - 189
Visual Basic for Engineers & Scientists
End Sub
Next item in the File menu title is “Exit”. You already know how to write the code for the
exit routine. The next menu title is the BgColor. The first item in this menu title is
“Default Color”. Write the following code for this menu item.
Private Sub mnuDefault_Click()
txtnotepad.BackColor = RGB(255, 255, 255)
txtnotepad.ForeColor = RGB(0, 0, 0)
mnuDefault.Enabled = False
mnuRed.Enabled = True
mnuBlue.Enabled = True
mnuGreen.Enabled = True
End Sub
Write the following code for the Red menu item.
Private Sub mnuRed_Click()
txtnotepad.BackColor = RGB(255, 0, 0)
txtnotepad.ForeColor = RGB(255, 255, 255)
mnuDefault.Enabled = True
mnuRed.Enabled = False
mnuBlue.Enabled = True
mnuGreen.Enabled = True
End Sub
Write the following code for the Green menu item.
Shahab D. Mohaghegh
Chapter SIX - 190
Visual Basic for Engineers & Scientists
Private Sub mnuGreen_Click()
txtnotepad.BackColor = RGB(0, 255, 0)
txtnotepad.ForeColor = RGB(0, 0, 0)
mnuDefault.Enabled = True
mnuRed.Enabled = True
mnuBlue.Enabled = True
mnuGreen.Enabled = False
End Sub
Write the following code for the Blue menu item.
Private Sub mnuBlue_Click()
txtnotepad.BackColor = RGB(0, 0, 255)
txtnotepad.ForeColor = RGB(255, 255, 255)
mnuDefault.Enabled = True
mnuRed.Enabled = True
mnuBlue.Enabled = False
mnuGreen.Enabled = True
End Sub
Write the following code for the Maroon submenu item.
Private Sub mnuMaroon_Click()
txtnotepad.BackColor = RGB(150, 50, 50) ' Maroon
txtnotepad.ForeColor = RGB(255, 255, 255)
mnuMaroon.Checked = True
Shahab D. Mohaghegh
Chapter SIX - 191
Visual Basic for Engineers & Scientists
mnuGrey.Checked = False
mnuLightBlue.Checked = False
mnuDefault.Enabled = True
mnuRed.Enabled = True
mnuBlue.Enabled = True
mnuGreen.Enabled = True
End Sub
Write the following code for the Gray submenu item.
Private Sub mnuGrey_Click()
txtnotepad.BackColor = RGB(100, 100, 100) ' Grey
txtnotepad.ForeColor = RGB(255, 255, 255)
mnuMaroon.Checked = False
mnuGrey.Checked = True
mnuLightBlue.Checked = False
mnuDefault.Enabled = True
mnuRed.Enabled = True
mnuBlue.Enabled = True
mnuGreen.Enabled = True
End Sub
Write the following code for the Light Blue submenu item.
Private Sub mnuLightBlue_Click()
txtnotepad.BackColor = RGB(0, 200, 250) 'Light Blue
txtnotepad.ForeColor = RGB(255, 255, 255)
Shahab D. Mohaghegh
Chapter SIX - 192
Visual Basic for Engineers & Scientists
mnuMaroon.Checked = False
mnuGrey.Checked = False
mnuLightBlue.Checked = True
mnuDefault.Enabled = True
mnuRed.Enabled = True
mnuBlue.Enabled = True
mnuGreen.Enabled = True
End Sub
Write the following code for the Normal menu item in the Font Size menu title.
Private Sub mnuFontNormal_Click()
txtnotepad.FontSize = 10
mnuFontNormal.Enabled = False
mnuFontSmall.Enabled = True
mnuFontLarge.Enabled = True
End Sub
Write the following code for the Small menu item.
Private Sub mnuFontSmall_Click()
txtnotepad.FontSize = 8
mnuFontNormal.Enabled = True
mnuFontSmall.Enabled = False
mnuFontLarge.Enabled = True
End Sub
Shahab D. Mohaghegh
Chapter SIX - 193
Visual Basic for Engineers & Scientists
Write the following code for the Large menu item.
Private Sub mnuFontLarge_Click()
txtnotepad.FontSize = 12
mnuFontNormal.Enabled = True
mnuFontSmall.Enabled = True
mnuFontLarge.Enabled = False
End Sub
4. Save the project and make a “.EXE” file using the appropriate item in the File menu.
Code Interpretation
The New menu item starts by making sure that nothing is written in the text box.
txtnotepad.Text = ""
The next action is to make sure that the background color (the BackColor property of the
text box) is white (the default color) and the font color, which is the same thing as the
ForeColor property of the text box is black.
txtnotepad.BackColor = RGB(255, 255, 255)
txtnotepad.ForeColor = RGB(0, 0, 0)
The RGB function of Visual Basic is used to assign color. This function uses three
integers between values of 0 and 255 (hence 256 color) as the values for Red, Green and
Blue respectively. Value 0 means none of that color and value 255 means 100% of that
color.
Shahab D. Mohaghegh
Chapter SIX - 194
Visual Basic for Engineers & Scientists
In the menu item Default Color, first we make sure that the default back and fore colors
are assigned as white and black respectively. Then using the Enable property of the menu
items make the Default Color item disabled, which sends the message to the user that this
item is now being used, and keeps all other options enabled. This sends the message that
any of these menu items can now be used.
txtnotepad.BackColor = RGB(255, 255, 255)
txtnotepad.ForeColor = RGB(0, 0, 0)
mnuDefault.Enabled = False
mnuRed.Enabled = True
mnuBlue.Enabled = True
mnuGreen.Enabled = True
This approach is used for all other menu items and submenu items in the BgColor menu
title. Each time the back and fore colors are changed to the proper color. Then the
enabled property of the menu item is made to be false, which by making it dimmed in the
menu list, sends the message to the user that this is the item currently activated and other
menu items are enabled by making their enable property to be true. Following codes are
used for assigning different colors.
Color
Shahab D. Mohaghegh
RGB Function Values
White
RGB(255,255,255)
Black
RGB(0,0,0)
Red
RGB(255,0,0)
Green
RGB(0,255,0)
Chapter SIX - 195
Visual Basic for Engineers & Scientists
Blue
RGB(0,0,255)
Maroon
RGB(150,50,50)
Gray
RGB(100,100,100)
Light Blue
RGB(0, 200, 250)
Table 6-1. Some colors using Visual Basic’s RGB function.
Adding More Features to the Menu
Among the common features that are usually added to the menu are access keys and
shortcuts. Adding access keys and short cuts to the menu allows the user to manipulate
the application using the keyboard rather than the mouse. Access keys make the menu
available through keyboard using the combination of the “Atl” and another key.
Shortcuts make the menu available through the function keys, the combination of “Ctrl”
and another key or “Shift” and another key.
Access keys
In order to add an access key to a menu item you should add an “&” in front of the letter
Shahab D. Mohaghegh
Chapter SIX - 196
Visual Basic for Engineers & Scientists
that should be used in combination with the “Alt” key. This is done in the “Caption” box
of the Menu Editor and will show up in the list box at the bottom of the Menu Editor.
Figures 6-8 and 6-9 show how the access keys are assigned in the Menu Editor and how
they would look in the application after they are implemented.
Figure 6-8. Menu Editor after adding the access keys.
Shortcuts
Shortcuts are added to the menu items through the Menu Editor. Unlike the access keys
that add a sign (the underline) to the appearance of the menu, shortcuts have no
indicators. Their presence should be noted to the user through manuals and help files.
There is a combo box in the Menu Editor that allows you to choose a shortcut key or
combination of keys for each menu item. Figure 6-10 shows the Menu Editor for the
same application (The Notepad Program) when shortcuts are used.
Shahab D. Mohaghegh
Chapter SIX - 197
Visual Basic for Engineers & Scientists
Figure 6-9. The application after the access keys are implemented.
Figure 6-10. Menu Editor when shortcuts are used.
Creating Pop-Up Menus
Pop-up menu refers to the block of menu that appears when user clicks on the right
mouse button. It is a convenient way of providing access to some of the most important
features of your application. In the following example we take the Notepad program and
add a pop-up menu to it.
The Note Pad Program (Revised)
1. Open the Notepad program to revise it. If you choose not to revise your old program
you can rename the new program in a separate directory and start using it. This is due
to the fact that we are going to add a new feature to this program and do not intend to
change any existing feature.
Shahab D. Mohaghegh
Chapter SIX - 198
Visual Basic for Engineers & Scientists
In this application we want to make the background color part of the menu available
through the right mouse button.
2. There is no need to change any part of the interface in this new application. Since the
background color block of the menu is what we are going to make available through
the pop-up menu, we just revisit that particular menu item in the following table.
Object
Property
Menu Title
Value
Caption
BgColors
Name
mnuColors
3. Attach the code to the interface.
In order to generate the pop-up menu we need to add the following code to the
“MouseDown” event of the Form.
Private Sub Form_MouseDown(Button As Integer, Shift As_
Integer, X As Single, Y As Single)
' Right mouse button clicked
If Button = 2 Then
PopupMenu mnuColors
End If
End Sub
Once completed, the application will look like Figure 6-11, when the right mouse button
is clicked anywhere in the form. It should be noted that in order to activate the pop-up
menu the cursor must be located on the form not on the menu or the text box. If you click
the right mouse button while the cursor is on the text box you will see that a pop-up menu
Shahab D. Mohaghegh
Chapter SIX - 199
Visual Basic for Engineers & Scientists
will be displayed that has items like copy, cut, and paste. This is part of the text box and
no code needs to be written for it.
Figure 6-11. The Notepad program revised to have a pop-up menu.
4. Save the project and make a “.EXE” file using the appropriate item in the File menu.
Code Interpretation
The only piece of code that was added to this application was to detect and trap the right
mouse button. This is done by adding an If statement with “Button=2” as its condition.
“Button=2” means the second mouse button that is the right one. Since the code is written
in the “MouseDown” event of the form object, whenever any of the mouse buttons are
pressed while the cursor is on the form this event is triggered. The If statement checks to
see which button is pressed. If it is the left mouse button nothing will happen (since we
have written the code for the right mouse button). If it is the right mouse button that is
pressed, hence Button=2, then the following statement is executed:
Shahab D. Mohaghegh
Chapter SIX - 200
Visual Basic for Engineers & Scientists
PopupMenu mnuColors
This statement invokes the “PopupMenu” method. This method displays a pop-up menu
at the current mouse location. Pop-up menu can only display one block of menu. In this
application we chose the background color block of menu items to be the pop-up menu
block. This is accomplished by identifying the “mnuColors” as the block of the menu to
be displayed.
File Access Using a Dialog Box
In Chapter four you learned how to access data that resides in a file and read it into your
application. The problem with that approach is that you have to include the name and
location of the data file into your application. Every time you plan to use that application
you have to go back to the code and change the data file name and path. This means that
you have to have Visual Basic on the computer that is using your application and the
compiled version of the application is pretty much useless.
The way most of the Windows applications work is as follows. You click on a command
button or a menu item to open a particular data file. A dialog box appears that allows you
to brows through all the disk drives in your computer and all the directories in each drive
and gives you access to all the files in each directory. You go through the search and
Shahab D. Mohaghegh
Chapter SIX - 201
Visual Basic for Engineers & Scientists
locate the data file that you are interested in and then the program opens the file for you.
This way the data file can reside at any location and could be called any names. In this
section of this chapter we show you how to develop such a dialog box.
In order to accomplish this task we make use of three new controls. They are
DriveListBox, DirectoryListBox, and FileListBox. From their names you can see that
they are List Boxes. This means that their function is to list the available drive,
directories and files, respectively. Figure 6-12 shows their icons in the toolbox.
Figure 6-12. New controls icons in the toolbox.
In this section we start by developing an application that uses these controls to give user
access to the file that needs to be opened and its content be imported into a grid control.
The Open File Dialog Program
1. Start a new application using the Standard.EXE option in Visual Basic.
In this application we give access to the user to locate the data file and then we open
the data file and import its content into a grid control.
2. There are two forms in this application. One is the main interface and the second
form is used to display the “Open File” dialog box. Use the following table and
develop the interface for the main form. Once completed the main form should look
like Figure 6-13.
Shahab D. Mohaghegh
Chapter SIX - 202
Visual Basic for Engineers & Scientists
Object
Property
Value
Caption
The Open Menu Program
Name
frmMain
Text Box
Name
Txtno_rec
Flex Grid
Name
Msfgrddata
Rows
50
Cols
6
Caption
File
Name
mnuFile
Caption
Open File
Name
mnuOpen
Caption
-
Name
mnuSeparator1
Caption
Exit
Name
mnuExit
Caption
Import Data
Name
mnuImport
Caption
Start Import
Form
Menu Title
Menu Item
Menu Item
Menu Item
Menu Title
Menu Item
Shahab D. Mohaghegh
Chapter SIX - 203
Visual Basic for Engineers & Scientists
Name
mnuStart
Figure 6-13. Interface for the Open File Dialog Program.
We now need to add a second form to this application. This form will play the role of the
Open File Dialog box. In order to add a new form to the project you need to click on the
“Project” menu item in Visual Basic. Then select the item “Add Form” from the drop
down menu. The “Add Form” dialog box will appear. Figure 6-14 shows the Visual
Basic’s Add Form dialog box.
Shahab D. Mohaghegh
Chapter SIX - 204
Visual Basic for Engineers & Scientists
Figure 16-14. The Add Form dialog box.
Once the new form has been added to the project, use the following table to develop the
Open dialog interface. Figure 6-15 shows the Open File dialog box interface.
Object
Property
Value
Caption
Open File
Name
frmOpenFile
FileListBox
Name
filFind
DriveListBox
Name
drvChange
DirListBOx
Name
dirLook
Command Button
Name
cmdOK
Caption
&OK
Form
Shahab D. Mohaghegh
Chapter SIX - 205
Visual Basic for Engineers & Scientists
Command Button
Name
cmdCancel
Caption
&Cancel
Figure 16-15. Open File dialog box interface.
3. Attach the code to the interface.
Following code is added to the frmMain form. Add the following lines to the General
Declaration procedure.
Option Explicit
Private x(50) As Single, y(50) As Single, z(50) As Single
Private i As Integer, no_rec As Integer
Add the following code to the Form_Load procedure:
Shahab D. Mohaghegh
Chapter SIX - 206
Visual Basic for Engineers & Scientists
Private Sub Form_Load()
Dim k As Integer
msfgrddata.Row = 0
msfgrddata.Col = 0
msfgrddata.Text = " No Crt "
msfgrddata.Col = 1
msfgrddata.Text = "
X"
msfgrddata.Col = 2
msfgrddata.Text = "
Y"
msfgrddata.Col = 3
msfgrddata.Text = "
Z"
msfgrddata.Col = 0
For k = 1 To 28 Step 1
msfgrddata.Row = k
msfgrddata.Text = Format(k, "
##")
Next k
End Sub
Add the following code to the click procedure of the mnuOpen menu item.
Private Sub mnuOpen_Click()
frmOpenFile.Show
End Sub
Add the following code to the click procedure of the mnuStart menu item.
Shahab D. Mohaghegh
Chapter SIX - 207
Visual Basic for Engineers & Scientists
Private Sub mnuStart_Click()
Dim counterf As Integer
i=1
Do While Not EOF(1)
Input #1, x(i), y(i), z(i)
i=i+1
Loop
Close #1
counterf = i - 1
' substract 1 because we started from i=1
txtno_rec.Text = counterf
Write_data_in_grid x(), y(), z(), counterf
End Sub
As you can see we are addressing a procedure called Write_data_in_grid. Add a
procedure to your application and name it Write_data_in_grid. Add the following code to
this procedure.
Private Sub Write_data_in_grid(ByRef a() As Single, ByRef_
b() As Single, c() As Single, ByVal rec_no As Integer)
For i = 1 To rec_no Step 1
msfgrddata.Col = 1
msfgrddata.Row = i
msfgrddata.Text = Format(a(i), "##0.#0")
msfgrddata.Col = 2
msfgrddata.Text = Format(b(i), "##0.#0")
Shahab D. Mohaghegh
Chapter SIX - 208
Visual Basic for Engineers & Scientists
msfgrddata.Col = 3
msfgrddata.Text = Format(c(i), "##0.#0")
Next
End Sub
At this point the frmMain form is completed and it is time to add code to the controls in
the frmOpenFile form.
Add this code to the Change event of the dirLook Directory List Box control.
Private Sub dirLook_Change()
' Change to the current or selected path
filFind.Path = dirLook.Path
End Sub
Add the following code to the Change event of the drvChange Drive List Box control.
Private Sub drvChange_Change()
' Change to the current or selected drive
dirLook.Path = drvChange.Drive
End Sub
Add the following code to the Click event of the cmdOK command button.
Private Sub cmdOK_Click()
Dim File As String
'Initialize an error traping ( in case you hit Esc for example)
On Error GoTo FileError
Shahab D. Mohaghegh
Chapter SIX - 209
Visual Basic for Engineers & Scientists
'Chech if the string of the selected directory
If (Right(dirLook.Path, 1) = "\") Then ' ends with "\"
'Builds the entire pathe
File = dirLook.Path + filFind.FileName
Else
'Add "\" and builds the entire path
File = dirLook.Path + "\" + filFind.FileName
End If
'Open the selected file for reading
Open File For Input As #1
FileError:
Resume Next
‘Hide the Open File Form
frmOpenFile.Hide
End Sub
Add the following code to the Click event of the cmdCancel command button.
Private Sub cmdCancel_Click()
Unload cmdCancel.Parent
'Unload the form
End Sub
4. Save the project and make a “.EXE” file using the appropriate item in the File menu.
Code Interpretation
The main form includes a handful of routines. Almost all of the code in this form should
be familiar to you since they are being repeated from previous examples in this book. In
Shahab D. Mohaghegh
Chapter SIX - 210
Visual Basic for Engineers & Scientists
the Form_Load procedure the grid control is set up and the numbers are placed on the
first column. There are two procedures in the menu. First is the “Open File” Item in the
“File” menu item.
Private Sub mnuOpen_Click()
frmOpenFile.Show
End Sub
This procedure simply invokes the form that has the open file dialog box using the
“show” method and passes the control of the program to it. We will visit the frmOpenFile
form later in this section. The second menu item “Import Data” includes the “Start
Import” item. The code in this procedure is executed after the frmOpenFile form is
closed. During the frmOpenFile form’s operation, the text file where the data resides is
identified and the file is assigned a number, in this case 1. The code refers to the file
using its number in the “Do While” loop.
Do While Not EOF(1)
Input #1, x(i), y(i), z(i)
i=i+1
Loop
Close #1
The rest of the code is a repeat of what was presented in the past, including a procedure
that writes the data into the grid control.
The code for the frmOpenFile form is short and simple. The form includes five controls.
Two command buttons, Cancel and O.K., and two list boxes and a combo box. But these
Shahab D. Mohaghegh
Chapter SIX - 211
Visual Basic for Engineers & Scientists
are not simple list and combo boxes. They are special list boxes (even the combo box is
called a list box). The first one is called the DriveListBox control. This is the one that
actually looks like a combo box. A DriveListBox control enables a user to select a valid
disk drive at run-time. This control is used to display a list of all the valid drives in a
user's system. The second list box is called the DirListBox. DirListBox control displays
directories and paths at run-time. It is used to display a hierarchical list of directories.
The third or last list box is the FileListBox. FileListBox control locates and lists files in
the directory specified by the “Path” property at run-time. It is used to display a list of
files selected by file type.
The sequences by which these list boxes are activated are the natural drive, directory and
file sequence. The idea is to generate a path that includes all these information and pass it
to the next procedure to open the file. Following code is executed if the user attempts to
change the drive. It registers the change in the path property of the DirListBox control
named “dirLook”.
Private Sub drvChange_Change()
dirLook.Path = drvChange.Drive
End Sub
The same logic works if the user attempts to change the directory. Here is the code to
detect and register that action.
Private Sub dirLook_Change()
filFind.Path = dirLook.Path
End Sub
Shahab D. Mohaghegh
Chapter SIX - 212
Visual Basic for Engineers & Scientists
The change here is registered in the path property of the FileListBox control named
“filFind”. Rest of the actions takes place in the code written for the “O.K” command
button. It starts by declaring a string variable we have chosen to call “File”. This variable
will hold the path to the file including its name.
Dim File As String
The next line of code starts an error procedure,
On Error GoTo FileError
This code is written in order to make sure that in case an error takes place (user hits the
“Esc” button or he/she is unable to find the file needed and decides to leave the form), the
program does not produce an error. As you will see later in the code this action lets the
user to gracefully leave this form and go back to the form that initiated this dialog box.
We will revisit the error trapping later in this procedure.
Next we try to make sure that the path has the correct syntax. We do that by checking to
make sure if there is a “\” (back slash) between the directory name and the file name. If
the back slash is not there we insert one. To do this, we use the “Right” function on the
“dirLook.Path” which is a string. The “Right” function, starting from the right hand side,
examines the number of characters we specify (in this case we have specified 1). In the
following code the last character (number 1 character from right) of the directory is
checked, if it detects a “\” it will simply add the file name to it. If the “\” is not there it
will inserts it. The path is then assigned to the “File” string variable.
Shahab D. Mohaghegh
Chapter SIX - 213
Visual Basic for Engineers & Scientists
If (Right(dirLook.Path, 1) = "\") Then ' ends with "\"
'Builds the entire pathe
File = dirLook.Path + filFind.FileName
Else
'Add "\" and builds the entire path
File = dirLook.Path + "\" + filFind.FileName
End If
Next we open the file using the following code and assign a number to it. In this case we
assign the number 1 to the file.
Open File For Input As #1
From here on we simply refer to the file using its assigned number which is 1. We are
finished with the code at this point. All that remains is the continnuation of the error
handling process. We had instructed the code to “GOTO” the “FileError” if an error
occurs. Here is the “FileError” section.
FileError:
Resume Next
‘Hide the Open File Form
frmOpenFile.Hide
It instructs the code to resume to the next line, which is to hide the frmOpenFile form.
What we have done in this code may be summarized as follows:
1. We have opened the file that the user has identified
2. We have assigned a number to the file that can be used throughout the program.
Shahab D. Mohaghegh
Chapter SIX - 214
Visual Basic for Engineers & Scientists
As you remember, we used the file number in the “Do While” loop to read the content of
the file.
Using the Visual Basic’s Open Dialog Control
In the previous section we showed you how to develop a form and write the appropriate
code to generate an “open File Dialog Box”. It was a good practice and revealed some
insight into the Visual Basic and its capabilities. In fact, Visual Basic provides an easier
way to accomplish the same task (and much more) use a control called the “Microsoft
Common Dialog Control”. This control is not present in the toolbox by default. You have
to add it to your project. Just like you did in Chapter 4 with the Grid control. You can add
this control to your project using the “component” item in the “project” menu of the
Visual Basic as shown in the Figure 6-16.
Figure 6-16. Adding the common dialog control to your project.
Shahab D. Mohaghegh
Chapter SIX - 215
Visual Basic for Engineers & Scientists
The CommonDialog control provides a standard set of dialog boxes for operations such
as opening and saving files, setting print options, and selecting colors and fonts. The
control also has the ability to display help by running the Windows Help engine. The
CommonDialog control provides an interface between Visual Basic and the routines in
the Microsoft Windows dynamic-link library Commdlg.dll. To create a dialog box using
this control, Commdlg.dll must be in your Microsoft Windows SYSTEM directory.
Following table shows the methods available to the CommonDialog control and their
action.
Method
Dialog Displayed
ShowOpen
Show Open Dialog Box
ShowSave
Show Save As … Dialog Box
ShowColor
Show Color Dialog Box
ShowFont
Show Font Dialog Box
ShowPrinter
Show Print or Print Option Dialog Box
ShowHelp
Invokes the Windows Help Engine
Table 6-2. Available methods for the CommonDialog control.
In this section we just use the “ShowOpen” method. You can practice with the rest of the
methods on your own.
In this section we repeat the previous example. This time we substitute the Visual Basic’s
CommonDialog control for the “Open File” dialog that we generated. Therefore we will
not repeat the entire example and concentrate only on the CommonDialog control.
Shahab D. Mohaghegh
Chapter SIX - 216
Visual Basic for Engineers & Scientists
The Open File Dialog Program (Revised)
1. Start a new application using the Standard.EXE option in Visual Basic.
2. Use the same interface as you developed for the last example. Do not add the second
form, which is the “Open File” form. Instead use the “Components” item in the
“Project” menu of the Visual Basic to add the CommonDialog control to the project.
The CommonDialog is shown in Figure 6-17.
Figure 6-17. CommonDialog control.
Add this control to the application. It does not matter where you place it. It will be
invisible during the run-time. Once you run the program it will look like Figure 6-18.
Figure 6-18. New application interface.
Shahab D. Mohaghegh
Chapter SIX - 217
Visual Basic for Engineers & Scientists
In order for the application to show the above dialog box, you need to attach code to the
interface. This will require the modification of the code in the “Open File” menu item.
3. Attach the code to the interface.
Following code is added to the Click event of the mnuOpen menu item.
Private Sub mnuOpen_Click()
'set the flags and attributes of the common dialog control
' the Filter property selects the Text files, Excel files and All files
dlgcommondialog.Filter = "Text Files (*.txt)|*.txt|" + _
"Excel Files (*.xls)|*.xls|" + _
"All Files (*.*)|*.*"
dlgcommondialog.ShowOpen
' test if any file from the text box was selected
If Len(dlgcommondialog.FileName) = 0 Then
Exit Sub:
End If
Open dlgcommondialog.FileName For Input As #1
End Sub
This completes the code for invoking the CommonDialog control. When you run the
application and use the “Open File” item in the “File” menu you will see what is shown
in Figure 6-18.
4. Save the project and make a “.EXE” file using the appropriate item in the File menu.
Shahab D. Mohaghegh
Chapter SIX - 218
Visual Basic for Engineers & Scientists
Code Interpretation
The CommonDialog control has a property called “Filter”. This property provides the
option that only certain types of files (using the file extension as identifier) be displayed
in the list box. Please note that the CommonDialog control used in the application has
been named “dlgcommondialog”.
dlgcommondialog.Filter = "Text Files (*.txt)|*.txt|" + _
"Excel Files (*.xls)|*.xls|" + "All Files (*.*)|*.*"
Above code is responsible for the part of the dialog box that is indicated with an ellipse
in Figure 6-19.
Figure 6-19. Using the Filter property with the CommonDialog control.
Using the “ShowOpen” method invokes the “Open File” diallog.
dlgcommondialog.ShowOpen
Shahab D. Mohaghegh
Chapter SIX - 219
Visual Basic for Engineers & Scientists
What remains to be done is to make sure that a file is selected and if not then the dialog is
gracefully exited without an error message. This is accomplished using the following If
… Then statement.
If Len(dlgcommondialog.FileName) = 0 Then
Exit Sub:
End If
The last line of code opens the file and assigns a number to it.
Open dlgcommondialog.FileName For Input As #1
Try It!
Use the ShowSave, ShowColor and ShowFont methods of CommonDialog
control in an application.
Summary
This would be some summary text.
Keywords
Menu
Item
Dialog Box
CommonDialog control
Shahab D. Mohaghegh
Chapter SIX - 220
Visual Basic for Engineers & Scientists
Exercises
1.
Develop an application that uses the menu items to
perform simple calculations such as addition, subtraction,
multiplication and division.
2.
Develop a Net Present Value calculator like the
one developed in Chapter 3. Make your own “open File” dialog
box to access the net cash flow from a text file.
3.
Develop an identical application as the one in
Problem #2 above. This time use the Visual Basic’s
CommonDialog control to access and open the data file.
Shahab D. Mohaghegh
Chapter SIX - 221