Anda di halaman 1dari 101

Authored by:

Jay Robert C. Fernandez, M.Sc.


Department of Computer Studies

Preface
Microsoft Visual Basic or simply VB is an incarnation of the old BASIC
language. It gives you a complete and powerful Windows application
development system in one package. VB give you a wide array of
software tools to create diverse applications like database systems,
games, and mathematical programs.
This manual is for programmers and would-be programmers who want to
learn Visual Basic. It contains a brief summary of the basic and more
important VB topics. It provides explained concepts and actual application
code that you can copy and run. It presents both the background and the
theory that a new Visual Basic programmer needs. The author though
assumes that the student already knows about basic programming
concepts such as flowcharting and algorithm formulation.
This manual was designed as a supplement to the Visual Basic classes of
Xavier University. Beginners might find this insufficient for a
comprehensive programmer's reference book. Teacher's guidance is
expected as students go through the lessons.

Acknowledgements
The author would like to thank the Commission on Higher Education
(CHEd) for funding this project.

Contact Me
I welcome any comment, suggestion, question, as well as corrections on the manual. You may contact me through:

Email jaeyf@xu.edu.ph
Phone (63-78) 858-3116 local 1006
(63-8722) 72-3116 local 1006

TABLE OF CONTENTS page


 Introduction: Basics of Visual Basic
 Lesson I: Form, Label, and Shapes
 Lesson II: Interactivity with TextBox and CommandButton
 Lesson III: Data Types, Arithmetic Operators & Precedence, and
Common Functions
 Lesson IV: Logical Structures and Operators
 Lesson V: Loop Structures
 Lesson VI: MsgBox and InputBox
 Lesson VII: Frame and OptionButton
 Lesson VIII: CheckBox
 Lesson IX: ComboBox and ListBox
 Lesson X: Horizontal and Vertical Scrollbar
 Lesson XI: DirectoryListBox, DriveListBox, and FileListBox
 Lesson XII: ImageBox and PictureBox
 Lesson XIII: Timer
 Lesson XIV: Modules, Event, Sub, and Function Procedures
 Lesson XV: Working with Multiple Forms
 Lesson XVI: Working with Menus
 Lesson XVII: Data Arrays and Control Arrays
 Lesson XVIII: Sequential File Handling
 Lesson XIX: The Printer Object

Hosted by: Xavier University Network Center (XUNet)


© 2001

2
Introduction Basics of Visual Basic

Objectives
  To recognize and understand the function of the main components of
the VB environment (Tool Bar, Toolbox, Project Window, Properties window,
Form, Code Window)
  To understand Events, Methods, and Properties

The Integrated Development Environment

It is a little known fact that you can write a VB program from scratch using nothing
more than a simple text editor, such as the Edit or Notepad applications that come
with Windows. In fact, the Visual Basic project files are exactly that - text files.
However, writing a project from scratch would involve a lot of tedious, detailed
manual entries. To simplify the task, Microsoft has built in to VB a software program
to help you write your VB projects. That software, known as the Integrated
Development Environment (IDE for short) is what comes to the screen when you
start VB and is the topic of this section.
Toolbox Form Title Bar Menu Bar Tool Bar

The Menu Bar

3
You use the Menu Bar to invoke IDE functionalities such as adding Forms to your
project. It also contains items that let you create and run your VB applications and
customize how the IDE would appear (like what windows and tools to display).
The Toolbox

The toolbox is simply a library of controls, both standard and custom. Controls are
objects that you place within Form objects such as a Label or a CommandButton.
Each type of control has its own set of properties, methods and events.

Below are the components of the Toolbox:

Pointer* PictureBox
Label TextBox
Frame CommandButton

Checkbox OptionButton
ComboBox ListBox
Horizontal Scrollbar Vertical Scrollbar

Timer DriveListBox
DirectoryListBox FileListBox
Shape Line

ImageBox Data

* Pointer is not a Control

The Project Explorer Window

This is the window you use to manage the files for any given project. The window
is usually displayed in the upper-right corner of the main working area, and it
displays all the Forms, modules, user controls, and property pages that are currently
included in the project.

The three icons in the upper-left corner of the Project Explorer window are the
View Code icon, the View Object icon, and the Toggle Folders icon. Clicking
the View Code icon displays the code in the code window for the highlighted object.
Clicking the View Object icon displays the Form associated with the object in the

4
Form window. The View Object icon is available only to those objects that have
Forms associated with them. Clicking the Toggle Folders icon changes the view of
the window. It toggles the view from a folder view to a list of all the objects in
alphabetical order regardless of their type. The following diagram shows the
different parts of the Project Explorer.

View Code View Object Toggle Folders

Form Name

Form Filename

Note: Within Visual Basic, you refer to a Form through its name. The filename
(with .frm extension) is the name you give to the file storing the Form’s
information.
The Properties
Window

VB Controls such as
CommandButtons, Labels,
PicturesBoxes and other features
of most VB applications
allow you to enter parameters
that define how these controls
work. In VB, these parameters are
called Properties.
Some properties can be entered
at design time within the IDE,
while others must be entered
with code while the program is
running.

5
The Code Window

Like what its name implies, this is where you type in the code that VB executes.
Notice that the heading of the window indicates with which event the code is
associated.

The Code Window is easily displayed by double-clicking any control on the Form or
by clicking the View Code icon.

6
A VB Session

The first step to creating an application with Visual Basic is to create the graphical
user interface. The interface is the visual part of the application with which the user
will interact. You use Forms and controls to create the interface. They are the
objects that you will work with to build your applications.

A VB Development Process typically goes through the following procedure:


1. Open a New Project
2. Add additional Forms (if needed)
3. Set the Forms’ properties
4. Place Controls on the Forms
5. Set Controls’ properties
6. Write code for Form/Control event procedures
7. Create executable (.EXE) or simply RUN program within the IDE (Debug if
there are errors)
8. Save Project

7
It is important to understand that a project (the whole application) may contain
several Forms. Information about each Form (its own properties as well as those of
the controls that are on the Form) are stored in separate files with extension .frm.
Hence, a project with multiple Forms has multiple .frm files. The project also has a
.vbp file. This file contains data about the Forms the project has, which among
these is the startup Form, etc. An .frx file may be added if your project contains
graphics that are associated to the Forms.

How does a VB application Work?

Visual Basic is an event-driven programming language. This means that a VB


program functions depending on specific events. Objects called controls are the
building blocks of a VB program. These controls have properties, methods, and
events. To fully understand these 3 concepts, consider the following example:

An electric fan is an object. It has properties such as its height, color, and shape.
Its primary function is to blow air at varying strength depending on a specified
speed. The fan only functions when the user turns it on and presses any of its
speed buttons.

The Visual Basic program is analogous to the fan. The parts of the fan e.g. its fan
blades, power button, speed controls represent VB controls. The color, height, and
shape of the fan correspond to the properties of the controls. The fan’s functions are
analogous to methods. The action of turning on the fan and pressing the speed
buttons relate to what we call events.

If we are to program the fan, we would need to create the fan first and set its
properties (you might want to have a blue 5-foot fan with 5 speeds). We will design
it to function depending on what buttons are pressed: Rotate the blade at speed 2-
rotations per second for button 1, at speed 3-rotations per second for button 2, and
so on. In this case, the fan's behavior changes from idle to working when a power-
button-press and a speed-button-press events occur. We stop rotating the blades
when the user presses the power button.

In the next lessons, we will learn more about VB’s common controls, their properties
and events.

8
Lesson I. Forms, Labels, and Shapes

Objectives
  To be able to create, execute, and save a VB project
  To interactively design a simple interface by selecting, placing and
sizing screen objects from the toolbox
  To be able to use the Pointer to select controls
  To be able to customize the Form using properties
  To use and be familiar with the Label control and its properties
  To use and be familiar with Shapes and their common properties
  To be familiar with VB events

Notes
IN FOCUS: FORMS

Forms are the windows that you see at runtime. They serve as containers of
controls such as Labels and CommandButtons. The following table lists the Form’s
properties.

Property Description
BackColor Specifies the Form’s background color. Programmer selects a color
from the Color Palette or specifies a color in Hex format.
BorderStyle Determines how the Form window appears. It also specifies whether
the user can resize the Form and determines what kind of Form you
wish to display (0: None, 1: Fixed Single, 2: Sizable, 3: Fixed Dialog,
4: Fixed ToolWindow, 5: Sizable ToolWindow)
Caption Specifies the text on the Form’s Title Bar at runtime.
Enabled Boolean. Determines whether the Form is active. A disabled Form
does not trigger an event. All controls on the Form are also
disabled.
Height Specifies the height of the Form in twips. A twip is 1,440th of an
inch)
Icon Specifies the filename of the icon graphic image that appears in the
Form’s Title Bar
Left Specifies the number of twips from the Label’s left edge to the Form
window’s left edge.
MaxButton Boolean. Specifies whether a maximize button appears on the Form.
MinButton Boolean. Specifies whether a minimize button appears on the Form.
MousePointer Determines the image of the mouse cursor when the user moves the
mouse pointer over the Form.
Moveable Boolean. Specifies whether the user can move the Form at runtime.
Picture Determines the graphic image that appears on the Form’s
background.

9
StartUpPosition Determines the state (centered or default) of the Form at application
startup.
Top Specifies the number of twips from the Label’s top edge to the Form
window’s top edge.
Visible Boolean. Determines whether the Form appears (True) or is hidden
from the user (False) at runtime.
Width Holds the width of the Form in twips.
WindowState Determines the initial state of the Form (0: Normal, 1: Minimized, 2:
Maximized)

Form’s Events
Form events are events that the Form can accept. The following are common ones:

Event Description
Load Occurs when a Form is loaded.
Unload Occurs when a Form is about to be removed from the screen.
Resize Occurs whenever a Form is resized, either by user interaction or
through code.
Activate Occurs when an object becomes the active Form. An active Form
appears in the foreground with a highlighted Title Bar.
Deactivate Occurs when a Form is no longer active.

More events are discussed in Lesson II.

IN FOCUS: LABELS

Labels hold text that appears on the Form. Labels cannot be edited directly – an
explicit code assigning a new caption to the Label should be carried out. You use a
Label, as its name obviously implies, to label a control, to provide instructions, etc.
The following table lists most common Label control properties.

Property Description
Alignment Determines whether the text appears 0: left-justified, 1: right-justified, or
2: centered within the Label’s boundaries.
AutoSize Boolean. Enlarges the Label’s size properties, when True, if you assign a
caption that is too large to fit in the current Label’s boundaries at
runtime. If False, the Label truncates the caption.
BackColor Specifies the Label’s background color. Programmer selects a color from
the Color Palette or specifies a color in Hex format.
BackStyle Determines whether the background shows through the label of if the
Label covers up it background text, graphics, and color.
BorderStyle 0: None, 1: Fixed Single. Determines whether a single-line border
appears around the Label.

10
Caption Holds the text that appears on the Label.
Enabled Boolean. Determines whether the Label is active. A disabled Label does
not trigger an even procedure.
Font Specifies the font of the text. Clicking this property will invoke a font
dialog box in which you can set the font name, style, and size.
ForeColor Specifies the color of the text. Programmer selects a color from the Color
Palette or specifies a color in Hex format.
Height Specifies the height of the Label in twips.
Left Specifies the number of twips from the Label’s left edge to the Form
window’s left edge.
MousePointe Determines the image of the mouse cursor when the user moves the
r mouse pointer over the Label.
TabIndex Specifies the order of the Label in the focus order.
TabStop Boolean. Determines whether the Label can receive the focus.
ToolTipText Holds the text that appears as a tooltip at runtime. A tooltip is a pop-up
description box that appears when the user rests the mouse pointer over
a control.
Top Specifies the number of twips from the Label’s top edge to the Form
window’s top edge.
Visible Boolean. Determines whether the Label appears (True) or is hidden from
the user (False) at runtime. Invisible Labels are only invisible at runtime.
Width Holds the width of the Label in twips.
WordWrap Determines whether the Label expands to fit its caption.

IN FOCUS: RUNNING, PAUSING, & STOPING A VB PROGRAM

You can run, pause, and stop VB applications by pressing the control buttons on the
Tool Bar or by clicking the Run menu and selecting the appropriate menu item.

Click this to run the application.

Click this to pause the application.

Click this to terminate the application. You can also click the
Close button on the Title Bar of the application.

IN FOCUS: SELECTING CONTROLS

11
The Pointer is one indispensable tool. When we move and resize control or when
we modify the properties of a control, we use the Pointer tool. How do we use the
Pointer in selecting controls?

  If you want to select a control, simply click the Pointer on the Toolbox
and click the control you would like to select.
  If you want to select multiple controls, hold down the Ctrl key and click
each control. You may also just lasso multiple controls by dragging a square
around the controls using the mouse.

IN FOCUS: SHAPE CONTROL

The Shape control provides you with basic shape objects such as Rectangles,
Squares, Ovals, and Circles. The following Form shows each of these shapes:

When you drag a Shape control to the Form, a rectangle is displayed. To change
the shape, simply change the Shape property to:

0: Rectangle
1: Square
2: Oval
3: Circle
4: Rounded Rectangle
5: Rounded Square

By default, Shapes are transparent – all you see is the outline of a white shape. If
you want the color of the Form to appear through the Shape, (the Shape shows
whatever it covers), set the BackStyle to 0: Transparent.

12
You can fill Shapes with a color by setting the FillStyle property to 0: Solid and
setting a color to the FillColor property. You may also fill the Shapes with one of
the pre-defined patterns: 2: Horizontal, 3: Vertical Line, 4: Upward Diagonal, 5:
Downward Diagonal, 6: Cross, and 7: Diagonal Cross.

You can also modify the border (or outline) of the Shapes. The BorderStyle
property determines how the Shape’s borders would look like. When set to 0:
Transparent, you do not see any border. The border can also be 1: Solid Line (the
default), 2: Dashes, 3: Dots, 4: Dash Dots, 5: Dash Dot Dots, 6: Inside Solid . The
BorderWidth determines the width of the Shape’s border. Default value is 1. The
bigger this value, the thicker the border. The Visible property determines whether
the Shape should be displayed (True) or not (False) at runtime.

Lesson in Action

13
Create a new project. When you fire up VB, a New Project dialog box appears.
Select Standard Exe, and click the Open button.
1. Customize the Form.
 Name frmMain
 Caption My First Visual Basic Application
 MinButton False
 MaxButton False
 StartUpPosition Center Screen
 Height 3135
 Width 4620
 BackColor White
2. Place a Label control on the form.
3. Customize the Label.
 Name lblBanner
 Caption Welcome to Visual Basic
 Font Arial, Regular
 Size 24
 BackColor Yellow
 ForeColor Blue
 Width 3735
 Height 1215
 Top 720
 Left 360
4
4. Run your application by clicking the button.
5. Save your work as Lesson1.vbp. Do this by clicking the File menu, then
Save Project.
6. If you want to load your project again, simply click the File menu, then
Open Project. A dialog box appears. Just select the Drive and Directory
where your project is saved.

On your Own

14
1. Create an Application displaying your name. Consider the following
specifications:
 Display the Maximize and Minimize buttons.
 Your name should be displayed in Arial font, Size 18, Bold, color Blue.
 Display a rectangle Shape control (BorderWidth=3, BorderStyle=Dots)
around the Label.
 Label should be transparent.
 Form should have a white Background color.
 Display an icon on the Title Bar (icon file will be provided by the
instructor).

Lesson II. Interactivity Using TextBoxes & CommandButtons

Objectives
  To explore Forms and the code behind an application in design mode
  To create a simple interactive application
  To use and be familiar with the TextBox & CommandButton controls
and their properties
  To use the concatenation operator (&)
  To be able to familiar with VB events and write a event-handler
subroutine
  To use the End statement
  To understand and use Remarks

Notes
IN FOCUS: TEXTBOX CONTROL

TextBoxes accepts text input such as the user’s name or address. The following
are the common TextBox properties.

Property Description
Alignment Determines whether the text appears 0: left-justified, 1: right-
justified, or 2: centered within the TextBox’s boundaries.
BackColor Specifies the TextBox’s background color. Programmer selects a
color from the Color Palette or specifies a color in Hex format.
BorderStyle 0: None, 2: Fixed Single. Determines whether a single-line border
appears around the TextBox.
Enabled Boolean. Determines whether the TextBox is active. A disabled
TextBox does not accept input.
Font Specifies the font of the text. Clicking this property will invoke a font
dialog box in which you can set the font name, style, and size.
ForeColor Specifies the color of the text. Programmer selects a color from the

15
Color Palette or specifies a color in Hex format.
Height Specifies the height of the TextBox in twips.
Left Specifies the number of twips from the TextBox’s left edge to the
Form window’s left edge.
Locked Boolean. Determines whether the user can edit the text inside the
TextBox.
MaxLength Specifies the maximum length of text that the TextBox can accept.
MousePointer Determines the image of the mouse cursor when the user moves the
mouse pointer over the TextBox.
MultiLine Boolean. Determines whether the TextBox can hold multiple lines of
text (True) or just a single line of text (False).
PasswordChar Determines the character that appears in the TextBox when the user
enters a password.
ScrollBars 0: None, 1: Horizontal, 2: Vertical, 3: Both. Determines whether
scrollbars appear on the edges of a Multiline TextBox.
TabIndex Specifies the order of the TextBox in the focus order.
TabStop Boolean. Determines whether the TextBox can receive the focus.
Text Holds the text entered in the TextBox. Specified text in this property
becomes the default value that appears in the TextBox at runtime.
ToolTipText Holds the text that appears as a tooltip at runtume.
Top Specifies the number of twips from the TextBox’s top edge to the
Form window’s top edge.
Visible Boolean. Determines whether the TextBox appears (True) or is
hidden from the user (False) at runtime. Invisible TextBoxes are only
invisible at runtime.
Width Holds the width of the TextBox in twips.

IN FOCUS: COMMANDBUTTON CONTROL

CommandButton is a control that you press to tell a VB application to perform a


particular task. A button labeled “Compute” may tell the VB to computer for the
sum of two numbers and display the result on a Label. Below are the common
properties of a CommandButton.

Property Description
BackColor Specifies the CommandButton’s background color. Programmer
selects a color from the Color Palette or specifies a color in Hex
format. Applicable only when Style property is set to 1: Graphical.
Cancel Determines whether the CommandButton gets a click event if the
user presses Esc.
Caption Holds the text that appears on the CommandButton.
Default Determines if the CommandButton responds to an Enter keypress

16
even if another has the focus.
Enabled Boolean. Determines whether the CommandButton is active. A
disabled CommandButton is grayed out and cannot be pressed.
Font Specifies the font of the CommandButton caption. Clicking this
property will invoke a font dialog box in which you can set the font
name, style, and size.
Height Specifies the height of the CommandButton in twips.
Left Specifies the number of twips from the CommandButtons’s left
edge to the Form window’s left edge.
MousePointer Determines the image of the mouse cursor when the user moves
the mouse pointer over the CommandButton.
Picture Holds the name of an icon graphic image that appears on the
CommandButton as long as the Style property is set to 1-
Graphical.
Style Determines whether the CommandButton appears as a standard
Windows button (0: Standard) or a CommandButton with a color
and possible picture (1: Graphical)
TabIndex Specifies the order of the CommandButton in the focus order.
TabStop Boolean. Determines whether the CommandButton can receive
the focus.
ToolTipText Holds the text that appears as a tooltip at runtime.
Top Specifies the number of twips from the CommandButton’s top edge
to the Form window’s top edge.
Visible Boolean. Determines whether the CommandButton appears (True)
or is hidden from the user (False) at runtime. Invisible
CommandButtons are only invisible at runtime.
Width Holds the width of the CommandButton in twips.

IN FOCUS: EVENTS

Events, as discussed in the introduction, are the primary elements of a user and VB
interaction. Your application opens a dialog box when the user selects the Open
menu or outputs the square of two numbers when the user clicks on a button.
Selecting the menu and clicking the button are examples of events.

Events can be keyboard- or mouse-triggered. With the mouse, you can use the
MouseDown, MouseUp, and MouseMove events to enable your applications to
respond to both the location and the state of the mouse.

Event Description

MouseDown Occurs when the user presses any mouse button.

17
MouseUp Occurs when the user releases any mouse button.

MouseMove Occurs each time the mouse pointer is moved to a new


point on the screen.

Click Occurs when the user clicks the selection mouse button
(may be the right or left button).

DblCLick Occurs when the user double clicks the selection mouse
button (may be the right or left button).

Keyboard clicks and key presses also provide means of data input and basic window and menu navigation. The
following are the events you can trigger using the keyboard:

Event Description

KeyPress Occurs when the user presses any keyboard key.

KeyUp Occurs when a pressed key returns to its normal or up


state.

KeyDown Occurs when a key is in its down state (when the user
presses the any key).

How do a KeyPress and KeyDown or a MouseDown and a Click differ from each
other? KeyPress and MouseDown are keyboard/mouse state related. They occur at
that instant when the mouse button is clicked down and a key is pressed down.
This means the events occur before the mouse button or key is released back to its
normal state. Click and KeyPress occur after the user has clicked the mouse or
pressed a key.

How do we create event-handlers then? When we double click the


CommandButton, a Code Window appears like the one below.

18
Visual Basic automatically creates an Event Procedure for you in the format:

Private Sub cmdSum_Click()

End Sub

An Event Procedure is simply a block of statement executed when an event (in


this case, a Click) of a particular control is triggered. cmdSum is the name of the
control that we clicked. The Click() event is the default event of a button – VB
assumes that you want to do something like calculating the sum of two numbers
when the user clicks on this button at runtime. If this is indeed what you want, you
write VB code within the procedure. The ListBox on the right contains all the Events
supported by cmdSum, a CommandButton control. It supports, aside from Click(),
MouseUp(), LostFocus(), and many others. The TextBox also supports events. You
might want to execute a procedure when the user enters something in the TextBox
(a KeyPress() event), or when it the user edits the text property at runtime
(Change() event).

IN FOCUS: THE END STATEMENT

The End statement ends an application immediately. No code after the End
statement is executed. The program will also not respond to further events. To end
the program, simply execute the statement End as in the following example:

Private Sub cmdQuit_Click( )


End
End Sub

IN FOCUS: REMARKS

Remarks are notes that you write in your code. These notes are commonly used to
help clarify some code, explain codes to readers, state the programmer’s name and
the date the program was written, and describe the purpose of the program. Since
remarks are intended for people, they are completely ignored by VB.

19
VB supports two kinds of remarks:
  Remarks that begin with the Rem statement
e.g.
Rem Programmer: Jay R.C. Fernandez
Rem Computer Center
Rem 17 May 2001
Rem This program computes for the average of 3 numbers.

  Remarks that begin with the apostrophe


e.g.
x=x+1
‘ This statement increments the value of x by 1.
y = “Computer”
‘ This statement assigns the string “Computer” to variable y

Lesson in Action

The application that will ask for the user’s first and last name and outputs “Hello
<firstname> <lastname>!” in a label. The visual representation of the program is
as follows:

1. Create a new project.


2. For the Form control, set the following properties:
 Name frmMain
 Caption An Interactive VB Application
 MaxButton False
 StartUpPosition Center Screen
 Height 4410

20
 Width 6195
 BackColor White

3. Drag 3 Labels to the Form:


Set the following properties for the first Label:
 Name lblFName
 BackStyle Transparent
 Caption First Name
 Font Arial, Size 14, Regular
 Top 600
 Left 360
 Width 1575
 Height 495
Set the following properties for the second Label:
 Name lblLName
 BackStyle Transparent
 Caption Last Name
 Font Arial, Size 14, Regular
 Top 1200
 Left 360
 Width 1575
 Height 495
Set the following properties for the third Label:
 Name lblOutput
 BackColor Light Blue
 Caption None. Erase Default Value
 Font Arial, Size 14, Italic
 Width 5295
 Height 975
 Top 1800
 Left 360

4. Drag 2 TextBox controls to the Form.


Set the following properties for the first TextBox:
 Name txtFName
 Font Arial, Size 14, Regular
 Text None. Erase Default Value
 Width 3495
 Height 495
 Top 480
 Left 2160
Set the following properties for the second TextBox:
 Name txtLName
 Font Arial, Size 14, Regular

21
 Text None. Erase Default Value
 Width 3495
 Height 495
 Top 1080
 Left 2160

5. Drag 2 CommandButton controls to the Form.


Set the following properties for the first CommandButton:
 Name cmdGreet
 Caption Greet
 Width 1695
 Height 495
 Top 3120
 Left 2160
Set the following properties for the second CommandButton:
 Name cmdQuit
 Caption Quit
 Width 1695
 Height 495
 Top 3120
 Left 3960

6. Enter the following procedures.

Private Sub cmdGreet_Click()


lblOutput.Caption = "Hello " & txtFName.Text & " " & txtLName.Text & "!"
End Sub

Private Sub cmdQuit_Click()


End
End Sub

7. Run the application and see how your new application works.
8. Save your work as Lesson2.vbp.

On your Own

1. Create an application with the following specifications:


Add two CommandButtons and one Label between them in one line. Make
the Label’s Caption property blank. When the user clicks the first

22
CommandButton, a caption should appear on the Label that reads “Left
Button Clicked!”. When the user clicks the second CommandButton, a
caption should appear on the Label that reads “Right Button Clicked!”.
2. Create an application with five CommandButtons
aligned vertically. Reverse the focus order so that when you run the
application and press the Tab key several times, the focus order flows
upward through the CommandButtons.

Lesson III. Data Types, Arithmetic Operators & Precedence, and


Common Functions

Objectives
 To determine what data types VB supports; how to declare variables, and
how to assign data to variables
 To able to use Arithmetic Operators
 To use and understand the Val( ), Str( ), and isNumeric Functions
 To apply the rule of arithmetic operator precedence
 To able to write subroutines that solve mathematical problems

Notes

Programming involves data and ways of manipulating these data. Thus, you should
learn how to represent data in the computer.

IN FOCUS: VARIABLES, TYPES, DECLARATION, AND SCOPE

You often need to store values temporarily when performing calculations with Visual
Basic. In VB, you can store values in containers called variables. Generally,
variables have a name (a string you use to refer to the variable when you want to
fetch or store value in the variable) and a data type (which determines the range of
values the variable can store and the operations defined for that type).

Data types control the internal storage of data in Visual Basic. How do we
associate a type to a variable? VB does this automatically. By default, Visual Basic
uses the Variant data type. But programmers can always associate variables to a
type explicitly.

The following table enumerates the common VB data types:

Data Type Description and Range


Boolean Data that is either True or False

23
Byte Positive numeric values without decimals that range from 0 to
255
Double Numeric values that range from
–1.79769313486232E+308 to 1.79769313486232E+308*
Integer Numeric values with no decimal point or fraction that range
from –32,768 to 32,767
Long Integer values with a range beyond that of Integer data
values. It ranges from
–2,147,483,648 to –2,147,483,647
String Data that consists of 0 to 65,400 characters of alphanumeric
(letters and numbers) and special characters (punctuations,
etc.).
Variant Data of any data type and used for control and other values
for which the data type is unknown.
*The value of 1.2E+6 is computed by multiplying 1.2 by 6 raise to 10. This
is equal to 1.2 times 1,000,000 = 1,200,000.

Variable Declaration
Data have different sizes, thus a variable that would contain a String value should
have enough space to accommodate strings. Variable declaration specifies how
much space VB should allocate for a variable.

How do we declare variables? You use the Dim statement through the following
syntax:

Dim <var_name> As <data_type>

The following are examples:

Dim strName As String


Dim A As Boolean, B As Integer

Scoping Variables
A variable is scoped as either a procedure-level (local) or module-level variable.
This depends on how it is declared.

Scope Private Public


Procedure- Variables are private to the Not applicable. You
level procedure in which they appear. cannot declare public

24
Declaration: Declare variables variables within a
within a procedure. For Example: procedure.
Private Sub cmdSum_Click( )
Private x As Integer

End Sub

Note: Variables declared within a


procedure are by default private –
the variables can only be accessed
within the procedure’s scope.

Module-level Variables are private to the module Variables are available to


in which they appear. all modules.

Declaration: You create module- Declaration: You create


level private variables by declaring module-level public
them with the Private keyword in variables by declaring
the Declarations section at the top them with the Public
of the module. keyword in the
Declarations section at
the top of the module.

Note: You can declare 2 different variables with the same name but these variables
must be declared in different scopes. For example, you could have a public variable
named Temp and then, within a procedure, declare a local variable named Temp. If
we refer to variable Temp within the procedure, we would access the local variable.
References to Temp outside the procedure would access the public variable.

IN FOCUS: ASSIGNMENT OPERATOR

We use the assignment operator = to assign data to a variable. Assigning data to a


variable is simply storing a value to the variable. The syntax is as follows:

<var_name> = <expression>

<var_name> is a variable name (which you might have declared using the Dim
statement). <expression> can be a literal, another variable, a mathematical
expression, or a function call. Take the following examples:

‘Assigning a literal to a variable


age = 18
stude_name = “Jay Fernandez”

25
‘Assigning the value of a variable to another variable
grade = score

‘Assigning the result of a mathematical expression


grade = score1 + score2

Always bear in mind that the left and right hand side values of the assignment
operator should be of the same data type or at least of compatible type. You
cannot assign a String value to a Double variable.

IN FOCUS: MATH OPERATORS

You use math operators when you want to manipulate data. If you want to get the
average of 2 numbers, you will probably use the formula (x + y)/2. The following
table describes VB’s primary math operators.

Operator Example Description


+ Score1 + Score2 Adds two values

- Price – Discount Subtracts the second value from the first


* Price * Discount Multiplies two values
/ Total / 2 Divides the first value by the second
value
\ Total \ 2 Divides the first value by the second
value but returns only the whole number
(e.g. 5\2 returns 2). Expressions with
this operator are called integer divisions.
Mod 5 Mod 2 Divides the first value by the second
value but returns only the remainder
whole number (e.g. 5 mod 2 returns 1).
Expressions with this operator are called
modulus divisions.
^ 2^2 Raises the first value to the second value
- -2 Negates a value. This operator is called
unary minus.
You can combine several mathematical expressions in one expression as in the
example:

grade = (score1 + score2 + score3) / 3

IN FOCUS: OPERATOR PRECEDENCE

26
Another matter that you should take note of is operator precedence. Precedence is
the order of computation. ^ is evaluated first, then * and /, then + and -. If there
are * and / in an expression, execution is done from left to right. This holds true to
+ and -. Let us demonstrate this in the following examples:

The expression 2 + 3 * 4 is equal to 14. This was computed by doing the


multiplication first before addition (since multiplication has higher precedence over
addition).

The expression 4 * 3 / 2 is equal to 6. We evaluate this expression from left to


right, which is by doing the multiplication first before division.

You can override the operator precedence by using parentheses. VB always


evaluates expressions enclosed in parentheses before anything else in the
expression. Consider the following expression:

4 * (2 + 3)

This is equal to 20, computed by adding 2 and 3 and multiplying the sum by 4.
Without the parentheses, the value of the entire expression is 11 (multiplying 4 with
2 and adding 3 to the product).

IN FOCUS: VAL(), STR(), AND ISNUMERIC FUNCTIONS

The Val(), Str(), IsNumeric Functions are useful for data conversion: from
numbers to Strings and from Strings to numbers. Val() converts Strings to numbers.
Str() complements Val() – it converts numbers to Strings. IsNumeric() returns True
if a String argument can represent a number.

Val() is useful when you want to convert e.g. the Text property of a TextBox to a
number. This is applicable in cases when you require the user to enter a number in
the TextBox (e.g. the user’s age). The Text property of TextBoxes and the Caption
property of Labels are Strings in type, thus conversion must be done if you need
their number value. You use IsNumeric() in cases when you need to verify if
whether a particular value can be represented as a number. For example, if you
require the user’s age, and the user enters letters, you might want to notify the user
of wrong input.

The following are examples of how we use the 3 functions.

strNumber = “122”
intNumber = Val(strNumber) ‘intNumber is assigned the numeric value 122
strNum = Str(intNumber) ‘strNum is assigned the string “122”

27
intAge = Val(txtAge.Text) ‘intAge is assigned the numeric value of
txtAge.Text
y = IsNumeric(intNumber) ‘y receives True

Lesson in Action

The application asks for the 2 numbers and outputs “The average of the 2 numbers
is <average>”.

1. Create a new project.


2. For the Form control, set the following properties:
 Name frmMain
 Caption Arithmetic Application
 MaxButton False
 StartUpPosition Center Screen
 Height 3945
 Width 5445
 BackColor White

3. Drag 3 Labels to the Form.


Set the following Properties for the first Label:
 Name lblNum1
 BackStyle Transparent
 Caption First Number
 Font Arial, Size 14, Regular
 Top 360
 Left 240
 Width 2175
 Height 495
Set the following properties for the second Label:
 Name lblLNum2
 BackStyle Transparent
 Caption Second Number

28
 Font Arial, Size 14, Regular
 Top 960
 Left 240
 Width 2175
 Height 495
Set the following properties for the third Label:
 Name lblResult
 BackColor Light Blue
 Caption None. Erase Default Value
 Font Arial, Size 14, Italic
 Width 4815
 Height 975
 Top 1560
 Left 240

4. Drag 2 TextBox controls to the Form.


Set the Following Properties for the first TextBox:
 Name txtNum1
 Font Arial, Size 14, Regular
 Text None. Erase Default Value
 Width 615
 Height 495
 Top 240
 Left 2520
Set the following properties for the Second TextBox:
 Name txtNum2
 Font Arial, Size 14, Regular
 Text None. Erase Default Value
 Width 615
 Height 495
 Top 840
 Left 2520

5. Drag 2 CommandButton controls to the Form.


Set the following properties for the first CommandButton:
 Name cmdAverage
 Caption Average
 Width 1695
 Height 495
 Top 2760
 Left 1440
Set the following properties for the second CommandButton:
 Name cmdQuit
 Caption Quit
 Width 1695

29
 Height 495
 Top 2760
 Left 3360
6. Write the following procedures:

Private Sub cmdAverage_Click()


ave = (Val(txtNum1.Text) + Val(txtNum2.Text)) / 2
lblResult.Caption = "Average of the 2 numbers is: " & Str(ave)
End Sub

Private Sub cmdQuit_Click()


End
End Sub

7. Run your application.


8. Save your work as Lesson3.vbp.

On your Own

1. Write a code that declares these variables: your first name, your last name,
your age, your course, and whether you are old or new student.
_______________________________________________________________
_______________________________________________________________
_______________________________________________________________

2. Write an application that accepts your age in a TextBox and then displays,
when you click a CommandButton, your age in 10 years time.
3. Make an application that asks for an item price, the discount (if any), and the
cash given by the customer. Compute and output the selling price and the
change (cash – selling price). Refer to the Form below.

30
Lesson IV. Logical Structures

Objectives
  To able to write simple decision-making statements
  To be able to use the If-Then and If-Then-Else selection structures to
choose between alternative actions
  To use Logical Operators
  To use the Format() function

Notes

Logical structures allow nesting in the program flow. You might want to do a
particular routine if a certain condition is true, and do another routine if it isn’t. For
example, if you want to check if a student has passed a subject, what do you do?
You check if his grade is greater than or equal to the passing grade. You say
“Passed” if this is true. Otherwise, you say “Failed”.

There are a couple of logical structures in VB. What we will discuss in this lesson
are: If, If-Else, and the Select-Case statements. But before going into these, let
us discuss Comparison and Logical Operators first.

IN FOCUS: COMPARISON AND LOGICAL OPERATORS

Comparison operators compare data values against each other and produce True or
False results. Put simply, we evaluate a comparison expression as True or False.
The expression 1>2 is false because 1 is not greater than 2. The following table
describes the comparison operators provided for by Visual Basic.

Operator Usage Description


> Salary > 10,000 Returns true of if the value on the left
hand side is greater than the value on
the right hand side.
< Age < 18 Returns true of if the value on the left
hand side is less than the value on the
right hand side.
= Gender = Returns true of if the values on the left
“Female” and right hand sides are equal to each
other.
>= Grade >= 60 Returns true of if the value on the left
hand side is greater than or equal to

31
the value on the right hand side.
<= Total <= Quota Returns true of if the value on the left
hand side is less than or equal to the
value on the right hand side.
<> Course <> “CS” Returns true of if the values on the left
and right hand sides are unequal.

Note that expressions on both sides of a comparison operator should conform to the
same data type or at least compatible types. You cannot compare String and
numeric values, as this will cause a type mismatch error.

VB also supports three additional operators – And, Or, and Not. These are called
Logical Operators. Logical operators allow you to combine two or more
comparison tests into a single compound comparison expression.
The next table describes the logical operators.

Operator Usage Description


And (A>B) And (C<D) Returns true if both expressions are
true.
Or (A>B) Or (C<D) Returns true if at least one expression is
true.
Not Not (A>B) Returns true if the expression (A>B) is
false. It returns false if the expression
is true.

Comparisons are evaluated from left to right unless explicitly indicated by


parentheses. Consider the following expressions:

Expression 1. (1>3) Or (2=2) And (3<=2) « False Or True And


False
Expression 2. (1>3) Or ((2=2) And (3<=2)) « False Or (True And
False)

The expression 1 returns False while expression 2 returns True. Expression 1 is


evaluated from left to right, evaluating the Or expression first then the And. In
expression 2, the And expression is evaluated first because it is enclosed in
parentheses.

IN FOCUS: IF STATEMENT

32
The If statement has the following syntax:

If <comparisonExpression> Then
One or more VB statements
End If

T
Comp VB Statement/s
Exp
F

Flowchart of If-Then structure

The statements enclosed in the If statement are executed only if


<comparisonExpression> is true. In the following example, the allowance is
increased by 50 only if the grade is greater than 90.

If (Grade>90) Then
allowance = allowance + 50
End If

IN FOCUS: IF-ELSE STATEMENT

If-Else statement is an extension of the If statement. While nesting in an If


statement is “this way or nowhere”, If-Else is “this way or that way”. The syntax is
as follows:

If <comparisonExpression> Then
One or more VB statements
T
Else CompE VB Statement/s
One or more VB statements xp
F
End If
VB Statement/s

Flowchart of If-Then-Else structure

As in the If statement, if <comparisonExpression> is true, the statement


block proceeding Then is executed. The If-Else statement executes the statements
after the Else keyword if this is false. The following is an example:

If (grade>=60) Then
lblOutput.Caption = “You passed!”

33
Else
lblOutput.Caption = “Sorry but you failed.”
End If

IN FOCUS: SELECT CASE STATEMENT

If we are comparing an expression to several expressions, the If-Else statement may


not be efficient. Consider this example: display “Excellent” if the grade falls within
the range 86-100, “Outstanding” for grades 71-85, “Good” for grades 50-70, and
“Failed” for grades below 50. This can be done through If-Else statement:
If (grade>=86) Then
lblOutput.Caption = “Excellent”
Else
If (grade>=71) Then
lblOutput.Caption = “Outstanding”
Else
If (grade>=50) Then
LblOutput.Caption = “Good”
Else
LblOutoput.Caption = “Failed”
End If
End If
End If

The above code works but the coding is extremely difficult to follow.

Visual Basic supports another logical statement called Select Case. The syntax is
as follows:

Select Case <expression>


Case <value>:
One or More VB statements
Case <value>:
One or More VB statements

Case <value>:
One or More VB statements
Case Else
One or More VB statements
End Select

<expression> can be any VB expression – such as a calculation, a string value, or a


numeric value – provided that it results in an integer or a string value. Each
<value> must be compatible with <expression>, that is, if <expression> results in
an integer, then all <value>s must be integers as well. VB compares <expression>

34

CompExp N
F 1
2 T
Flowchart of Select-Case
VB Statement/s
structure VB Statement/s
to each <value>. If it finds a match, it executes the statements that immediately
follow it. It then ignores the rest of the Case statements. In the event when no
matches have been found, then the statements following the Case Else are
executed.

The Case clause has several variations. Case <value> works when you are
comparing <expression> to several specific values (e.g. Case 6, Case “Computer”).
If you want to compare it to a range of values, you use either:

Case Is <relation>: e.g. Case Is <5:


or
Case <expression1> To <expression2>: e.g. Case 40 To 60:

The following code is the translation of the If-Else code to Select-Case. It is now
shorter and more readable.
Select Case grade
Case 50 To 70: lblOutput.Caption = “Good”
Case 71 To 85: lblOutput.Caption = “Outstanding”
Case 86 To 100: lblOutput.Caption = “Excellent”

35
Case Else: lblOutput.Caption = “Failed”
End Select

IN FOCUS: FORMAT FUNCTION

The Format() function enables you to format how data are displayed. If variable
total_cost contains the total amount of a product, you might want to display the
value of this variable in currency format (in 2 decimal places with a currency sign).

Format() does not change a value, it only changes the way a value looks. This
function returns a variant. The following is Format()’s syntax:

Format(<expression>, <strFormat>)

<expression> can be any variable, expression, or a constant. <strFormat> may be


a value in the following table:

strFormat Description

“Currency” A dollar sign appears before the formatted value. The


value has a comma thousands separator and 2 decimal
places. Negative values are automatically enclosed in
parentheses.

“Fixed” Displays at least one digit before and two digits following
the decimal point, with no thousands separator.

“General Displays the number with no thousands separator.


Number”

“Percent” Displays the number, multiplied by 100, and adds


appends percent sign to the right of the number.

You can also create your own strFormat. You’ll just need a combination of pound
sign and zeros to format values. Each pound sign indicates where a significant digit
goes. The zero indicates that you want either leading or trailing zeros, whether the
zero or significant or not.

Examples:
A = 123.3232
B = 23.0002
C = 12233
D = .34

36
Format Expression Result
Format(A, ”Currency”) $ 123.32
Format(D, ”Percent”) 34%
Format(B, “Fixed”) 23.00
Format(D, “###”) Nothing
Format(D, “##.###”) .34
Format(D,”0.000”) 0.340
Format(C,”#,###.00”) 12,233.00
Format(C,”#,###.##”) 12,233.
Format(C, “P #,##0.00”) P 12, 233.00

Lesson in Action

We will create an application that asks for two grades and outputs their average. It
will then display “Passed” if the average is greater than or equal to 60 or “Failed” if
the average grade is less than 60.

1. Create a new project.


2. For the Form control, set the following properties:
 Name frmMain
 Caption Grading Program
 BorderStyle 1 – Fixed Single
 StartUpPosition Center Screen

37
 Height 5145
 Width 5325
 BackColor White

3. Drag 2 Labels to the Form:


Set the following properties for the first Label:
 Name lblMGrade
 BackStyle Transparent
 Caption Enter your Midterm Grade:
 Font Arial, Size 16
 Top 240
 Left 240
Set the following properties for the second Label:
 Name lblFGrade
 BackStyle Transparent
 Caption Enter your Final Grade:
 Font Arial, Size 16
 Top 960
 Left 240

4. Drag 2 TextBoxes to the Form.


Set the following Properties for the first TextBox:
 Name txtMGrade
 Font Arial, Size 14
 Text (None. Erase Default Value)
 Width 615
 Height 495
 Top 240
 Left 4200
 MaxLength 3
Set the following properties for the second TextBox:
 Name txtFGrade
 Font Arial, Size 14
 Text (None. Erase Default Value)
 Width 615
 Height 495
 Top 960
 Left 4200
 MaxLength 3

5. Drag a Shape to the Form.


Set the following properties for the Shape:
 Name shpRect
 Width 4695

38
 Height 1575
 Top 1920
 Left 240

6. Drag 2 Labels to the Form.


Set the following properties for the first Label:
 Name lblAve
 Font Arial, Size 14
 Caption Average:
 Width 2175
 Height 375
 BackColor Light Yellow
 Top 2160
 Left 840

Set the following properties for the second Label:


 Name lblRema
 Font Arial, Size 14
 Caption Remark:
 Width 2175
 Height 375
 BackColor Light Yellow
 Top 2760
 Left 840
7. Drag additional 2 Labels to the Form.
Set the following properties for Label 1:
 Name lblAverage
 Caption None. Erase Default Value
 Width 1215
 Height 375
 Top 2160
 Left 3120
 Backcolor Lightyellow
Set the following properties for Label 2:
 Name lblRemark
 Caption None. Erase Default Value
 Width 1215
 Height 375
 Top 2760
 Left 3120
 Backcolor Lightyellow

8. Drag a CommandButton to the Form.


Set the following properties for the CommandButton.

39
 Name cmdCompute
 Caption COMPUTE
 Width 1455
 Height 495
 Top 3960
 Left 1800

9. Double Click on the Command Button. Enter the following code to your
cmdCompute_Click procedure.

Private Sub cmdCompute_Click()


a = (Val(txtMGrade.Text) + Val(txtFGrade.Text)) / 2
lblAverage.Caption = Format(a, "##0")

If (a >= 60) Then


lblRemark.Caption = "Passed"
Else
lblRemark.Caption = "Failed"
End If
End Sub

10. Run the application and see how your new application works.
11. Save your work as Lesson4.vbp.

On your Own

1. Rewrite the following nested If statement using a single If with a logical


operator:
If (level >= 2) Then
If (course = ”BSCS”) Then
lblResult.Caption = “Qualified Member”
End If
End If

2. How do comparison operators differ from mathematical operators?

3. What role does the ASCII table play in comparison logic?

4. What happens if every Case fails and there is no Case Else option?

5. Rewrite the following If statement to eliminate the Not. The logic should
still be the same.
If Not(A < 4) Or Not(college = ”Engineering”) Then

40
6. Write a program that contains a TextBox and a CommandButton. Put a
Label above the TextBox that tells the user to type a number from 1 to 10
inside the TextBox. Display a default value of 0. When the user clicks the
CommandButton, check the TextBox for a valid number. Display “Valid
Number” in another Label if the number is within the range. Display “Invalid
Number. Please enter a number from 1 to 10” when the entered value is out of
range.

Lesson V. Loop Structures

Objectives
  To be able to use the Do-While-Loop, Do-Until-Loop, and For-Next
repetition structures
  To understand and implement counter-controlled repetition and
sentinel-controlled repetition
  To understand the concept of nested control structures

Notes
Loop Structures are statements that execute instructions repeatedly. A common
practical application is when you need to compute 3^6. This expression is
evaluated by multiplying itself 6 times.

VB provides several Loop Structures. They are classified as Sentinel-controlled


Structures and Counter-controlled Structures. Sentinel-controlled Loop Structures
iterate routines until a special value called sentinel value contains a certain value to
indicate. For example, we iterate until variable done has the value True. Variable
done in this case is our sentinel. Counter-controlled repetition requires a counter
variable (or sometimes called a loop counter). The counter variable is incremented
(or decremented) every iteration. Loop terminates when the counter value reaches
a particular value.

IN FOCUS: DO-WHILE LOOP STRUCTURE

Syntax:
Do While (<comparison_test>)
One or more VB Statements
Loop
T
CompE Loop Body
xp

F
41
Flowchart of Do-While loop structure
The statements enclosed by Do-While and Loop, called the loop body, are executed
repeatedly while <comparison_test>, a boolean expression, is True.
<comparison_test> is evaluated the first time the loop begins. Thus, if
<comparison_test> is initially False, the loop body will never execute. One of the
statements in the loop body should somehow set the <comparison test> to False to
terminate the loop. If it remains True, VB will perpetually execute the statements.
This is called infinite loop and often causes the computer to appear to have hung.

IN FOCUS: DO-UNTIL LOOP STRUCTURE

Syntax:
Do Until (<comparison_test>)
One or more VB Statements
Loop
F
CompE Loop Body
xp

Flowchart of Do-Until loop structure

Do-Until loop works exactly like the Do-While loop except that the Do-Until loop
continues executing the loop body until the comparison is True. Just like Do-While,
Do-Until evaluates <comparison_test> first to determine if the loop body should be
executed.

IN FOCUS: DO-LOOP-UNTIL LOOP STRUCTURE

Syntax:
Do
One or more VB Statements
Loop Until (<comparison_test>)

42
Loop Body

F
CompE
xp

Flowchart of Do-Loop-Until loop structure

This structure works exactly like the preceding two loop structures. Unlike the first
two, the loop body is executed first before evaluating <comparison_test>. If
<comparison_test> is true, VB repeats the loop body. Otherwise, VB exits the loop
and executes the statement following the loop code. Do-Loop-Until executes the
loop body at least once.
IN FOCUS: FOR LOOP STRUCTURE

Syntax:
For <counter_var> = <start_val> To <end_val> Step <increment_val>
One or more VB statements
Next <counter_var>

CounterVar=StartVal Increment CounterVar

T
CounterVar<
Loop Body
= EndVal
43
F
Flowchart of For loop structure

The For-Loop also iterates a block of statements. Unlike the other loop structures
that we have discussed, For-Loop iterates for a specified number of times. The
number of iterations is determined by <start_val> and <end_val>, both Integers.
Initially, <counter_var>, an Integer variable, receives the value of <start_val>.
<counter_var> is incremented by the value of <increment_val> every iteration. By
default, <increment_val> is equal to 1. In this case, the loop terminates when
<counter_var> is greater than <end_val>. Thus, if <start_val> is equal to 1 and
<end_val> is equal to 5, then there would be 5 iterations. <counter_var> will have
the value 1 in the first iteration, 2 in the second iteration, and 5 in the last iteration.
The Step clause is optional (Step 1 by default). If you assign a negative value to
<increment_val>, Visual Basic counts down. The Next clause tells the For-Loop to
add <increment_val> to <counter_var> and checks if it has not gone beyond
<end_val>. The <counter_var>s after For and Next should be the same variable.

Take the following examples:


For x = 2 To 7
Loop Body
Next x

The loop body is iterated 6 times. Value of x is incremented by one every iteration
(x=2 in the first iteration, x=3 in the second iteration, .. , x=7 in the last iteration).

For x = 2 To 7 Step 2
Loop Body
Next x
The loop body is iterated 3 times. Value of x is incremented by two every iteration
(x=2 in the first iteration, x=4 in the second iteration, and x=6 in the last iteration).
At the end of the third iteration, Next x assigns the value 8 to x. Since it is greater
than 7, the <end_val>, the loop terminates.

For x = 9 To 1 Step -3
Loop Body
Next x

44
The loop body is iterated 3 times. Value of x is decremented by three every
iteration (x=9 in the first iteration, x=6 in the second iteration, and x=3 in the last
iteration). At the end of the third iteration, Next x assigns the value 0 to x. Since it
is less than 1, the <end_val>, the loop terminates.

The following Do-While and For-Loop structures are the same:

For x = 1 To 8 Step 2 x= 1
Loop Body Do While (x<=9)
Next x Loop Body
x=x+2
Loop

For-Loop is a perfect structure for programs that requires a specific number of


iterations (instead of a condition which is met at no specific time) or for a program
that needs to access a sequence of values.

Lesson in Action

Let’s create an application that asks for an integer and outputs the summation of
that number. E.g. the summation of 5 is 15 (1+2+3+4+5).

Private Sub cmdSum_Click()


If (Val(txtNum.Text) > 0) Then
intSum = 0
For x = 1 To Val(txtNum.Text)
intSum = intSum + x
Next x
lblResult.Caption = "Summation of " & txtNum.Text & " is " & Str(intSum)
& "."
Else
lblResult.Caption = "Enter a positive integer only."
End If

45
End Sub

The If statement makes sure that before we compute for the summation, the
number entered should be a positive number (otherwise, our program will bear an
incorrect result). intSum = intSum + x is done Val(txtNum.Text) times. If the user
entered 3, then we will be executing this statement thrice. On the first iteration,
intSum is assigned the value 1. On the second iteration, the value of x (which is 2
at the moment) is added to intSum, eventually assigning the value 3 to intSum.
Finally, the next value of x (which is 3) is added to intSum giving it the value 6.
Since Next x increments x to 4, and 4 is greater than 3 (our <end_val>), we
terminate the loop and display the value of intSum, the summation of 3.

On your Own

1. Modify the summation procedure in Lesson in Action and use Do-Until loop
instead.

2. How many times does the following loop iterates?


intX = 20
Do While (intX >= 1)
intX = intX + 1
Loop

3. Create a program that asks for a number and computes for its Factorial. The
Factorial of 3 is 6 (1 x 2 x 3). Factorial of 5 is 120 (1 x 2 x 3 x 4 x 5). You
may use the same Form and change the caption of the button from
“Summation” to “Factorial”. Also, make sure that the user enters a number
using the IsNumeric() Function. Display appropriate messages in the Label if
the user enters non-numeric values.

Lesson VI. MsgBox() and InputBox()

Objectives
  To be able to use the MsgBox Function
  To be able to use the InputBox Function

46
Notes
You use Message and Input Boxes when you need to ask the user questions or
display error messages and advise the user.

Input Box
Message Box Input Box

IN FOCUS: MESSAGE BOX

The format of the Message Box function is as follows:

<intVariable> = MsgBox(<str_message>, <int_type>, <str_title>)

<intVariable> is an Integer variable that receives the return value of the function.
If you do not need to determine which button the user clicked (for example, when
there is only one button), you may use the function by executing:

MsgBox<str_message>, <int_type>, <str_title>

<str_message> is a String literal or a String variable that contains the message to


be displayed in the Message Box. <int_type> is an optional numeric value or
expression the describes the options you want in the Message Box. This value is the
sum of the values of the options (see the tables below) you want to invoke. For
example, if you want to display the Yes and No buttons, vbQuestion icon, and set
the No button as the default button, then the value of <int_type> is 292 (4 + 32 +
256). You may also use their corresponding named literal as in vbYesNo +
vbQuestion + vbDefaultButton2. <str_title> is a String literal or variable that
contains the text that appears in the Title Bar of the Message Box.

Named Literal Value Description


vbOkOnly 0 Displays the OK button.
vbOkCancel 1 Displays the OK and Cancel buttons.
vbAbortRetryIgnore 2 Displays the Abort, Retry, and Ignore
buttons

47
vbYesNoCancel 3 Displays the Yes, No, and Cancel
buttons.
vbYesNo 4 Displays the Yes and No buttons.
vbRetryCancel 5 Displays the Retry and Cancel
buttons.
The Buttons displayed in a Message Box

Named Literal Value Description


vbCritical 16 Displays the Critical Message Icon.
vbQuestion 32 Displays the Warning Query Icon.
VbExclamation 48 Displays Warning Message Icon.
vbInformation 64 Displays Information Message Icon.
The Icons displayed in a Message Box

Named Literal Value Description


vbDefaultButton1 0 The first button is the default.
vbDefaultButton2 256 The second button is the default.
VbDefaultButton3 512 The third button is the default.
The Default Buttons displayed in a Message Box

If your Message Box has more than 1 button, you determine which button is
pressed by checking the value of <intVariable>. The return values are enumerated
in the following table.

Named Constant Value Description


vbOk 1 The user clicked the Ok button.
vbCancel 2 The user clicked the Cancel button.
vbAbort 3 The user clicked the Abort button.
vbRetry 4 The user clicked the Retry button.
vbIgnore 5 The user clicked the Ignore button.
vbYes 6 The user clicked the Yes button.
vbNo 7 The user clicked the No button.
MsgBox()’s Return Values

The sample Message Box on the previous page was created through:
MsgBox "You must enter A, B, or C.", vbCritical, "Error"

IN FOCUS: INPUT BOX

Input Box is very similar to a Message Box but instead of the 7 return values that
indicate which button was pressed, the Input Box returns a string data value
entered by the user.

48
The following is the format of Input Box function:

<strVariable> = InputBox (<str_prompt>, <str_title>, <str_default>, <intXPos>,


<intYPos>)

<str_prompt> works like <str_message> value in Message Box. It is the text that
appears in the Input Box. It is usually an instruction on what the user should enter
in the TextBox provided for in the Input Box. <str_title> is what appears in the
Title Bar. <str_default> is the default String in the TextBox. <intXPos> and
<intYpos> determine the position of the Input Box relative to the Form. They hold
the number of twips from the top and left edge of the Form window to the top and
left edge of the Input Box, respectively. <str_title>, <str_default>, <intXPos>,
<intYpos> are optional parameters.

Input Boxes always containt Ok and Cancel buttons. If the user presses the Ok
button, the function returns the String entered in the TextBox. If the user presses
the Cancel button, a null String (“”) is returned.

Examples:

MsgBox("This is a MessageBox", vbRetryCancel + vbInformation, "Sample")

MsgBox("This is another MessageBox", vbAbortRetryIgnore + vbDefaultButton2 +


vbExclamation, "Sample 2")

InputBox("This is an Input Box", "Sample", "test")

49
Lesson in Action

The following application uses both Input and Message Boxes. When the
application is executed (therefore, place your code in the Form_Load procedure),
an Input Box will ask for a number from 1 to 10. A Message Box is displayed
when the user enters a number not in the range. When a valid entry is received,
simply display that value in a Label on the Form.

The following are screen shots of the Input and Message Boxes.

Write the
following
procedure:

Private Sub Form_Load()


num = InputBox("Enter a number from 1 to 10.", "Input", "")
If ((num < 1) Or (num > 10)) Then
MsgBox "Please enter a number from 1 to 10 only!", vbCritical, "Invalid
Entry"
Else
lblOutput.Caption = "You entered number " & num & "."
End If
End Sub

Save your work as Lesson6.vbp.

On your Own

1. Write an application that asks for your age through an InputBox() and then
displays your age 5 years ago through a MsgBox(). Display a default value
of 10 in the InputBox. Note: if the age entered is <=5, output “You were
not yet born 5 years ago”. The InputBox should automatically appear
during program startup.

50
2. Create a program with one CommandButton and one Label. When the
user presses the button, a MsgBox appears with 3 buttons: Yes, No,
Cancel. Display which button was clicked in the Label.

Lesson VII. Frames and OptionButtons

Objectives
  To use the Frame and OptionButton controls
  To show how Frames work with OptionButtons

Notes

OptionButtons give users an array of choices. By clicking an OptionButton, the


user selects or deselects an OptionButton. It has a black dot inside when it is
selected.

OptionButtons are sometimes called radio buttons. The user can only select one
button among a set of buttons. Buttons are grouped in sets with the use of another
Visual Basic control called Frame. A Frame is a rectangular region that holds other
controls and groups these into a single set. When one button is selected in a set of
option buttons, the rest are automatically deselected by Visual Basic. Thus,
OptionButtons are useful in cases like when you want the user to select a gender
(either male or female; one can never be both male and female).

OptionButtons have similar properties with that of a Label. The text that you see
beside the OptionButton is its caption property; hence, you don’t have to place a
Label to identify it.

Warning: When option buttons are not placed in Frames, Visual Basic assumes that
the option buttons are independent of each other. Thus, the user can select
any of them at the same time (in our example above, the user can be both
male and female).

Option Button Frame

How do you know if an OptionButton is selected? Each OptionButton has a Value


property that contains either True or False. When the value of this property is
True, the button is currently selected. Otherwise, it is deselected.

51
Lesson in Action

optBlue

optRed

Create the above Form and write the following procedures:

Private Sub optBlue_Click()


lblColor.Caption = "BLUE"
lblColor.BackColor = vbBlue
End Sub

Private Sub optRed_Click()


lblColor.Caption = "RED"
lblColor.BackColor = vbRed
End Sub

What the above procedures do is to format the Label based on which OptionButton
is selected. If the user selects Blue, VB changes the background color of the Label to
blue (through the BackColor property) and sets its caption property to “Blue”.

vbRed and vbBlue are color named literals. Since hex color formats are difficult to
remember, VB provides you with these values that represent hex values of
commonly used colors. The other colors aside from vbBlue and vbRed are as
follows:

Literal Color
vbBlack Black
VbGreen Green
VbYellow Yellow
VbMagenta Magent
a
VbCyan Cyan
VbWHite White

52
Save your work as Lesson7.vbp.

On your Own

Instructions: Create a short math drill. The drill contains 3 items. When the
user presses a button labeled Check Score, a Message Box appears revealing the
his score (e.g. You correctly answered 2 items!). The following is how the Form
should look like.

Lesson VIII. Checkbox

Objectives
  To be able to use and be familiar with the Checkbox and its properties
  To be familiar with the different Checkbox styles

Notes

CheckBoxes work just like the OptionButton, with two differences: a selected
CheckBox shows the selection with a checkmark and are never mutually exclusive.
Therefore, the user can select one or more CheckBoxes even if those boxes reside in
the same Frame or on the same Form.

53
Examples of Checkboxes

How do I know if a CheckBox has been checked? A CheckBox has a value


property that may be 0, 1, or 2. When the value of this property is 0, the
CheckBox is currently unchecked. If the value is 1, the CheckBox is checked. The
CheckBox is disabled if this value is equal to 2.

CheckBoxes may also look like CommandButtons (only that a checked graphical
CheckBox appears in a pressed state). Just set the Style property to 1: Graphical
(the examples above are CheckBoxes of Style set to 0: Standard, which is the
default). The following Form illustrates the various CheckBox property options
available.

Lesson in Action
The application below demonstrates the use of CheckBoxes. The application
counts how many items have been checked and displays the number when the user
presses the “Ok” button.

54
Private Sub cmdOk_Click()
Cnt = 0
If chkMath.Value = 1 Then
Cnt = Cnt + 1
End If
If chkScience.Value = 1 Then
Cnt = Cnt + 1
End If
If chkLiterature.Value = 1 Then
Cnt = Cnt + 1
End If
If chkHistory.Value = 1 Then
Cnt = Cnt + 1
End If
lblOutput.Caption = "You have checked " & Str(Cnt) & " subject(s)."
End Sub

Save your work as Lesson8.vbp.

55
On your Own

1. 1. Create a program that computes for the price of a


pizza based on the following:
Thin Crust P 60.00
Thick Crust P 95.00

Add-ons:
Extra Cheese P 8.00
Extra Ham P10.00
Extra Onions P 5.00

Dine Out additional P 20.00

The total cost should reflect in a Label. Your application should look like the
following Form:

2. Make a program that formats the Label’s display using 3 CheckBoxes. The
CheckBoxes are: Bold, Italic, and Underlined. If the user checks Bold, then
the Label’s caption is made bold. Refer to the Form below.

Lesson IX. ListBox and


ComboBox

56
Objectives
  To create selection lists at design time using ListBox and ComboBox
  To be able to differentiate ListBox from a ComboBox
  To be able to add/remove an item from a ListBox or ComboBox at
runtime.

Notes

IN FOCUS: LISTBOX

ListBox gives the user a choice of several values. The user selects an option
instead of typing a value into a Textbox. The ListBox ensures that the user always
chooses one of the available options.

Types of ListBoxes: (Left) Standard ListBox; (Right) CheckBox ListBox

As in the figure above, the ListBox displays scrollbars if it is not tall enough or wide
enough to display all its data. The contents of the ListBox may be set at design time
or at runtime.

The following are the significant properties of a ListBox.

Property Description
BackColor Specifies the ListBox’s background color
Columns Determines the number of columns. If 0, the ListBox scrolls
vertically in a single column. If 1 or more, the ListBox items
appear in the number of columns specified (one or more
columns) and a horizontal scrollbar appears so you can see all
the items in the list.
IntegralHeight Boolean. Determines whether the ListBox can display partial
items, such as the upper half of an item that falls toward the

57
bottom of the ListBox. True (default): Does not display partial
items
List Holds the items in your ListBox.
MultiSelect The state of the ListBox’s selection rules. If 0-None (the
default), the user can select only one item by clicking with the
mouse or by pressing the spacebar over an item. If 1-Simple,
the user can select more than 1 item by clicking with the
mouse or by pressing the spacebar over items in the list. If 2-
Extended, the user can select multiple items using Shift-click
and Shift-arrow to extend the selection from a previously
selected item to the current one. Control-click either selects or
deselects an item from the list.
Sorted Determines whether the ListBox values are automatically
sorted. If False (the default value), the values appear in the
same order in which the program added the items to the list.
Style Determines whether the list box appears in its usual list format
or, as in the figure in the previous page, with the Checkbox
before the items.

The following are the methods supported by ListBoxes. These methods help the
user initialize, add items to, and remove items from a ListBox.

Method Description
AddItem Adds a single item to the ListBox
Clear Removes all items from the ListBox
List A string array that holds items from within the ListBox.
ListCount The total number of ListBox items.
RemoveItem Removes a single item from the ListBox.

How do I add an item to a ListBox?


There are two ways. One is by entering items in the List property of a ListBox.
The other way is by executing the statement:

ListCourses.AddItem “Computer Science”

where ListCourses is the name of the ListBox and “Computer Science” is the item
to be added.

How do I remove an item to a ListBox?


Each item in a ListBox is associated with a subscript or index. The first item has
a subscript 0, while the nth has subscript n-1. Execute the following to remove
the first item.

58
ListCourses.RemoveItem(0)

How do I remove all items in a ListBox?


Just execute the statement:

ListCourses.Clear

How do I know how many items are there in a ListBox?


The expression ListCourses.ListCount returns the total number of items in the
ListBox named ListCourses.

How do I know if an item is selected or not?


Use the Selected method. If you want to know if the first item is selected, the
expression ListCourses.Selected(0) returns True if item 0 is selected; otherwise,
it returns False.

IN FOCUS: COMBOBOX

ComboBoxes work much like ListBoxes except that these may allow the user to
add items to a ComboBox at runtime through a built-in TextBox. VB has three kinds
of ComboBoxes. All the properties of a ListBox apply to a ComboBox.

Here are the three kinds of ComboBoxes:

Kind Description
Drop-down Displays only one item unless the user clicks the ‚ button to
ComboBox display additional items (a scrollbar appears if there are more
items than what the ComboBox can display). The user can
also enter values at the top of the ComboBox in the same way
you do in a TextBox.
Simple Looks like a ListBox attached to a TextBox. Items are
ComboBox displayed as if they were in a ListBox. You may also enter
values on top of the ComboBox.
Drop-down Do not allow you to enter values, so it is similar to a ListBox.
ListBox It looks like a Drop-down ComboBox.

Use the Style property to switch from one kind of ComboBox to another. The Form
below displays the three kinds.

59
Lesson in Action
Let us make an application that formats the font style of a Label. A ListBox will
provide a list of available font names.

The application will look like this:

The ListBox contains the following font names: Arial, Century Gothic, Times New
Roman, and Tahoma. You may add several others.

Now when we select a font from the ones in the ListBox, the Label should
automatically be formatted. Thus, the main event will be a click on the ListBox.

The code is a short one. We just need to assign the Text property of the currently
selected ListBox item to the FontName property of the Label.

Private Sub lstFonts_Click()


lblBanner.FontName = lstFonts.Text
End Sub

60
On your Own

Instructions: Make a program that computes for a pizza’s price based on the size
and toppings selected.
Size:
Small P 40.00
Medium P 75.00
Family P 100.00
Large P 140.00
Extra Toppings:
Cheese P 5.00
Ham P 15.00
Onions P 8.00
Pepper P 10.00
Base your program design on the following Form.

Save your work as Lesson9.vbp.

Lesson X. Horizontal and Vertical Scrollbars

Objectives
  To be able to use Horizontal and Vertical Scrollbar controls to select
from ranges of values.
  To be able to use Scrollbars to manipulate other controls.

Notes

Scrollbars let users control value changes. Rather than type specific values, the user
can move the scrollbar with the mouse to specify relative positions within a range of
values. There are two types of scrollbars: Horizontal and Vertical Scrollbars.
Except for their orientation, they share exactly the same properties.

61
Example of a Horizontal Scrollbar (Left) and a Vertical Scrollbar (Right)

The following are the fundamental properties of a scrollbar.

Property Description
LargeChange Specifies the amount that the scrollbar’s Value property
changes when the user clicks within the scrollbar’s shaft
area.
Max Indicates the maximum number of units that the scrollbar
value represents at its highest setting. The range is from
1 to 32,767 (the default Max value)
Min Indicates the minimum number of units the scrollbar value
represents at its lowest setting. The range is from 1 (the
default Min value) to 32,767.
SmallChange Specifies the amount that the scrollbar’s Value property
changes when the user clicks an arrow at either end of
the scrollbar.
Value Contains the units of measurement currently represented
by the position of the scrollbar.

When you place a scrollbar on a Form, set the range of values the scrollbar is to
represent. Set the Min and Max property to the lowest and highest value the
scrollbar will represent, respectively. When the user eventually clicks any arrow in
the scrollbar, the Value of the scrollbar will change (positive SmallChange when the
right or up arrow is clicked; negative SmallChange when the left or down arrow is
clicked).

Lesson in Action

Let’s use the ScrollBar in a simple application. In the Form below, the ScrollBar
will be used to manipulate the font size of the Label. The main task is simply to
associate the Value property of the scrollbar to the FontSize property of the Label.
Thus, changing the ScrollBar’s Value will subsequently change the FontSize of the
Label.

62
1. Create the Form displayed above.
2. Drag a Label control to the Form and set the following properties:
 Name lblBanner
 Caption Visual Basic
 FontSize 8
 FontStyle Arial
 BackColor Yellow

3. Drag a HScrollBar to the Form and set the following properties:


 Name hsbFSize
 Min 8
 Max 35
 Value 8
The Max value also determines the maximum font size of the label. Tip:
Assign the maximum font size of the caption that can fit within the Label to
the Value property of the HScrollBar. The initial value of the Value
property should match the initial FontSize of the Label’s caption.

4. Write the following procedure:

Private Sub hsbFSize_Change()


LblBanner.FontSize = hsbFSize.Value
End Sub
5. Run your application.
6. Save your work as Lesson10.vbp.

On your Own

1. Create a program that manipulates the position of the Label in the Form
using Vertical and Horizontal Scrollbars. Note: Make sure that the Label does not
go beyond the rectangular Shape control.

63
2. Modify the program you have made in the Lesson in Action section.
Display the current font size in a Label.

Lesson XI. FileListBox, DirectoryListBox, and DriveListBox

Objectives
  To use FileListBox, DirectoryListBox, and DriveListBox
  To understand how these 3 controls interact in a simple application

Notes
A FileListBox is a list of files in a specified directory. A DirListBox displays the
directory structure of a specified drive. DriveListBoxes lists the drive structure of
the user’s computer.

These three controls are initially independent of each other in the Form. Thus, it is
your job to tie them up together. What you can probably do is to update the
contents the FileListBox whenever the user selects a new folder in the DirListBox.
You can also update the directory structure of this DirListBox whenever the user
selects a new drive in the DriveListBox. The primary event of these controls is
Change() — when the user selects a new item in these ListBoxes.

64
The following are the properties of a FileListBox:

Property Description
Archive Boolean. Specifies whether or not archive attributes
are displayed. Default is True.
Hidden Boolean. Specifies whether or not hidden attributes
are displayed. Default is False.
MultiSelect Integer. Specifies whether or not the user can make
multiple selections
Path String. Specifies the current path.
Pattern String. Specifies the files displayed in the FileListBox
ReadOnly Boolean. Specifies whether or not read-only attributes
are displayed. Default is True.
System Boolean. Specifies whether or not system attributes are
displayed. Default is True.

The most important method of a DriveListBox is Drive. The drive method returns
the current drive (in the form C: or D:) of the DriveListBox. Using DirectoryListBox,
the Path method gives you the path to the current folder or directory (e.g.
C:\myfiles\computer).

Lesson in Action

The application below is a simple file system browser. Using FileListBox,


DirectoryListBox, and DriveListBox, you can view your system’s file structure, from
its drives to its directories and files.

65
Private Sub dirDirectory_Change()
filFiles.Path = dirDirectory.Path
End Sub

Private Sub drvDrives_Change()


dirDirectory.Path = drvDrives.Drive
End Sub

Private Sub txtPattern_KeyPress(KeyAscii As Integer)


If KeyAscii = 13 Then
filFiles.Pattern = txtPattern.Text
End If
End Sub

Save your work as Lesson11.vbp.

On your Own

Modify the application you have created in the Lesson in Action section. In a
Label, display the number of files found with the specified pattern in a specified
location. When the user selects a file in the FileListBox, the file name complete
with its path (drive and directory) appears in another Label.

Lesson XII. ImageBox and PictureBox

Objectives
  To be able to use and be familiar with the ImageBox control and its
properties.
  To be able to use and be familiar with the PictureBox control and its
properties.
  To be able to know how the ImageBox differs from PictureBox.

Notes

Imaginative use of graphics and animation can greatly enhance an application.


There is a wide room in VB for creativity when it comes to devising ways of
acquiring, manipulating and using images. Two controls serve this purpose: the
ImageBox and PictureBox controls.

66
ImageBox and PictureBox share the following properties:

Property Description
BorderStyle Determines the whether the controls have borders (O:
None 1: Fixed Single)
Height Specifies the height of the control
Left Specifies the number of twips from the control’s left edge
to the Form window’s left edge.
Picture Sets the graphic image to be displayed in the control.
Select a file through the dialog box that appears when
this property is clicked.
Visible Determines if the control is visible at runtime.

Once you place an ImageBox or PictureBox on the Form, you can resize the controls
just as you can other controls by dragging the controls’ sizing handles in and out.
The ImageBox has a unique boolean property called Stretch. It determines whether
a graphic resizes to fit the size of the ImageBox. When you resize a PictureBox to a
size smaller than the graphic image, the PictureBox will truncate or clip the image
that does not fit in the PictureBox. Only a portion of the image is displayed. This
holds true to ImageBox if the Stretch property is set to False (the default).

You can set a background color for the PictureBox using the BackColor property.
PictureBoxes also have the AutoSize property. This property, set to False by default,
determines how the PictureBox responds to a loaded image’s size. If Autosize is
False, the control does not resize to fit the image. If however, AutoSize is True, the
control resizes and does not truncate the image. Therefore, the PictureBox’s size is
depends on the size of the image to be displayed.

Loading Pictures
You can load a picture in an ImageBox or PictureBox through:
  selecting the image file through a dialog box that appears when the
Picture property is selected
  invoking the LoadPicture() function at runtime.
e.g. imgPicture.Picture = LoadPicture(“C:\mypic.jpg”)

Note: imgPicture.Picture = “C:\mypic.jpg” is a syntax error.

67
The following are the file types supported by the Image Control

Extension File Description


.bmp Windows bitmap file
.cur A cursor file
.dib An older bitmap image format
.emf Enhanced Windows Metafile
.gif Graphic Interchange Format
.ico Icon file
.jpg Joint Photographic Experts Group format
.wmf Windows Metafile
.rle Run-Length Encodin

Lesson in Action

We will create a simple Icon Viewer using the ImageBox control. Icons are small
graphical images with .ico filename extensions. We will have to use the
FileListBox, DirectoryListBox, and DriveListBox controls to browse through the
file system of the computer.

Write the following procedures:


cmdExit
Private Sub cmdExit_Click()
End
End Sub

Private Sub dirDirectory_Change()


filFiles.Path = dirDirectory.Path
End Sub

Private Sub drvDrives_Change()


dirDirectory.Path =
drvDrives.Drive
End Sub

Private Sub filFiles_Click() drvDrives


If filFiles.FileName <> "" Then dirDirectory
imgIcon.Picture = LoadPicture(filFiles.Path & "\" & filFiles.FileName)
lblFName.Caption = filFiles.FileName
End If
End Sub

68
On your Own

Instructions: Let’s create a simple guessing game using Picture Box. Using the
Form below, the
user guesses which between the 2 PictureBoxes conceals a particular image e.g.
Apple. The
user clicks the button of his choice.

After the user has given his choice, reveal the two images. In the Label, display
You Got it Right! or Sorry, but it’s not there! whenever the user selects a correct or
incorrect choice, respectively. Refer to the Form below.

Note: Randomize the location of the images. Download images here: apple.jpg
and grape.jpg.

69
Lesson XIII. Timer

Objectives
  To know how Timer works
  To use Timer control in time-dependent applications

Notes

The Timer control works in the background – you do not see it on the Form at
runtime. The primary purpose of a Timer is to trigger an event at a certain interval.
The following are the properties of a Timer.

Property Description
Enabled Determines whether the Timer can respond to events.
Index Specifies the subscript of the control in a control array.
Interval Specifies the number of milliseconds between calls to a
Timer control’s Timer event. The value must be within
the range of 1 to 65535. This value is in millisecond (or a
thousandth of a second).

What can we do with a Timer? You may want to replace the caption property of a
Label with another quotation every 5 seconds. You may want to simulate animation
by replacing the image of an ImageBox every half a second. Or you may simply
want to give a time-pressured quiz – a sequence of questions appears one after
another at an interval of 10 seconds.

The Timer has one event, the Time event. The procedure <timer_name>.Timer( )
is executed every <interval_value> milliseconds. The Timer control continues this
until we disable the control by setting the Enabled property to False.

Lesson in Action

Let’s have some fun and create a small animation. Animation involves a series of
still images displayed in rapid sequence. We will need several images of an object
to be animated at different times. For this application, we will make a dog walk.

The following are the images that we will use:

70
The images are named dog1.wmf, dog2.wmf, dog3.wmf, dog4.wmf, and dog5.wmf.
You will later know why we have to make the names similar.

Follow these steps:


1. Create a new Project.
2. Drag an ImageBox to the Form and name it imgDog. Set the Picture
property to dog1.wmf (the initial snapshot of our dog). Resize the ImageBox
to the size you want. Make sure that the Stretch property is set to True so
that the image resizes to the size of the ImageBox.

3. Drag a Timer to the Form.


4. What we want to do is to change the image every 80 milliseconds. Thus, set
the Interval property of the Timer to 80.
5. We have already displayed dog1.wmf. We will have to display dog2.wmf,
dog3.wmf, …, dog5.wmf, then back to dog1.wmf. Add the following
procedure:

Private Sub timTimer_Timer()


imgDog.Picture = LoadPicture (App.Path + "\dog" & Trim(Str(x)) &
".wmf")
If x < 5 Then
x=x+1
Else
x=1
End If
End Sub

71
What the above code does is to change the picture by calling the
LoadPicture() function. "\dog" & Trim(Str(x)) & ".wmf" specifies the filename
of the image to be loaded and displayed. Variables x serves as our counter.
If x is currently one, then we load dog1.wmf. If it is 2, then we load
dog2.wmf. Had we not named the pictures such, we will have to write the
filenames lexically.

The first time timTimer_Timer() is called, we dog2.wmf should be loaded.


Hence, we have to initialize x to 2. We do this during Form_Load(). We will
have to declare in the general area with the Public keyword to make variable
x accessible to all procedures.

Public x As Integer

Private Sub Form_Load()


x=2
End Sub

6. Run the application.


7. Save your work as Less13.vbp.

On your Own

1. Add a button to the Dog Animation application with caption “Pause”. If the
user presses the Pause button, the animation stops and the caption of the button
changes to “Play”. If the user clicks the Play button, animation resumes.

2. Create an application. Add a Label to the Form with the caption “Timer”.
Set the Font property to Arial, size 6. Drag a Timer control as well. Every
second, add 3 points to the Label’s font size. When the font size grows to a
value that will make the caption too big for the Label, set the font size back to 6
points and start increasing the size once again.

Lesson XIV. Modules, Event Procedures, Sub Procedures, & Function


Procedures

Objectives
  To understand how to construct programs modularly from procedures
and functions
  To be able to create new procedures and functions
  To understand the mechanisms used to pass information between
procedures and functions
  To understand the Exit Sub and Exit Function Statement

72
  To understand how the visibility of identifiers is limited to specific
regions of programs
  To be able to create and use code modules

Notes

A Visual Basic project is made up of modules such as Form Modules. A Form


Module consists of pieces of codes called Procedures. In this lesson, we will
discuss the four types of procedures, namely: Visual Basic Procedures, Sub
Procedures, Event Procedure, and Function Procedures.

Type Description
Visual Basic Procedures provided by Microsoft to perform
Procedures common tasks (e.g. Format(), Str(), Val())
Sub Procedures A block of statements that perform a particular
task. They may receive data from the calling
Procedure.
Event Procedures Similar to Sub Procedures but the Procedure is
executed as a response to an event (e.g. keypress)
Function Similar to Sub Procedures but return a value to the
Procedures calling Procedure

Sub and Function Procedures are invoked by another Procedure through a


Procedure call made by a Caller Procedure. The call specifies the Procedure name
and provides information (if needed; as arguments) that the callee needs to do its
job.

IN FOCUS: SUB PROCEDURES

The syntax of Sub Procedures is as follows:

Private Sub <procedure_name>( )


One or more VB Statement
End Sub

Private Sub <Procedure_Name>(<arguments>)


One or more VB statements
End Sub

Examples are as follows:

‘Example of a Sub Procedure


Private Sub ComputeSum( )

73
x=y+z
lblSum.Caption = “Sum is “ & Str(x)
End Sub

IN FOCUS: FUNCTION PROCEDURES

The syntax of Function Procedures is as follows:

Private Sub <procedure_name>( ) As <data_type>


One or more VB Statement
<procedure_name> = <expression>
End Sub

Private Sub <Procedure_Name>(<arguments>) As <return_value_data_type>


One or more VB statements
<procedure_name> = <expression>
End Sub
Examples are as follows:

‘Examples of Function Procedures


Private Sub GetNameLength( ) As String
GetNameLength = Len(lblName.Caption)
End Sub

Private Sub ComputeProduct(y As Integer, z As Integer) As Integer


ComputeProduct = y * z
End Sub

c = ComputeSum(a,b) Private Sub ComputeSum(x As Integer, y As Integer)


ComputeSum = x + y
End Sub

Caller Callee

<return_value_data_type> specifies the data type of the return value. Recall that
all Function Procedures must return a value to the calling procedure. How do we
return a result? You assign the result to a variable whose name is the same with
the Function Procedure name. In the example above, we return the result through
ComputeSum variable. Note: <return_value_data_type> is optional. If you don’t
specify it, the return value will have a Variant data type.

74
Another thing that you should take note in using Function Procedures are the
arguments. Function Procedures may have arguments, and in this case, the calling
procedure must pass the same number of arguments. The order of the arguments
to be passed to the Function must correspond to the order of arguments in the
Function header with respect to the data types. This means that if the Function
requires 2 values, one String and one Boolean, the calling procedure must pass one
String and one Boolean in this order. We will learn more about this parameter
passing process in the following section.

IN FOCUS: PARAMETER PASSING

Parameter Passing is a process by which the caller (or the calling procedure) passes
(or transmits) the parameter (or actual arguments) to a called procedure and binds
the actual arguments to the formal parameters. Procedures communicate with each
other through this process. A particular procedure might have this particular
capability and for other procedures to take advantage of its services, it needs to
know the procedure’s name and the data it needs, if any.

There are two parameter passing conventions supported by Visual Basic: Pass-by-
Value and Pass-by-Reference.

Call-by-Value
In Call-by-Value, a copy of the argument’s value is passed, thus, the called
procedure do not manipulate the caller’s data because it is the copy that it received.
There is one known disadvantage: if we have numerous arguments with large sizes,
we incur an overhead of copying large amounts of data. This may cause our
application to run slow.

You call a procedure by Call-by-Value through the Call statement as we have


discussed, but you should tell the procedures to be called to receive the just value of
the passed arguments:
 Precede the corresponding parameter variable in the procedure definition
with keyword ByVal
e.g. Function X (ByVal x as Boolean) As Integer
 Enclose the argument in parentheses ( )
e.g. Function X ( (x) as Boolean) As Integer

Call-by-Reference
Call-by-Reference is the default method. The caller gives the called procedure the
ability to directly access the caller’s data and to modify the data if the called
procedure chooses. This is accomplished by passing the reference (the addresses of
the variables) to the arguments. Because of this, duplication is avoided but it has
weak security.

75
Since this is the default passing convention, you need do tell the called procedure to
receive the reference instead of the value. There is one explicit way of doing this:
precede the corresponding parameter variable in the procedure definition with
keyword ByRef as in the following example:

Function Sample (ByRef x As Boolean) As Integer

IN FOCUS: OPTIONAL ARGUMENTS

Visual Basic allows programmers to create procedures that take one or more
optional arguments – the caller has the option of passing that particular argument.

In the following example, variable z is optional as denoted by the keyword


Optional. This means that the calling procedure may or may not pass an argument
to z.

Private Sub AAA(y as Boolean, Optional z as Long)


….
End Sub

-----
Call AAA() ‘Invalid because the first argument is mandatory
Call AAA(True) ‘Valid
Call AAA(True, 10) ‘Valid
IN FOCUS: EXIT SUB AND EXIT FUNCTION

Exit Sub and Exit Function alter the flow of control. They cause an immediate exit
from a Sub Procedure and Function Procedure, respectively. When this happens,
control is then returned to the caller and the next statement in sequence after the
call is executed.

In the following example, Exit Sub terminates PrintNumbers when num<0.

Private Sub PrintNumbers (num as Integer)


If num>=0 Then
….
Else
Exit Sub
End If
End Sub

76
IN FOCUS: STATIC PROCEDURES AND VARIABLES

Variables declared within procedures, also known as local variables, are allocated
space when the procedure is active (when it is currently being executed)
and deallocated space when the procedure terminates. Programming
Languages are designed this way to save space – outside of the procedures,
local variables are often not needed, and thus we can just do away with
these. When a variable is deallocated space, the datum stored in it is
erased.

There are cases when you want to maintain a variable all throughout the program’s
execution time. You can do this either by declaring the variable outside of
Procedures or by making them Static. Static variables are allocated and initialized
once the Form is loaded. You declare a Static variable through preceding a variable
declaration with the keyword Static. For example,

Static Dim x as Integer

If you want to make all local variables Static, you can just create a Static Procedure.

Private Static Sub MyProcedure() ‘Static Procedure


Dim x, y, z As Integer

End Sub

In the above procedure, x, y, and z are Static variables – regardless of whether or


not variables are explicitly declared Static.

Lesson in Action

Let’s create a simple application that determines the smallest value among 3
numbers entered in 3 TextBoxes. What we need is an interface and a Function
that will determine the smallest value.

77
Write the following procedures.

Private Sub cmdGetMin_Click()


Dim v1 As Integer, v2 As Integer, v3 As Integer

v1 = val(txtNum1.Text)
v2 = val(txtNum2.Text)
v3 = val(txtNum3.Text)

‘Call GetMinimum Function and pass the v1, v2, and v3


smallest = GetMinimum(v1, v2, v3)
lblOutput.Caption = "Smallest value is " & Str(smallest)
End Sub

Private Function GetMinimum(min_val As Integer, y As Integer, z As


Integer) As Integer
‘Assume that the first number is the smallest. We just then compare this to
the other 2 numbers.
If (y < min_val) Then
min_val = y
End If

If (z < min_val) Then


min_val = z
End If
GetMinimum = min_val
End Function

Save your work as Less14.vbp.

On your Own

1. Write a Function Procedure that accepts an Integer and returns its square.

2. Write a Function Procedure named IsEven that accepts an Integer and


returns True if this Integer is even, False if it is odd.

3. Write the procedure header for the following:


a. RectArea takes two Double arguments, length and height, and returns a
Double result.
b. OutputResult does not receive any arguments and does not return a value
c. ChangeString takes 1 String and 1 Integer argument, and returns a String.

78
Lesson XV. Working with Multiple Forms

Objectives
  To create applications consisting of more than one Form
  To include in applications Forms that have been created previously
  To provide simple code to enable users to navigate between Forms at
runtime

Notes

When you create a new project, VB provides a blank Form named Form1. You can
create an application with this Form, but for complex applications, you may need to
work with multiple Forms. For example, it is common to have a welcome screen and
a main Form that branches to different Forms. The high level structure of an
interactive application can often be understood best from a diagram showing the
Forms hierarchy. You can have 3 Forms in your project: One Form might be the
opening Form, the other two for Addition and Multiplication routines. Just imagine
how a Form would look like if it has so many functionalities. It would probably look
cluttered and confusing.

So how do we add a new Form to a project? You can do in 2 ways:

 On the Tool Bar, click the Add Form icon . Click Form. This will display
the following dialog box:

Form is the default selection and this is just what we need.


Click Open. The newly added Form will be displayed and a new Form icon
will be added in the Project Explorer.

79
 You can also add another Form by doing a right-click on the Project
Explorer, Click Add, then Click Form.

If you want to add an existing Form (in case your new project needs a Form you
have previously created for another project), follow the same steps but instead:

 Method 1: Select Existing Tab of the dialog box displayed above, locate the
Form, select the Form, and click Open.
 Method 2: Click Add File instead of Form. Locate the Form, select the
Form, and click Open.

Note: The added Form will have a default name of Form1. Make sure that there
are no other Forms currently in the project with this name. A loading error will
occur if name duplicate is found. You may notice that the filename of this added
Form still has its original filename. This is because VB keeps only one copy of each
file (even if it is used in different applications). So if you want to use and modify an
existing file, you must save it as another file with the Save As option by doing a
right-click on the Form icon in the Project Explorer, click Save
<theOrigFileName> As…, provide a new filename, select the directory where
you would be saving the Form, and click Save.

You may also remove a Form from a project by selecting the Form on the Project
Explorer, then clicking Remove <form_filename>.

Switching Forms at Runtime


It is virtually impossible to interact with 2 or more Forms at the same time. Only
one Form can have the focus. To switch between Forms at run time, you need to
hide (using the Hide method) the current Form (e.g. frmForm1) and show (using
the Show method) the next one (e.g. frmForm2). This is done with the following
statements. These statements should be attached to the event (e.g. button click)
that causes the change of Form to occur.

frmForm1.Hide
frmForm2.Show

Note: frmForm1 is the Form’s name. Do not confuse this with the Form’s filename
(the one with the .frm extension).

Every Form that is the screen displayed is first loaded into memory. Even when it is
hidden it still remains loaded in memory. This is not a problem with two or three
Forms, but if you have many Forms, you can run out of available memory. If this
happens the solution is to unload some of the Forms the program no longer need.
Use the Unload command to do this:

Unload frmForm1

80
Conversely, the Load command loads a Form into memory without displaying it.
This is usually unnecessary since VB performs a load automatically if the Form to be
displayed is not yet in memory.

You can also show a Form without hiding the current one. In this case, you will
have several Forms on top of the other – the top most is the active one. You may
not want this to happen if do not want the user to interact with another Form
without unloading or disabling the current one. One situation is when you have a
hierarchy of Forms:

Form1
The Main Menu

Form2 Form3
Science Mathematics

Form4 Form5
Biology Chemistry

The Form1 displays the main menu that branches out to Science and Mathematics.
Once the user clicks on the button that leads to Science, you may want to disable
Form1 until the user closes Form2. In this case, there is only one way of going to
Mathematics: through Form1.

We do this by disabling a Form through the Enable property before showing another
Form as in the following statements:

frmMainMenu.Enable = False
frmScience.Show

Somehow, the user is able to close frmScience and focus is given back to
frmMainMenu. We do this by unloading frmScience, enabling frmMainMenu and
giving back the focus to it (note that enabling a Form does not give the Form the
focus). The code will be:

Unload FrmScience
frmMainMenu.Enable = True

81
frmMainMenu.SetFocus ‘Set the focus to frmMainMenu

There is an easier way of doing this. The procedure below calls frmScience with two
arguments: vbModal and Me. vbModal tells VB that the current Form should be
disabled until the called Form is unloaded. Me means that the calling Form is the
owner of the called Form, and that when the latter is unloaded, control is passed to
the owner Form.

Private Sub cmdGoToScience_Click()


Call frmScience.Show(vbModal, Me)
End Sub

IN FOCUS: STARTUP FORM

Since you have more than one Form in your project, you have to tell Visual Basic
which Form should be displayed during startup. You specify the startup Form
through:

1. From the Project menu, choose Project Properties.


2. Choose the General tab.
3. In the Startup Object list box, select the Form you want as the new startup
Form.
4. Choose Ok.

Sometimes you might want your application to start without any Form initially
loaded. For example, you might want to execute code that initializes a couple of
variables before displaying any Form. You can do this by creating a Sub Procedure
called Main in a standard module, as in the following example:

Sub Main( )
intStatus = “Locked”
'Show a startup form
frmMain.Show

This procedure must be a Sub procedure, and it cannot be in a Form Module. To


set the Sub Main procedure as the startup object:

1. From the Project menu, choose Project Properties.


2. Select the General tab
3. Select Sub Main from the Startup Object box.

82
Lesson in Action

Let’s create an application with 3 Forms. The first Form (frmMain), as shown below,
is the Main Menu. The button labeled Mathematics loads the Mathematics Form
(frmMath). The button labeled Science loads the Form (frmScience).

Below are the screenshots of the Science and Math Forms.

Set the StartUpPosition of frmMain to 2-CenterScreen. For the 2 other Forms, set
this property to 1 – CenterOwner.

Write the following procedures for frmMain.


Private Sub cmdMath_Click()
frmMath.Show vbModal, Me
End Sub

Private Sub cmdScience_Click()


frmScience.Show vbModal, Me
End Sub

83
Private Sub cmdQuit_Click()
End
End Sub

Write the following procedure for frmScience and frmMath.


Private Sub cmdBack_Click()
Unload Me
End Sub

On your Own

1. What happens when you attempt to hide an unloaded Form?

2. Create a multiple Form application. Each Form has a button labeled


Previous and Next. By pressing the Next button, a Form is displayed one
after the other (Form1, Form2, .., Form5). When the 5 th Form is loaded, the
Next button loads the 1st Form. The previous button loads the previous Form
e.g. if the active Form is the 3rd one, then load the 2nd one. Note: Only one
Form should be displayed, so unload the active Form before loading another.

3. Modify the application you created in item 2. In a Label on each Form,


display how many items each Form has been accessed (or loaded).

4. Create a simple login functionality. Add 2 Forms to a project. The first Form
asks for a password in a TextBox. Assume that the password is “Letmein”
with the quotes. When the user enters this password, unload this Form and
load the other Form. Otherwise, prompt the user of the incorrect password
using a MsgBox.
Lesson XVI. Working with Menus

Objectives
  To be able to create menus to enhance application’s GUI
  To be able to use menus to trigger Event Procedures

Notes

If you have been working with the Windows TM operating system, you already have
been exposed to menus. When you open a file in Microsoft Word TM, insert a
PowerPointTM slide, or exit a Windows application, you use menus to select the
functionality you need. What you may not know is that the menu selections File and
Exit are independent controls that VB can create for you using the menu editor.

84
Menus are groups of related commands. The concept that a menu selection is really
a control is because menus support properties and events, just like any other
controls we have been using.

Menus support only one event, the click event (occurs when a menu item is
selected).

Before we get into the menu editor, in which you can set properties of a menu
control, let us look at the complete list of menu control properties.

Properties Description
Caption The visible text you see on the menu item
Name The name used in code to refer to the menu control
Checked Determines whether a small check mark is
displayed to the left of the menu control
Visible Determines whether a menu control can be seen
Enabled If False, the text is grayed out and cannot be
selected
Index If you create a menu control array rather than
name individual menu items uniquely, this property
specifies the menu item’s subscript within the
control array.
Shortcut A key sequence that will invoke the menu
HelpContextID Determines which topic in the help file will be
displayed
NegotiatePosition Works in conjunction with OLE embedment to
determine which menu controls are displayed
WindowList Determines whether a menu control maintains a list
of the current MDI child windows

Our task is to create the menu structure using the Menu Editor and to set the
properties for each menu. Then we add code to each Click event to perform
whatever function you choose in response to a user selection of the menu items.

85
IN FOCUS: MENU EDITOR

The following is the Menu Editor window:

As you can see, the editor has two general sections. In the top half, you set the
properties we enumerated on the previous page. In the bottom half you create the
hierarchical structure of the menu (the hierarchy determines how the menu items
are organized and displayed on the Form).
Remember that menus are only associated with a Form. No other control has a
menu. VB provides the built-in ability to manage the display of all of the menu
items. You only have to create the structure and let VB handle it from that point on.

Now, let's talk about each of the properties and see if there's some guidance on
what to use for the properties.

Caption Simply use the shortest name you can. Users


hate long captions because they take up to
much space on the screen and reading them
slows down using the menu. Also, try to use a
caption that does not have the same first letter
as any other menu caption. This will allow you
to use the first letter of the control caption as
the shortcut - it makes it much easier for the
user to remember!
Name While it can be anything, remember that the
menu event will bear this name. For easy

86
identification, the name should be prefixed with
mnu e.g. mnuFile, mnuEdit.
Checked Menu items are either checked or not. You can
check it from within the menu editor or by using
code. Generally, you’ll add checkmarks to menu
options that perform on or off actions, such as
to display or not to display a Form. For
example, this code will cause a menu item to be
displayed with a small checkmark to its left:

mnuFileOpen.checked = True

Visible If you want to prevent a user from having


access to a menu item, simply set the visible
property to FALSE. This will keep the user from
even knowing that the menu item exists.

mnuFileOpen.visible = False

Enabled To allow the user to see the menu, but not to


select it, set the enabled property to False:

MnuFileOpen.enabled = False

Shortcut Most users want to be able to invoke a menu


item from the keyboard. This is the property
that defines the shortcut keystrokes. When a
shortcut is defined, you can invoke the menu
item from the keyboard, no matter how deep in
the menu structure the item is that you are
calling.

87
Lesson in Action

Let’s create a menu structure as shown in the following Forms.

As shown in the previous page, The File menu has 3 menu items: Open, Close, and
Exit. When we dig in the Open submenu, we can find the items labeled Form and
Project. Under the Edit menu, we have items Copy, Paste, Search, and Replace.
Follow through the following steps:

1. On the menu bar, click Tools.


2. Click Menu Editor.
3. Let's create the File menu. Enter the following property settings:
 Caption &File
 Name mnuFile
 Leave the rest of the properties as they are: Enabled and Visible
4. Click Next.
5. Since Open is a menu item under File, click the right arrow (è) button. This
also causes all the succeeding new menu items to fall under the Open menu.
6. For the Open menu item:
 Caption &Open
 Name mnuOpen
7. Click Next.
8. Click the right arrow (è) button to create a submenu.
9. For the Form submenu:
 Caption &Form
 Name mnuForm
 Shortcut Ctrl+F
10.Click Next.
11.For the Project submenu:
 Caption &Project
 Name mnuProject
 Shortcut Ctrl+P
12.Click Next.
13.Click the left arrow (ç) button.

88
14.For the Close submenu:
 Caption &Close
 Name mnuClose
 Enabled Disable by unchecking the checkbox
15.Click Next.
16.For the Exit submenu:
  Caption &Exit
  Name mnuExit
17.Click Next.
18.Click the left arrow (ç) button.
19.Create the Edit menu.
  Caption &Edit
  Name mnuEdit
20.Click Next.
21.Click the right arrow (è) button to add items for the Edit menu.
22.For the Copy menu item:
 Caption &Copy
 Name mnuCopy
 Shortcut Ctrl+C
23.ClickNext.
24.For the Paste menu item:
 Caption &Paste
 Name mnuPaste
 Shortcut Ctrl+V
25.Click Next.
26.Let's insert a divider.
 Caption - (one dash)
 Name Any name. We won't be referring to this anyway.
27.Click Next.
28.For the Search menu item:
 Caption &Search
 Name mnuSearch
 Shortcut F3
29.Click Next.
30.For the Replace menu item:
 Caption &Replace
 Name mnuReplace
 Shortcut F4
31.Click Next.
32.For the Case Sensitive menu item:
 Caption Case Sensitive
 Name mnuCase
 Checked check the checkbox
33.Click Ok.

89
You can always edit an existing menu structure.
 Delete an item: just select the menu item and press the Delete button.
 Edit the properties of a menu item: select the item to be edited and edit
the properties.
 Modify the order of items listed in the menu editor: select the item and
press either the up (é) or down (ê) button. You can still use the left (ç) or
right (è) buttons to move items from one level to another.
 To insert a menu item: Select the position in the menu hierarchy where
you will insert the item and press the Insert button.

On your Own

Create a new project with the following menu bar items: Lessons, and Options.
The menu structure is as follows:
A. Lessons
1. Mathematics
a. Addition
b. Subtraction
2. Science
a. Animals
b. Plants
B. Options
1. Audio On (Checked item)
2. Input Device (Checked item)
a. Keyboard
b. Mouse

Note: Only one Input Device should be checked at a time. If the user selects
Keyboard, then Mouse should be unchecked.

Lesson XVII: Data Arrays and Control Arrays

Objectives
 To understand the array data structure
 To understand controls arrays
 To use control arrays in an application
 To be able to declare and manipulate arrays
 To be able to pass arrays to procedures

90
Notes IN FOCUS: DATA ARRAYS

Arrays are data structures consisting of contiguous memory “cells” of the same
name and type. For example, we can have an array of student names. In Visual
Basic, we refer to each element in an array through an index e.g. name(0),
name(1), .., name(n).

Declaration
Arrays should be declared so that the compiler can determine the amount of
memory space to allocate. Recall that data types have different memory
requirements. You declare arrays through the following syntax:

Dim <var_name> As <data_type>

Examples:
a. Dim grade(7) As Integer
b. Dim grade(7) As Integer, name(7) As String

Example a. tells the compiler to reserve six elements for array grade of type Integer.
The value 7 tells defines the upper bound of the array. The compiler allocates 7
“cells” of equal memory sizes with indices starting at 0 (the lower bound) until 6.

Note: Unlike other variables, arrays should implicitly be declared. Not doing so is a
syntax error. Arrays may be declared in Code or Form Module but may only be
declared Public in the former.

Numeric array elements are initialized to zero (0) by default. Strings are initialized
to a zero-length String. The programmer can also initialize the array with user-
defined values. Take the following examples:

a. grade(0) = 9
grade(1) = 5
b. For x = 0 To 7
grade(x) = 2
Next x
c. For x = 0 To 6
grade(x+a) = 2 ‘Make sure that the expression x+a evaluates to a Long
value
Next x

Passing Arrays
Arrays can be passed to a procedure. To do so, specify the name of the array
followed by a pair of empty parentheses. For example:

91
Call ComputeAverage( grade() )

You can also pass selected elements of an array, as in the following example:

Call ComputePercentage( score(3) )

Take note that array or individual array element arguments are always passed by
reference – the procedure can modify the contents of the original array.

On the part of the called procedure, its parameter list must specify that an array will
be received. The procedure header of ComputeAverage might be written as:

Private Sub ComputeAverage( x() As Integer )

The header indicates that the procedure expects to receive integer array in formal
parameter x. The size of x is not specified because it will be referring to the actual
argument array grade() (by virtue of pass by reference).

On the other hand, if the procedure expects to receive an individual array element,
you write the procedure header as you do in expecting non-array arguments. An
example is:

Private Sub ComputePercentage( x As Integer )

Variable x will be referring to element score(3).

IN FOCUS: MULTI-DIMENSIONAL ARRAYS

Arrays can have multiple dimensions. One use of this is when you want to represent
data in a table (where each data, is in a spreadsheet, is referred to by its column
and row number). In Visual Basic, we declare, say a 2-dimensional array, through:

Dim point(5,5) As Integer

You manipulate multi-dimensional arrays in the same manner as you do a one-


dimensional array (you can pass the array to procedures, use mathematical
expressions as indices, etc).

Note: Refer to each element as point(2,3) and not as point(2)(3). The latter is a
syntax error.

Visual Basic supports 60 array dimensions, but normally, programmers only need to
use no more than 3 dimensions.

92
IN FOCUS: DYNAMIC ARRAYS

Dynamic arrays are flexible arrays – their size can be changed during the course of
the program execution. Dynamic arrays are very useful when you do not know how
many elements to store in the array during development (programming) time.

A dynamic array is not given a size when declared. For example:

Dim student() As String

You can resize the array at runtime through the statement:

ReDim student(8)

ReDim must be written within procedures. You can ReDim an array many times.
It can also be used to change the index bounds. The statement

Redim student(3 to 10)

changes the lower and upper bound to 3 and 6, respectively.

Note: During declaration, the number of dimensions of the array is not yet
specified. This is determined the first time ReDim is used. Once this is done, the
number of dimensions cannot be changed.

When ReDim is used, all the contents of the array are erased. Numeric arrays are
initialized to 0 and Strings to a zero-length String. If you want to retain the
values, use the keyword Preserve as in the following statement:

ReDim Preserve student(8)

IN FOCUS: CONTROL ARRAYS

If you need to erase the text property of 10 TextBoxes, what do you do? You
make 10 statements: txtName0.Text = “”, txtName1.Text = “”, …, txtName9.Text =
“”. This is one heck of a job. With control arrays, you can group related controls
and refer to each control by an index. We then refer to the TextBoxes as
txtName(0), txtName(1), …, txtName(9). To solve the problem, we write the
following code:

For x= 0 To 9
txtName(x).Text = “”
Next x

93
Note that the names of the controls are all the same. They only vary in index (when
a control is part of a control array, an Index property is added). A control array is
an array of the same control. This means you cannot have an array composed of
TextBoxes and Labels. One good thing about controls array is that when you
format one control (e.g. changing the BackColor property), the format is applied to
all other controls in the array.

So how do you create a control array? When you name a control with an existing
name (of the same type of control), Visual Basic displays a dialog box asking you if
you want to make a control array. Just click Yes. If you click the No button, VB
renames the control. The dialog box appears below.

Typically, an event procedure for a CommandButton is in the form:

Private Sub cmdSum_click ( )



End Sub

If we have a control array, we have controls with the same name. How do we know
then which button has been pressed? All Event Procedures related to a control
array has a special argument value passed to them. This value determines which
control is being worked on. Below is a click event of a CommandButton that is part
of a control array.

Private Sub cmdSum_click (Index as Integer)



End Sub

How do you modify the properties of control array at runtime? Refer to a specific
member of the control array using an index. For example,

txtGrade(0).Text = “90”
lblResult(4).Caption = “Computer”

94
Lesson in Action

Let’s create an application that asks for a maximum of 10 numbers and displays the
average of these numbers.
txtNum cmdAdd lblOutput lblAverage

cmdClear cmdCompute

Dim numbers(10), x As Integer

Private Sub cmdAdd_Click()


lblOutput.Caption = lblOutput.Caption & "[" + txtNum.Text & "]"
numbers(x) = Val(txtNum.Text)
x=x+1
If x = 10 Then
cmdAdd.Enabled = False
End If
End Sub

Private Sub cmdClear_Click()


x=0
lblOutput.Caption = " "
End Sub

Private Sub cmdCompute_Click()


Sum = 0
For y = 0 To x - 1
Sum = Sum + numbers(y)
Next y
lblAverage.Caption = " Average: " & Format((Sum / x), "0.0")
End Sub

Private Sub Form_Load()


x=0
End Sub

95
On your Own

1. Create an application that asks for 10 numbers (to be entered in a control


array of 10 TextBoxes) and outputs the average of these 10 numbers in a
Label. Create a function that receives an array of these values to do the
averaging.

2. Create the following application:


a. Using an Input Box, ask for how many student names are to be
entered.
b. Ask the names of these students using a series of Input Boxes. Store
the names in a data array.
c. When the all the names have been inputted, load a Form.
d. The Form contains a TextBox and a CommandButton labeled
Search. The user may enter a name in the TextBox and presses the button
to search this name. If the name is in the array, display a Message Box
with caption Name found!. Otherwise, display Name not found!.

Lesson XVIII:Sequential File Handling

Objectives
  To be able to open and close sequential files using Open and Close
  To be able to detect end-of-file condition
  To be able to write to files using Write
  To be able to fetch data from files using Input

Notes

Visual Basic offers file handling capabilities and database handling features. In
database handling controls, the file manipulation is transparent to the programmer
and user. However, in non-database applications the programmer has to handle
virtually all aspects of reading or editing the data contained in a file. This is what
this lesson will cover.

Simple text files (also called sequential files) are often used as the storage method
for information. This is because of their universally standard format. You can simple
create text files using DOS Edit TM program and the newer Windows NotePad TM
applications.

To start manipulating files, you must first open it. You do this through the
following:

96
Open <filename> for <mode> As # <filenumber>

Close #<filenumber>

Open tells Visual Basic to locate a file specified by <filename>, open it for some
purpose, and in some cases, create the file if it does not exist. <filename> can be a
string literal such as “D:\myfiles\names.txt” or a string variable containing the name
of the file to be opened. <mode> tells Visual Basic what to do with the opened file.
It can be any of the following:

Mode Description
Input Opens files for reading. An error occurs if the specified
file does not exist.
Output Opens files for writing. If the specified file does not exist,
VB creates the file for writing. Note: It overwrites the
contents of the file specified.
Append Opens files for appending. It appends new data to the
contents (if there are any) of a file. If the specified file
does not exist, VB creates the file.
Random Opens files for reading or writing.

The pound sign (#) is optional. The <filenumber> value (also called file channel),
which can be between 1 and 255 inclusive, represents the specified file. If you need
to manipulate a file, you refer to the file by the <filenumber> to which it is
associated. The number remains associated to the file until such the time when you
close the file using Close statement. Always remember that a <filenumber> can
only be associated to one file only at one time. If the file is closed, you may use the
<filenumber> again for some other file. If you have lost track of the available
<filenumber>, you may use the FreeFile() function as in the following statement:

FileNum = FreeFile()
The Close statement on the other hand performs the opposite job from Open. It
closes a file and releases the <filenumber> for reuse by the Open statement.
There are 2 ways in which you can use this statement. They are as follows:

Close #<filenumber>, …, #<filenumber> e.g. Close #1 / Close #1,


#2, #7

Close

The first Close format closes one or more files as specified by the <filenumber>.
The second format close all opened files, thereby releasing all <filenumber>s.

IN FOCUS: WRITING TO FILES

97
The Write command writes data of any data type or format to an opened file. You
need to open a file for Output, Append, or Random before you can use Write.
Below is the syntax of Write:

Write #<filenumber>, <expressionlist>

<filenumber> is the number of the opened file where we will write the data.
<expressionlist> contains the value or values that you will be writing to the file. If
you don’t specify <expressionlist>, then Write writes a carriage return (ASCII 13)
and line feed (ASCII 10) character to the file. If you have multiple values in
<expressionlist>, separate these values by a comma. VB automatically writes a
carriage return (ASCII 13) and line feed (ASCII 10) character after these data.

Let’s take the following example:

StudeName(0) = “Antonio”
StudeName(1) = “Heidi”
StudeName(2) = “Joni”
StudeAge(0) = 24
StudeAge(1) = 25
StudeAge(2) = 29

Open “C:\studerec.txt” For Output As #1


For x = 1 To 2
Write #1, StudeName(x), StudeAge(x)
Next x
Close #1

When executed, the above code will produce the following file contents:

“Antonio”, 24
“Heidi”, 25
“Joni”, 29

IN FOCUS: READING FROM FILES

File handling does not only mean writing to files. What are files for if we do not use
the contents? Retrieving files is easy. You do this using the Input statement
through the following syntax:

Input #<filenumber>, <expressionlist>

The Input statement reads the data stored in the file into a list of variables
enumerated in <expressionlist>. Note that the <expressionlist> should match the

98
type and number of data stored in the file. In our example above, we wrote the
name followed by the age of the student. If we fetch these data, a sample code
might be:

Open “C:\studerec.txt” For Input As #1


Input #1, StdName, StdAge
Close #1

Variable StdName will receive the name while StdAge will receive the age. Thus,
they must be of type String and Integer respectively. More, the order of the
variables in the <expressionlist> should match the order of data in the file. The first
value will be stored in the first variable, the second value on the second variable,
and so on. Errors may occur if read more data than the file holds or when you are
storing a data to a variable of incompatible type (e.g. a Boolean value into an
Integer variable).

We are not done yet. What the code above does is simply to fetch the values on
the first line: store “Antonio” to StdName and 24 to StdAge. From this, we say that
Input just fetches one line only. So do we fetch the remaining data? Answer: We
need to do a loop through the file until we reach the end of it. How do we know
that we have reached the end of the file? Answer: VB provides you with the EOF()
function. It returns True if we have reached the End Of File. Therefore, what we
should do is to keep on executing Input while EOF() returns False. The following
code does all these routines:

Open “C:\studerec.txt” For Input As #1


Do Until (EOF(#1) = True)
Input #1 StdName, StdAge
Loop
Close #1
This code works but with one flaw: Every time we iterate the Input statement, we
overwrite the date previously stored in StdName and StdAge. This does not serve
our purpose, after all! What we should do then is to store the contents in an array.

Open “C:\studerec.txt” For Input As #1


x=0
Do Until (EOF(#1) = True)
Input #1 StdName(x), StdAge(x)
x=x+1
Loop
Close #1

After 3 iterations, we will have the following data:

99
StdName(0) “Antonio” StdName(1) “Heidi” StdName(2)
“Joni”
StdAge(0) 24 StdAge(1) 25 StdAge(2) 29

Lesson in Action

Let’s create a simple file handling application. The Form below contains a
TextBox, a ListBox and 2 CommandButtons. The “Add Name” button adds the
name entered in the TextBox to the ListBox. “Save to File” button saves the
contents of the ListBox in a text file for future use.

Enter the following code into the code window.

‘This procedure adds the name in the TextBox in the ListBox


Private Sub cmdAddName_Click()
lstNames.AddItem txtName.Text
End Sub

‘This procedure saves the contents of the ListBox to a text file named names.txt
Private Sub cmdSave_Click()
Open App.Path & "\names.txt" For Output As #1
For x = 0 To lstNames.ListCount - 1
Write #1, lstNames.List(x)
Next x
Close #1
End Sub

‘When the form is loaded, this procedure retrieves the names saved in the file (if
any)
Private Sub Form_Load()
Open App.Path & "\names.txt" For Input As #1

100
While Not EOF(1)
Input #1, temp
lstNames.AddItem temp
Wend
Close #1
End Sub

On your Own

Instructions: Modify the sample program to include not just the name but also the
age of the person. The program should also be able to delete a person and edit
a person’s data.

The < and > buttons are for browsing through the student records. When > is
pressed, the program displays the records of the next student (if any). Disable
this button when there are no more succeeding records. When < is pressed, the
program displays the records of the previous student (if any). Disable this
button when there are no more preceding records. The records of the first
student (the one stored at index 0 of the array), if any, should be displayed
during start-up. The TextBoxes containing the student’s name and age should
be locked to avoid being edited. Unlock these TextBoxes only when the user
adds a new student (when the New button is pressed) or when the Edit button is
pressed. Disable Edit and Delete buttons when there are no displayed records.
The Save button should be disabled until the user adds a new student record.
Use two arrays StudeName() and StudeAge() to store the students’ data and
store these in StudeRec.txt.

101

Anda mungkin juga menyukai