Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views189 pages

Application Programming

The document provides a comprehensive guide to Microsoft Visual Basic 6.0, covering the environment setup, form design, control properties, and basic programming concepts. It includes step-by-step instructions for creating applications, managing controls, and writing event-driven code. Additionally, exercises are provided to reinforce learning and application of the concepts discussed.

Uploaded by

dranzxell
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views189 pages

Application Programming

The document provides a comprehensive guide to Microsoft Visual Basic 6.0, covering the environment setup, form design, control properties, and basic programming concepts. It includes step-by-step instructions for creating applications, managing controls, and writing event-driven code. Additionally, exercises are provided to reinforce learning and application of the concepts discussed.

Uploaded by

dranzxell
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 189

Microsoft Windows Visual Basic 6.

0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Microsoft Windows Visual Basic 6.0

Introduction

Events

Text boxes and buttons

List, combos and forms

Graphics $ simple animation

Timers, scroll bars, etc

File system controls

Modules and functions

Applications and DLL’s

Grid, Data & OLE Controls

MDI, toolbars etc

Data Access

Introduction

[email protected] 1
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Introduction to the Visual Basic Environment, Forms, Controls and


Properties

1. Starting Visual Basic


2. The Visual Basic environment
The tool bar
The tool box
The form designer window
The properties window
The project explorer window
The form layout window
3. Creating an application
4. Designing the form
Drawing controls
Moving controls
Resizing controls
Resizing the form
Setting properties
Adding the button controls
5. Running your application
6. Saving your application
7. Exercises

Introduction to the Visual Basic Environment, Forms, Controls and


Properties/1

1.0 Starting Visual Basic


Starting Visual Basic is the same as starting any other Windows application.

Step 1 Launch Visual Basic from the Start menu by choosing Programs;
Microsoft Visual Studio 6.0; Microsoft Visual Basic 6.0

Depending on the environment settings, you may see the New Project dialog box.

[email protected] 2
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-1

Step 2 If the New Project box appears, select Standard.EXE, then click Open.

2.0 The Visual Basic environment


The Visual Basic environment is made up of several windows. The initial appearance of
the windows on your screen will depend on the way your environment has been set up.

Figure 2-1

[email protected] 3
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

The tool bar


The Visual Basic tool bar functions like the tool bar in any other Microsoft application. It
provides shortcuts for many of the common operating commands. It also shows you the
dimensions and location of the form currently being designed.

Figure 2-2

The tool box


The tool box gives you access to the controls that you use on a form.

A control is an object such as a button, label or grid.

Controls are used on forms to display output or get input.

Each control appears as a button in the tool box. If the control you are
looking for is not in the toolbox, select Components from the Project
menu.

If the tool box is not displayed on your screen, or if at any time during the
exercises you close it, choose Toolbox from the View menu.

Figure 2-3

The form designer window


This window is where you design the forms that make up your user interface.

[email protected] 4
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-4

If the form designer window is not displayed on your screen, or if at any time during the
exercises you close it, choose Object from the View menu.

The properties window


A form, and each control on it, has a set of properties which control its characteristics
such as size, position and colour.

The properties window lists all the properties a control has and their value. The default
value of a property can be changed by setting the property value using the properties
window when you design your application or changed by assigning a new value in code
while your application is running.

If the properties window is not displayed on your screen, or if at any time during the
exercises you close it, choose Properties Window from the View menu.

The project explorer window


A project is a collection of the forms and code that make up an application. Each form in
your application is represented by a file in the project explorer window.

[email protected] 5
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-5

A form file contains both the description of the screen layout for the form and the
program code associated with it. If the project explorer window is not displayed on your
screen, or if at any time during the exercises you close it, choose Project Explorer from
the View menu.

The form layout window


Move the form in the screen in this window to set the position of your form when your
application is running.

You may wish to close the form layout window to allow more
space for the properties window. To open the window again,
select Form Layout Window from the View menu.
Figure 2-6

Introduction to the Visual Basic Environment, Forms, Controls and


Properties/2

3.0 Creating an application


There are three steps to creating an application.

1. Design the forms by drawing controls.


2. Set initial property values for the forms and controls.
3. Write code to perform the required tasks.

In the exercise that follows you will create a single form as shown below.

[email protected] 6
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 3-1

The exercise shows you how to add controls to a form and how to set properties at design
time. This first application will not actually do anything until you add code as shown in
chapter 2.

4.0 Designing the form


The form has three controls on it. There is a label which will display the text “Hello” and
two command buttons.

A label control is used to display text.

A command button control enables the user of your application to click on a button when
they require an action to be carried out. You will learn later how to write the code that
will be run when the button is clicked.

Drawing controls
Drawing controls is a two step process. First you need to add the control you want by
double clicking on it in the tool box. Secondly, you need to position and size the control
by clicking and dragging on the form.

Firstly you will create the label which contains the text “Hello”.

Step 3 Move the mouse over the controls in the toolbox until the tool tips indicate
that you have found the label control.

[email protected] 7
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 4-1

Step 4 Double click on the label control button and a label will appear in the
middle of the form.

Figure 4-2

Moving controls
Controls can be moved around a form by dragging them with the mouse.

Step 5 Move the cursor to the label and depress the left mouse button. Keeping
the mouse button depressed, drag the control to its new location, shown in
Figure 4-3.

[email protected] 8
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 4-3

Step 6 Release the mouse button.

Resizing controls
To achieve the form design shown in figure 3-1, you need to make the label control
larger.

Before a control can be resized it must be selected. When a control is selected it will be
surrounded by black dots or handles.

Clicking and dragging one of these handles will adjust the size of the control.

Step 7 Click on the label control to select it.

Figure 4-4

Step 8 Drag the bottom right handle to enlarge the control, then release the
mouse button.

[email protected] 9
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 4-5

Resizing the form


The form can be resized in the same way as a control.

Step 9 Position the mouse pointer over the right hand edge of the form.

The mouse pointer will change to a double headed arrow.

Step 10 Hold down the left mouse button and drag the edge of the form to the left
to make the form smaller.

Setting properties
Once the control is positioned correctly on the form you then need to customise the
properties of the control to suit your requirements.

This application requires you to change the text that is displayed in the label control from
the default “Label1” to “Hello”. You are also going to change the alignment to Centre
and the font to Arial with font size 16.

To change the properties for a specific control, you must have the control selected.

Step 11 Click on the label control on your form to select it.

Handles will appear on the label control to show it is selected.

Step 12 If the properties window is not visible, choose Properties Window from
the View menu or right click on the label control and select Properties.

Check that the Properties window shows the properties for the label
Step 13
control.

[email protected] 10
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 4-6

The Caption property determines what text is displayed in the label control.

Step 14 If the Caption property is not highlighted, click on it to select it. If Caption
is not visible in the list, use the scroll bar on the right to display it.

Step 15 Type Hello in place of Label1

Select the Alignment property and click on the drop down arrow to reveal
Step 16
the choices for this property.

Step 17 Choose ‘2 - Centre’.

Select the Font property and click the dialog button (…) to bring up the
Step 18
font window. Set the font values to Arial, Regular, 16.

Figure 4-7

[email protected] 11
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Adding the button controls


You can use the same process to add two buttons to the form.

Step 19 Double click on the command button control in the tool box.

Figure 4-8

A command button control will appear in the middle of the form.

Step 20 Move the button so that it is under the label.

Step 21 Repeat the last two steps to add a second button under the first.

Your form should appear similar to the one shown in figure 4-9.

Figure 4-9

Step 22 Select the button with the caption Command1. Make sure you can see the
handles that indicate that the button is selected.

Step 23 Using the properties window, change the caption property to On.

Step 24 Use the same process to set the caption for the bottom button to Off.

Step 25 Using the properties window, change the Name property for the form to
Hello.

[email protected] 12
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Introduction to the Visual Basic Environment, Forms, Controls and


Properties/3

5.0 Running your application


Now that the form is complete you can see it in action by running it.

When you have written code for the buttons, running the application will allow you to
activate the code. For now your buttons will not do anything.

Step 26 Click on the start (play) button on the tool bar.

Figure 5-1

Your form will appear like a window from any other Microsoft application.

Step 27 Click on one of the command buttons to see it depress.

Step 28 Click on the Stop button on the tool bar to return to the Visual Basic
design environment.

6.0 Saving your application


The last step in this chapter is to save your application so that you can use it for the
exercises later in the book.

Step 29 Click on the save button on the tool bar.

Figure 6-1

Visual Basic first asks you to save the form and then the project file. Remember that each
represents a separate file.

[email protected] 13
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 6-2

Step 30 Change the directory to the a: drive or to the folder where you want to
save your work.

Specify the filename for the form as hello.frm. The file extension “frm” indicates that the
file is a form file.

Step 31 Click on the Save button.

Figure 6-3

Step 32 Change the name of the project to hello.vbp and click on Save. The file
extension “vbp” indicates a project file.

Always take care to ensure that you save all the files that make up a project.

7.0 Exercises

Exercise 1

1. Open a new project by choosing New Project from the File menu.

[email protected] 14
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2. Design the form shown below. Note that you should set the caption property for
the form to Project One.

3. Change the Name property for the form to frmMain.


4. Change the MousePointer property for the form to ‘2 - Cross’. This is one of the
values in the drop down list for this property.
5. Change the MousePointer property for the command button to ‘1 - Arrow’
6. Run the project and move the mouse across the form to check that the cursor
changes when it is over the command button.
7. Save the project as Project1. (Use the default name of frmMain.frm for the form
filename.
8. Close Visual Basic.

Exercise 2

1. Launch Visual Basic


2. Open the project you saved in Exercise 1.
3. Using the form you created above, add a second button as shown below.

4. Change the MousePointer property for the new button to ‘1 - Arrow’.


5. Save the project using the same file names as before.

Introduction to Events and programming

[email protected] 15
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

1.0 Programming in Visual Basic


1.1 What are events?
1.2 Opening an existing project
2.0 Writing code
3.0 Running your application
4.0 Help for Visual Basic
5.0 Input dialog boxes
6.0 The BackColor property
7.0 Exercises

Events and Programming/1

1.0 Programming in Visual Basic


Now that you have designed a form and set some properties, it is time to make your
application do something.

Visual Basic applications work by executing code written in the Visual Basic
programming language. Code is associated with events.

1.1 What are events?


Each Visual Basic object has a set of events. Events are actions which Visual Basic can
detect and respond to. For example, a user clicking on a command button on a form will
generate a click event for that button.

When an event is generated Visual Basic will run any code you have entered for that
event.

1.2 Opening an existing project


You will now add code to the ‘Hello’ project which you created in the last chapter.

Step 1 Choose Open Project from the File menu.

Step 2 Change to the appropriate drive and folder and open hello.vbp.

[email protected] 16
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-1

The project window will display the file “Hello.frm” from your project.

Figure 2-2

Step 3 If the form is not visible, click the View Object button.

2.0 Writing code


In this exercise you will write code to make your ‘Hello’ label visible and invisible to the
user when the On and Off buttons are clicked.

Each object has an associated set of events which it can respond to. To enter the code,
you must access the code window.

Step 4 Double click on the ‘On’ button or click the right mouse button and select
View Code from the object menu.

[email protected] 17
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-3

The code window will appear as shown below.

Figure 2-4

Click on the Object menu and select Command1 from the list.

The code window has three main components.

1. The object menu allows you to change between controls. For example, you could
use this menu to look at the code for the Off button.
2. The event menu lists all of the available events for the selected control. This list
will change depending on the type of control selected.
3. The code for the event is shown in the main part of the window. Your code will
appear between the Private Sub and End Sub statements.

Step 5 Position the cursor in the blank line between the Private Sub and End Sub
statements.

[email protected] 18
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2.5

Visual Basic 5.0 uses the programming language Visual Basic for Applications, the same
language found in many Microsoft Office applications including Microsoft Excel,
Microsoft Access and Microsoft Project.

The statement you are going to type assigns a value to the Visible property for the label
on your form. This property is set to the value True by default at design time. Your
Visual Basic statement will change the value of the property when the command button is
clicked.

The syntax to refer to a property in code is:

ObjectName.PropertyName

The syntax to assign a value is

ObjectName.PropertyName = Value

Step 6 Press the tab key to indent the line of code and type Label1.Visible =
True, and press the Enter key.

Figure 2.6

Notice that the True has turned blue. This indicates that True is a special word or symbol
that Visual Basic understands. Such words are known as reserved words.

Step 7 Close the code window.

You will now follow the same process to enter the code for the Off button to make the
‘Hello’ label invisible when this button is clicked.

[email protected] 19
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 8 Double click on the Off button to access the code window.

Step 9 Position the cursor between the Private Sub and End Sub statements.

Step 10 Press Tab and type Label1.Visible = False. Press the Enter key.

Step 11 Close the code window.

Events and Programming/2

What the does the code do?


The code under your On button will appear as shown below.

Private Sub Command1_Click ()


Label1.Visible = True
End Sub

Each Visual Basic event has a subprogram associated with it. This is why Visual Basic
automatically includes the Sub and End Sub commands in your code.

The name of the control (in this case Command1) and the event (in this case Click) will
be joined together to form the subprogram name. This name follows the Sub statement.

The line of code that you typed for the On button sets the Visible property of the control
named Label1 to True (to make it visible).

Similarly, the code under the Off button sets the Visible property for the Label1 control
to False (to make it invisible). You can now change the value of the Visible property
while you are running your application.

3.0 Running your application


Now that the code has been written your buttons will operate when you run your
application.

Step 12 Click on the start button on the tool bar to run your application.

[email protected] 20
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

The “Hello” label will initially be displayed because the visible property in the properties
window was set to true.

Step 13 Click on the Off button.

The label will disappear.

Step 14 Click on the On button to make the text visible again.

When you have finished experimenting click on the end button on the tool
Step 15
bar to return to Visual Basic.

4.0 Help for Visual Basic


The Visual Basic environment provides you with a very comprehensive help system. You
should also take advantage of the Microsoft on the Web feature for more detailed
instructions and examples of how to carry out tasks.

Figure 2-7

Events and Programming/3

5.0 Input dialog boxes


In this exercise you will add a third button to the form which will enable the user to
change the text displayed in Label1.

An easy way to get user input, is by using input dialog boxes.

Step 16 Add a third button to your form as shown below.

[email protected] 21
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-8

Step 17 Change the button’s caption to “Change Text”.

Having added the button you can now write the code to make it work.

Step 18 Double click on the new button to display the code window.

Enter the following code. Note that the Sub and End Sub lines will already
Step 19
be entered by Visual Basic.

Private Sub Command3_Click ()


Label1.Caption = InputBox("Enter the new text")
End Sub

Step 20 Close the code window.

What does the code do?


In the same way that you set the Visible property for the Label1 control earlier on in the
exercise, this code sets the Caption property.

The InputBox function displays a dialog box to the user that allows them to enter in a
value. This value is then returned by the function and assigned to the Caption property
for Label1.

Step 21 Run the application to test your changes.

Step 22 Click on the Change Text button.

The input dialog box shown below will appear.

[email protected] 22
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-9

Step 23 Type in your name and click OK.

Your name will now appear as the label on the form.

Step 24 Click on the end button on the tool bar to return to Visual Basic.

6.0 The BackColor property


The finishing touch for your application will be to change the colour of the form to green.

Step 25 Click anywhere in the form itself to select it. Be careful not to click on a
control.

Step 26 In the properties window select the drop down menu for the BackColor
property and select Palette. Remember, if you cannot see the BackColor
property, use the scroll bars to move up or down the list.

The colour palette will appear.

Figure 2-10

Step 27 Click on a green square to set it as the new colour.

The colour of the form will change.

[email protected] 23
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 28 Change the BackColor property for Label1 to a colour of your choice.

Step 29 Run your application to test your changes.

Step 30 Save your project.

Events and Programming/4

Exercises

Exercise 1

1.1 Open a new project by choosing New Project from the File menu.

1.2 Design the form shown below with three labels and one command button.

Figure 2-11

1.3 Write the following code for the click event of the Time button.

Private Sub Command1_Click ()


Label2.Caption = Time
End Sub

1.4 Run your application.

When you click on the time button the current time should appear as shown below.

[email protected] 24
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-12

1.5 Save your application under the names time.frm and time.vbp.

Exercise 2
2.1 Using the form you created above, add a second button and change the Label3
caption as shown below.

Figure 2-13

2.2 Write the following code for the click event for the Date button.

Private Sub Command2_Click ()


Label1.Caption = “The date is:”
Label2.Caption = Date
End Sub

2.3 Add a line of code to the Command1_Click subprogram so that the caption for Label1
is set back to “The time is:” when the Time button is pressed.

2.4 Change the BackColor of the form to a colour of your choice.

2.5 Run your application to test that it is working.

2.6 Save your application files with the names DateTime.frm and DateTime.vbp.

[email protected] 25
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Text, check boxes and buttons

1.0 Text boxes


1.1 Creating a text box
1.2 The Name property
1.3 The Text property
2.0 Adding a label
3.0 Check boxes
3.1 Changing the properties of the check boxes
3.2 Setting the Value property
3.3 Writing the code
3.4 The Italic check box code
4.0 Option buttons
4.1 Setting the Value property
4.2 The code for the option buttons
4.3 Changing the colour of the text box
5.0 Finishing the form
6.0 Programming Notes
7.0 Exercises

Text, check boxes and buttons/1

1.0 Text boxes


In the last chapter you used an input dialog box to get input from the user. In this chapter
you will use a text box control.

You use a text box rather than an input dialog box when you want the user to enter data
directly onto the form.

The text box control defines an area on a form where the user can type text. Visual Basic
automatically responds to the delete and backspace keys, and other text editing functions
such as copy and paste, without the need for any programming.

In this chapter you will create the form shown below which will allow the user to enter
some text and format it.

[email protected] 26
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-1

Firstly open a new project.

Step 1 Choose New Project from the File menu, and select Standard EXE.

1.1 Creating a text box


Adding a text box to a form is exactly the same as adding any other Visual Basic control.

Step 2 Double click on the text box control in the tool box window.

Figure 1-2

Step 3 Click and drag in the text box to move it to where you want it and to make
it larger.

Your text box should appear as shown below.

[email protected] 27
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-3

1.2 The Name property


When you draw a control on a form Visual Basic automatically assigns the control a
name. In this case “Text1”.

The default name is determined by the type of control and the number of those controls
on your form.

The name is used to refer to a control when programming. It is good practice to change
the name to something meaningful to your application. A useful convention is to give the
control name a prefix which indicates the type of control.

You will change this text box control’s Name to txtInput.

Step 4 Check that the Text1 control is selected. It will appear on your form
surrounded by black handles.

Step 5 If the properties window is not visible, click the right mouse button and
select Properties from the object menu.

Click on the Name property in the properties window. If the Name


Step 6
property is not visible, use the scroll bars to display it.

Figure 1-4

[email protected] 28
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 7 Type txtInput as the new name for the control.

You have used the prefix “txt” to show that this control is a text box.

1.3 The Text property


You will notice that the text box on your form still contains the text “Text1”. This text is
the current value of the Text property.

To set the default text to something else, you would change the Text property for the text
box. In this case, you want it to be blank.

Step 8 Check that the txtInput control on your form is selected and click on the
Text property in the properties window.

Figure 1-5

Step 9 Highlight Text1 and press the delete key on your keyboard to delete the
text.

The text should have now disappeared from the control on your form.

2.0 Adding a label


In the previous chapter you used a label to display the text that the user entered. More
commonly labels are used as headings to prompt the user.

You will now create a label to explain the text box.

Step 10 Double click on the label tool in the tool box.

Step 11 Click and drag to create a label in the form, positioned above the text box.

[email protected] 29
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 12 Change the Caption property of the label to Enter your text here:.

Step 13 Use the Font property and change the font size to 14.

Figure 2-1

Having added the text box and label to your form you can run it to see what it looks like.

Step 14 Click on the play button on the tool bar.

Step 15 Type something in the text box.

Step 16 Click on the stop button on the tool bar to return to Visual Basic

Text, check boxes and buttons/2

3.0 Check boxes


The next step is to add check boxes to the form. These will allow the user to change the
format of the text in the text box to bold or italics.

Check boxes are used to represent on/off values. They can either be checked or
unchecked. When they are checked a tick will appear in the box.

Step 17 Double click on the check box control in the tool box.

[email protected] 30
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 3-1

Step 18 Move the check box to an appropriate location.

Step 19 Repeat the last two steps to add a second check box below the first.

Your form will appear like this.

Figure 3-2

3.1 Changing the properties of the check boxes


As with the text box you should now change the names of the check boxes to something
more meaningful.

Step 20 Click on the Check1 check box in your form.

Step 21 Change the Name property to chkBold.

[email protected] 31
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

You will also need to change the caption of the check box. Remember that this is what
appears on the form.

Step 22 Change the Caption property to Bold.

Step 23 Repeat the steps above to change the name of the second check box to
chkItalic and the caption to Italic.

Figure 3-3

3.2 Setting the Value property


The Value property of a check box determines whether the check box is checked,
unchecked or greyed.

Step 24 Click on the Bold check box on your form to select it.

Step 25 Click on the Value property in the properties window.

Step 26 Use the pull down menu to see the possible values for this property.

Figure 3-4

[email protected] 32
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

For now, leave the value property as 0 – Unchecked. You are going to write code so that
if this property has the value one (i.e. the user has checked the box), the font will be bold,
otherwise it will not be bold.

3.3 Writing the code


At this stage the check boxes on the form will not perform any action. To make the
appearance of the text in the text box change when the check boxes are checked and
unchecked you need to write code.

Step 27 Double click on the Bold check box on your form.

The code window will appear.

Step 28 Enter the code shown below. Remember that the Private Sub and End Sub
statements are automatically included by Visual Basic
Private Sub chkBold_Click ()
If chkBold.Value = 1 Then
txtInput.FontBold = True
Else
txtInput.FontBold = False
End If
End Sub

This is shown below.

Figure 3-5

This is an example of the Visual Basic If statement. The If statement in code allows a
choice of actions. The general structure is:

[email protected] 33
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
If expression Then
statements1
Else
statements2
End If

The first line of the If statement in your example tests the current value of the check box.
If the value of the property Value is equal to 1, then the check box is checked.

If the bold checkbox is checked, set the FontBold property of the txtInput control to True.

Otherwise, if the check box value is not 1 (unchecked or inactive), set the FontBold
property of the txtInput control to False.

Run the application to see the result.

Step 29 Click on the play button on the tool bar.

Step 30 Type some text in the text box.

Step 31 Click on the Bold check box to check it.

The text in the text box should be displayed as bold.

Step 32 Click on the Bold check box to uncheck it.

The text in the text box should be displayed as normal.

Step 33 Click on the stop button on the tool bar to return to Visual Basic.

3.4 The Italic check box code


The code for the Italic check box is similar to the Bold check box but changes the
FontItalic property.

Step 34 Double click on the Italic check box.

The code window will appear.

Step 35 Enter the code shown below. Remember that the Private Sub and End Sub
statements are automatically included by Visual Basic.
Private Sub chkItalic_Click ()
If chkItalic.Value = 1 Then

[email protected] 34
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
txtInput.FontItalic = True
Else
txtInput.FontItalic = False
End If
End Sub

Run the application to see the result.

Step 36 Click on the play button on the tool bar.

Step 37 Type some text in the text box.

Step 38 Click on the Italic check box to check it.

The text in the text box should be displayed as italic.

Step 39 Click on the stop button on the tool bar to return to Visual Basic.

Text, check boxes and buttons/3

4.0 Option buttons


Check boxes are used to represent true/false, on/off or yes/no values. Option buttons are
used to give a set of choices. Option buttons are sometimes called radio buttons.

When one option button is selected the others in the set are automatically deselected.

You will now use a set of option buttons on your form to represent three font type
choices for the text box.

Step 40 Double click on the option button control in the tool box.

[email protected] 35
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 4-1

Step 41 Move the option button to an appropriate location.

Step 42 Repeat the steps above to add two more option buttons to your form.

Figure 4-2

Step 43 Change the Name and Caption properties of the option buttons as given
below.

Name Caption
optMSSansSerif MS Sans Serif
optTimesNewRoman Times New Roman
optArial Arial

You may need to resize the option controls so that the caption fits on one line.

[email protected] 36
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 4-3

4.1 Setting the Value property


You will set the initial value of the MS Sans Serif option button to True because this is
the default font type for the text box.

To do this you set the Value property. The possible values are True or False. True
indicates that the option button is selected.

Step 44 Click on the MS Sans Serif option button on your form to select it.

Step 45 Click on the Value property in the properties window.

Step 46 Use the pull down menu in the editing panel to change the value to True
as shown below.

Figure 4-4

4.2 The code for the option buttons


The code for the option buttons sets the FontName property for the text box accordingly.

[email protected] 37
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 47 Double click on the MS Sans Serif option button in your form.

The code window will appear.

Step 48 Enter the code shown below. Remember that the Private Sub and End Sub
statements are automatically included by Visual Basic.
Private Sub optMSSansSerif_Click ()
txtInput.FontName = "MS Sans Serif"
End Sub
Step 49 Repeat this process to enter the code shown below for the Times New
Roman button.
Private Sub optTimesNewRoman_Click ()
txtInput.FontName = "Times New Roman"
End Sub
Step 50 Repeat the process again to enter the code shown below for the Arial
button.
Private Sub optArial_Click ()
txtInput.FontName = "Arial"
End Sub

Run the application to see the result.

Step 51 Type some text in the text box.

Step 52 Click on the Times New Roman option button to select it.

The text in the text box will be displayed in Times New Roman.

Step 53 Try the Arial and MS Sans Serif buttons.

Step 54 Click on the Stop button on the tool bar to return to Visual Basic.

4.3 Changing the colour of the text box


The final task is to change the background colour of the text box when the font changes.
Visual Basic provides names for colour values, for example, vbRed for red, vbGreen for
green and vbBlue for blue.

You need to add a line of code, which assigns a value to the BackColor property of the
text box, to the option button code.

[email protected] 38
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 55 Double click on the MS Sans Serif option button and insert the line
shown:
Private Sub optMSSansSerif_Click ()
txtInput.FontName = "MS Sans Serif"
txtInput.BackColor = vbGreen
End Sub
Step 56 Add code to the Times New Roman button to change the text box colour
to Red and code to the Arial button to change the text box colour to Blue.

Step 57 Try out your application.

Text, check boxes and buttons/4

5.0 Finishing the form


To tidy up the form you will add a title to it and change the size.

Step 58 Click anywhere on the form to select it. Be careful not to click on a
control.

Step 59 Change the Caption property of the form to read Text Formats.

Step 60 Resize the form to a more appropriate size.

The completed form will appear as shown below.

Figure 5-1

[email protected] 39
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 61 Run the application to test the changes.

Step 62 Save the project. Remember to save both the project file and the form.

6.0 Programming Notes

6.1 If statements
Use the If statement when you want to carry out different actions depending on current
values in your application.
The syntax of the If statement can be any of the following:

a) If condition Then statements1


b) If condition Then statements1 Else statements2
c) If condition Then
statements1
End If
d) If condition Then
statements1
Else
statements2
End If
e) If condition Then
statements1
Elseif
statements2
Else
statements3
End If

6.2 Built-In Colour Constants


Visual Basic recognises the following constant names for colours. You can use these
names in your code in place of the actual values.

Constant Value Description


vbBlack 0x0 Black
vbRed 0xFF Red
vbGreen 0xFF00 Green
vbYellow 0xFFFF Yellow
vbBlue 0xFF0000 Blue
vbMagenta 0xFF00FF Magenta
vbCyan 0xFFFF00 Cyan
vbWhite 0xFFFFFF White

[email protected] 40
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

7.0 Exercises

Exercise 1
1.1 Your boss has commissioned you to design the interface for a name tag recording
system.

1.2 Open a new project by choosing New Project from the File menu and design the form
shown below.

Figure 7-1

1.3 Change the name of the text box to txtName.

1.4 Write the code to make the bold and italic check boxes work.

Exercise 2
2.1 Change the Caption of the form to Name Tag Designer and the name of the form to
frmTag.

2.2 Add Times New Roman and Arial option buttons to change the font of the text box.

Figure 7-2

2.3 Write the code to make the option buttons work.

Exercise 3
3.1 Add a command button to the form so when it is clicked, the background colour of
the text box changes to green if it was blue or changes to blue otherwise.

[email protected] 41
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 7-3

(Hint: If txtName.BackColor = vbBlue Then…)

Exercise 4
4.1 Add a command button to the form so that when it is clicked, an input dialog box asks
the user for a font size for the tag.

Figure 7-4

(Hint: txtName.FontSize = InputBox(“Enter a new font size e.g. 14”))

List boxes, combo boxes and forms

1.0 Projects with more than one form


2.0 List boxes
2.1 What is a list box?
2.2 Creating a list box
2.3 The add button
2.4 The Delete button
2.5 The Clear button
2.6 Selecting items from a list
3.0 Combo Boxes
4.0 Programming Notes
4.1 Subprograms

[email protected] 42
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

4.2 Methods
4.3 Displaying Forms
4.4 Summary
5.0 Exercises

List boxes, combo boxes and forms/1

1.0 Projects with more than one form


In this chapter you will create an application in which one form opens a second form. The
opening form, which is called the main form, will include a command button which
activates the second form. The second form allows the user to maintain a list of clients.
When your user is finished with the second form they will return to the main form to
terminate the application.

Step 1 Design a main form to look like the following.

Figure 1-1

Step 2 Change the name of the form to frmWidgets.

Step 3 Change the names of the command buttons to cmdClientList (caption


Client List) and cmdQuit (caption Quit).

Step 4 Add the following code to the Quit button to terminate the application.
Private Sub cmdQuit_Click()
End
End Sub

The next stage will add a second form to the application. At this stage, just an outline
design will be sufficient.

Step 5 Click on the add form button on the toolbar.

[email protected] 43
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-2

Click Form from the display list of available forms and then click Open.

Figure 1-3

The form will be displayed in a separate window. Select the new window so you can see
the form.

Step 6 Design the form to look like the following.

Figure 1-4

Step 7 Change the name of the form to frmClientList and the name of the Close
button to cmdClose.

Step 8 Add this code to the command button.


Private Sub cmdClose_Click()
Unload Me
End Sub

[email protected] 44
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Visual Basic provides the keyword Me as a shortcut to refer to the currently active form.

Step 9 Select View Object for frmWidgets from the Project window.

Figure 1-5

When your user clicks on the Client List button, the second form should become active.
The process of making a form active is a two stage process. It must first be loaded into
memory using the Visual basic subprogram Load. Then it must be made visible using the
method Show.

Step 10 Add the following code for the Client List command button.
Private Sub cmdClientList_Click()
Load frmClientList
frmClientList.Show
End Sub
Step 11 Run your application to check that it works correctly. Use the Quit button
to stop the application running.

Step 12 Save the project. Note that there are now three files to be saved. Use the
Visual Basic default of the form names as the file names for the forms.
Save the project file as Widgets.vbp

The Visual Basic default will mean that the filenames for your form files are
frmClientList.frm and frmWidgets.frm.

List boxes, combo boxes and forms/2

2.0 List boxes


You will now complete the design of the second form.

[email protected] 45
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.1 What is a list box?


A list box is a list, which appears on the screen, from which the user can choose items. In
this chapter you will create the text box and list box shown below and program the add,
delete, clear buttons.

Figure 2-1

The add button will add the contents of the text box to the list. The delete button will
remove the item in the list which the user has selected. The clear button will delete all the
items from the list.

2.2 Creating a list box


Creating a list box is just like creating any other Visual Basic control.

Step 13 Select View Form for frmClientList from the Project window.

Step 14 Double click on the list box control in the tool box.

Figure 2-2

Step 15 Move and size the list box.

[email protected] 46
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-3

Adding the other controls on the form

Step 16 Add a label, text box and three more command buttons to the form, as
shown below.

Figure 2-4

Step 17 Name each of the new controls by selecting the control on your form and
changing the name property in the properties window.

Control Name
Text1 txtInput
List1 lstClientList
Command1 cmdAdd

[email protected] 47
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Command2 cmdDelete
Command3 cmdClear

The controls also require the captions to be changed.

Step 18 Change the Caption properties as shown below.

Control Name
Label1 Enter the name to add:
cmdAdd Add
cmdDelete Delete
cmdClear Clear

Step 19 Clear the Text property of the txtInput control.

Check the appearance of the form at this stage.

Step 20 Click on the play button on the tool bar. Click on the Client List button.
The second form should then appear as shown below.

Figure 2-5

Step 21 Click on the Close and Quit buttons once you have checked your form.

[email protected] 48
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.3 The add button


The Add button will add what the user has entered in the text box into the list.

Step 22 Double click on the Add button on your form to display the code window.

Step 23 Enter the code shown below. Remember that the Private Sub and End Sub
statements will have been entered for you by Visual Basic.
Private Sub cmdAdd_Click ()
lstClientList.AddItem txtInput.Text
txtInput.Text = ""
txtInput.SetFocus
End Sub

The first line of the code adds an item to the list box (remember the name of the list box
is lstClientList). The item which is added is the current value of the Text property of the
txtInput control. This will be what the user has entered into the text box.

The next line resets the Text property of the text box to a blank string, ready for the next
entry by the user.

The last line repositions the cursor inside the text box so the user can begin typing the
next entry.

Step 24 Run the application to test the Add button code.

Step 25 Type your name as the first client to add to the list.

Step 26 Click on the Add button.

Your name should appear in the list box and the text box should appear empty. The
cursor will be positioned in the text box ready for the next entry.

[email protected] 49
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-6

Step 27 Use the Close and Quit buttons on your forms to stop the application when
you have finished.

2.4 The Delete button


The Delete button will delete the item that the user has selected in the list box from the
list.

Step 28 Double click on the Delete button on your form to display the code
window.

Step 29 Enter the code shown below. Remember that the Private Sub and End Sub
statements will have been entered for you by Visual Basic.
Private Sub cmdDelete_Click ()
If lstClientList.ListIndex >= 0 Then
lstClientList.RemoveItem lstClientList.ListIndex
Else
Beep
End If
End Sub

The code uses an If statement to test whether the user has selected an item in the list.

The ListIndex property for the lstClientList control holds a number indicating which item
in the list has been selected by the user.

If ListIndex is zero then the first item in the list is selected. If ListIndex is equal to one
then the next item in the list is selected and so on.

[email protected] 50
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

If ListIndex is less than zero it means that nothing is selected.

If something is selected the next line of the code will remove it from the list. Visual Basic
will remove the item at list position lstClientList.ListIndex.

If nothing is selected a Beep is sounded.

You should run the application to test the Delete button code.

Step 30 Click on the play button on the tool bar and click the Client List button.

Firstly, test to see what happens if you click the Delete button when the list is empty.

Step 31 Click the Delete button.

A beep should sound to indicate that nothing in the list is selected for deletion. The action
should not result in an error message.

Next, test that the Delete button correctly deletes list items.

Step 32 Add several items to the list by entering them in the text box and clicking
on the Add button.

Figure 2-7

Step 33 Click on one of the items to select it.

The item you select will become highlighted.

Step 34 Click on the Delete button.

[email protected] 51
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

The item will be removed from the list.

Step 35 Try selecting and deleting the other list items.

Step 36 Stop the application running when you have finished testing.

2.5 The Clear button


The Clear button will delete all of the items in the list.

Step 37 Double click on the Clear button on your form to display the code
window.

Step 38 Enter the code shown below. Remember that the Private Sub and End Sub
statements will have been entered for you by Visual Basic.
Private Sub cmdClear_Click ()
lstClientList.Clear
End Sub

The code uses the Clear method to delete all the items from the list.

Run the application to test the Clear button code.

Step 39 Click on the play button on the tool bar. Click on Client List.

Step 40 Add several items to the list using the Add button.

Step 41 Click on the Clear button.

All of the items in the list will be deleted.

Step 42 Stop the application running.

Step 43 Save the project.

2.6 Selecting items from a list


The following example demonstrates how to use a list box to allow your user to make a
selection from the list.

The items in this list box example are added at design time.

[email protected] 52
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 44 Start a new project.

Step 45 Add a list box to the form. Change its name to lstFruits.

Step 46 Select the List property for the list box and click on the drop down arrow.

Step 47 Type apples then press Ctrl Enter

Step 48 Type the other fruit names shown pressing Ctrl Enter after each one.

Figure 2-8

Step 49 If you cannot see the full list of fruit in the list box on your form, make the
list box larger.

Step 50 Add a label with the caption shown and a text box to your form as in
figure 2-9.

Step 51 Change the name of the text box to txtSelection.

Figure 2-9

[email protected] 53
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

The List property returns the contents of the list for the specified index.

Step 52 Add the following code to the click event for the list box.
Private Sub lstFruits_Click()
txtSelection.Text = lstFruits.List(lstFruits.ListIndex)
End Sub
Step 53 Run the application and test that clicking on an item in the list box will
cause it to be displayed in the text box.

Step 54 Stop the application.

List boxes, combo boxes and forms/3

3.0 Combo Boxes


The combo box control is a combination of a list box and a text box. Items are stored in a
list and viewed using a drop down menu.

The contents of the Text property of the combo box is displayed at the top of the combo
box.

Step 55 Start a new project.

Step 56 Add a combo box to the form.

[email protected] 54
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 3-1

Step 57 Using the List property, add the items Potatoes, Carrots, Peas and Beans
to the list.

Step 58 Run the application. Click on the drop down arrow for the combo box and
select one of the items.

The Text property of the combo box is set to the selected item and it will be displayed.

Step 59 Stop the application.

Combo boxes also allow your user to type in a value to set the text property while the
program is running. This can be useful if the user needs a value that is not in the list.

4.0 Programming Notes

4.1 Subprograms
A subprogram is a block of code which is activated by an event or called from another
block of code.

The syntax to call a subprogram is:

SubprogramName [parameters]

or

Call SubprogramName[(Parameters)]

[email protected] 55
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Examples of subprograms provided by Visual Basic are Load, Unload and End.

4.2 Methods
A method is a subprogram which acts on an object.

The syntax to use a method is:

object.method [parameters]

Examples of methods are:

 Show for a form e.g. frmMain.Show


 AddItem for a list or combo box e.g. lstFruits.AddItem “Pineapple”
 SetFocus for any object e.g. cmdQuit.SetFocus

4.3 Displaying Forms


Each form must first be loaded into memory and then made visible.

The main form of a project is automatically loaded into memory and made visible when
the project starts running.

For other forms, statements to Load them and Show them must be executed. For
example:

Load Form2
Form2.Show

If you have forms which you want to open and close frequently, you can avoid the
overhead of loading them into memory each time by loading them once then using the
Show and Hide methods to make them available when required.

Each form has a load event and you can put code here to initialise values. The load event
for the main form is a good place to load other forms.

Private Sub Form1_Load()


Load Form2
Load Form3
End Sub

When you want Form2 to become visible, use the statement:

[email protected] 56
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Form2.Show

When you want Form2 to be invisible, use the statement:

Form2.Hide

4.4 Summary
Load is a Sub (subprogram) which loads the specified form into memory. Note that it
doesn’t necessarily make the form visible. (Load is also an event for a Form).

Show is a method which loads the specified form into memory if it isn’t already loaded
and makes it visible.

Unload is a Sub which unloads the specified form from memory.

Hide is a method which makes a form invisible but doesn’t unload it from memory.

Me is a convenient way of referring to the current form.

End is a subprogram which terminates the currently running project and unloads all its
forms.

5.0 Exercises

Exercise 1
1.1 Open a new project by choosing New Project from the File menu.

1.2 Design the form shown below. Change the Name property to frmDemo. Add code to
the QUIT button to stop the application running.

Figure 5-1

[email protected] 57
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

1.3 Click on the Add Form button and then on the existing tab to add the form
frmClientList, which you saved earlier in the chapter, to this project.

1.4 Add code to frmDemo to access frmClientList when the List Box button is clicked.

Exercise 2
2.1 Choose Add Form from the Project menu or click the Add Form button on the toolbar
to add a new form to your project. Change the name property to frmComboDemo.

2.2 Design the form to look like the following. Set the Style property differently for each
combo box.

2.3 Add the items: eggs, butter and ham to the lists for each combo box.

Figure 5-2

2.4 Add code to the Combo Box button in frmDemo to activate frmComboDemo.

2.5 Save the project as Ch4Demo.

Graphics and simple animation

1.0 Using graphics in Visual Basic


1.1 The coordinate system
2.0 The image control
2.1 The Stretch property

[email protected] 58
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.2 Making the traffic light change colours


2.3 The Picture property
2.4 Writing the code
2.5 Moving an image control
2.6 Resetting the form width
2.7 The code to move the car
2.8 Running the code
3.0 Programming Notes
3.1 Data Types in Visual Basic
3.2 Declaring variables in Visual Basic
3.3 The Case statement
3.4 Statements for repetition
4.0 Exercises

Graphics and simple animation/1

1.0 Using graphics in Visual Basic


Visual Basic allows you to include graphics easily in your application. Graphics can be
used to add visual impact to a form, or as part of an application itself.

You can use the line and shape controls to add graphics to your forms or methods such as
circle and pset to draw shapes while your application is running.

The simplest way to add graphics to a form is to use the image or picture box controls to
display a picture or icon.

In this chapter you will use image controls to display pictures and create simple
animation by changing the pictures displayed in the control and by moving the control
across the screen.

Figure 1-1

The Change button will change the colour of the traffic light. When the traffic light
appears green the car will move across the screen.

[email protected] 59
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 1 Open a New Project to begin.

Step 2 Change the Name property of the form to frmCar.

Step 3 Add a command button control to your new form.

Change the button Caption to Change and the Name to cmdChange using
Step 4
the properties window.

1.1 The coordinate system


Positioning and sizing graphical objects on a form often requires that you are aware of
the coordinates of the drawing area. By default, the convention for the coordinate system
of a form is as shown.

Figure 1-2

The default unit of measurement is the twip (one twentieth of a printer’s point). You will
probably find it easier to work in units that you are more familiar with.

Step 5 Change the ScaleMode property for the form to ‘7-centimeters’.

Graphics and simple animation/2

2.0 The image control


An image control is used to display a graphical image such as a bitmap or an icon.

Step 6 Double click on the image control in the tool box.

[email protected] 60
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-1

Step 7 Move the control to just under the button.

Figure 2-2

This will be the image control in which the traffic light is displayed.

Change the caption of the form to The Moving Car.

Step 8 Change the Height and Width properties for the image control to 2.

Step 9 Change the Name property of the image control to imgLight.

2.1 The Stretch property


When the value of this property is false, the control is resized to fit the picture loaded into
it. When the value is true, the picture resizes proportionally to fit the size of the control.
This gives you much more control over the appearance of your graphics on the form.

[email protected] 61
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 10 Set the Stretch property of the image control to true.

2.2 Making the traffic light change colours


There are several possible ways of changing the colour of the traffic light.

The method you will use is described below.

First, you will add another three image controls to your form. One to hold the traffic light
picture for each possible light colour. The Visible property for these will be set to false so
that they cannot be seen when the application is running.

Second, you will program the Change button to change the picture displayed in the
imgLight image control to the next appropriate picture by setting the Picture property of
the imgLight control equal to the Picture property of the correct traffic light image
control.

Step 11 Add three more image controls to your form.

Figure 2-3

These controls must be the exactly the same size as imgLight for the animation to look
convincing.

Make sure that the pointer button on the toolbar is depressed and using the
Step 12
mouse, drag a rectangle around the three new image controls.

The three controls are now selected and the properties window can be used to set
properties for all three at the same time.

Step 13 Set the Stretch property to True and the Height and Width properties to 2.

[email protected] 62
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 14 Change the Visible property to False.

Step 15 Click on the form away from the selected controls to deselect the group.

Change the Name property for the new image controls to imgGreen,
Step 16
imgYellow, and imgRed.

The next step is to set each of the image controls to display the appropriate traffic light
picture.

2.3 The Picture property


To set the picture which the image controls are to display, use the Picture property at
design time.

Step 17 Check that the image control, imgGreen, is selected on your form.

Step 18 Click on the Picture property in the properties window.

Step 19 Click on the dialog button (…) to choose the picture.

The standard Windows file dialog window will open. The window is used to select the
picture file.

Step 20 Change the folder to pcskills\Icons\Traffic.

Figure 2-4

Step 21 Click on trffc10a.ico in the file list to select it, and click on Open.

The image control will now display a picture of a traffic light set to green.

[email protected] 63
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Change the Picture property of the other image controls as shown below.
Step 22
The picture files are located in your class folder.

Image control Picture file


imgYellow Trffc10b.ico
imgRed Trffc10c.ico

Your form will appear like that shown below.

Figure 2-5

Run the form to see the result. At this point, you should only see the
Step 23
change button on screen.

Step 24 Click stop on the tool bar to return to Visual Basic.

2.4 Writing the code


You need to load one of the light images into the imgLight control when your program
starts running. The yellow light would be appropriate.

The Load event for your form would be a suitable place to carry out this action.

Step 25 Double click on the form and add the following code to the Load event.
Private Sub Form_Load()
imgLight.Picture = imgYellow.Picture
End Sub

The next step is to write the code which will change the picture displayed in imgLight
when the Change button is clicked.

[email protected] 64
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Double click on the Change button on your form to display the code
Step 26
window.

Step 27 Enter the code shown below.


Private Sub cmdChange_Click()
Select Case imgLight.Picture
Case imgGreen.Picture
imgLight.Picture = imgYellow.Picture
Case imgYellow.Picture
imgLight.Picture = imgRed.Picture
Case imgRed.Picture
imgLight.Picture = imgGreen.Picture
End Select
End Sub

The code uses a case statement which allows you to enter a number of possible options.
The case statement compares the Picture property of the imgLight control to the Picture
property for each of the other picture box controls.

When it finds one that matches, the code sets the Picture property of the imgLight
control to the next appropriate picture.

Run your application to test it.

Step 28 Click on the play button on the tool bar.

The light should be yellow.

Step 29 Click on the Change button.

The light will change to red.

Step 30 Click on the Change button to see the other colours.

Step 31 Click on the stop button on the tool bar to return to Visual Basic.

2.5 Moving an image control


In the exercise which follows you will add the car to the form. The car will move across
the form when the light changes to green.

You want the car to appear initially at the right of the form and move across until it is out
of sight at the left of the form.

[email protected] 65
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Drag the right edge of the form out to increase the size of the form as
Step 32
much as you can.

Add another image control to your form at the right hand edge as shown
Step 33
below.

Change the Name property to imgCar and set the Stretch property to
Step 34
True.

Step 35 Set the Picture property to pcskills/car.bmp.

Step 36 Size the image control until you have the car shape of your choice.

Your form should appear similar to that shown in the figure below.

Figure 2-6

2.6 Resetting the form width


You will now resize the form so that the car is not displayed when the form is initially
run.

Step 37 Drag the right hand border of the form back so that the car is hidden.

2.7 The code to move the car


The final step is to write the code to move the car. The technique for moving the car is to
change the Left property of imgCar by subtracting a small value from its current value. If
this is done in a loop, the car will appear to move across the form.

There are many programming constructs for loops in Visual Basic. This example uses a
While loop which terminates when the car reaches the left hand side of the form.

The syntax is:

[email protected] 66
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Do While condition
statements
Loop

The code to move the car should be executed as soon as the traffic light picture changes
to green.

Double click on the Change button and modify the code as shown. The
Step 38
new code is shown in bold.
Private Sub cmdChange_Click()
Select Case imgLight.Picture
Case imgGreen.Picture
imgLight.Picture = imgYellow.Picture
Case imgYellow.Picture
imgLight.Picture = imgRed.Picture
Case imgRed.Picture
imgLight.Picture = imgGreen.Picture
Do While imgCar.Left > 0
imgCar.Left = imgCar.Left - 0.01
Loop
End Select
End Sub

The statement in the while loop moves the image control to the left 0.01 cm.

Step 39 Run the application.

You will note that once the car has reached the left hand side of the form, changing the
traffic lights has no further effect. For the car to move again, it should be repositioned at
the right hand side of the form. In order to do this, you need to restore the original value
of the Left property for imgCar.

The following steps show how to store the original value in a variable and use it to
restore the car to its original position.

Step 40 Stop the application.

Step 41 Double click the Change button and modify the code as shown.
Private Sub cmdChange_Click()
Dim Original As Single
Select Case imgLight.Picture
Case imgGreen.Picture
imgLight.Picture = imgYellow.Picture
Case imgYellow.Picture
imgLight.Picture = imgRed.Picture
Case imgRed.Picture
imgLight.Picture = imgGreen.Picture
Original = imgCar.Left

[email protected] 67
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Do While imgCar.Left > 0
imgCar.Left = imgCar.Left - 0.01
Loop
imgCar.Left = Original
End Select
End Sub

The first line of the code dimensions (or declares) a variable. Variables are used to store
information while your program is running.

The Dim statement gives the variable a name and states the type of information which
will be stored in it. For this example, the variable will be used to store the value of the
original imgCar Left property. This is measured in centimetres and will probably not be
a whole number so the data type Single is used.

The second new line of code assigns the left hand position of the image control to the
variable Original. This is so that you can reset the image control to its original position
once it has moved across the screen.

Last, the car image control is repositioned back to its original location using the Original
variable that was set before the loop.

2.8 Running the code

Step 42 Click on the play button on the tool bar to run your code.

Step 43 Click on the Change button on the form until the light appears green.

The car should move across the form.

Click on the Change button on the form until the light appears green
Step 44
again.

The car should move across the form again.

Step 45 Click on the stop button on the tool bar to return to Visual Basic.

Step 46 Save your project as Car.frm and Car.vbp.

Keep your saved project in a safe place. You will need it for the following exercises.

[email protected] 68
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Graphics and simple animation/3

3.0 Programming Notes

3.1 Data Types in Visual Basic


The following fundamental data types are available:

Storage
Data Type Range Suffix
Size
Integer 2 bytes -32,768 to 32,767 %
Long (long integer) 4 bytes -2,147,483,648 to 2,147,483,647 &
Single(single- -3.402823E38 to -1.401298E-45 for negative
precision floating- 4 bytes values; 1.401298E-45 to 3.402823E38 for !
point) positive values.
1.79769313486232E308 to 4.94065645841247E-
Double(double-
324 for negative values; 4.94065645841247E-
precision floating- 8 bytes #
324 to 1.79769313486232E308 for positive
point)
values.
-922,337,203,685,477.5808 to
Currency 8 bytes &
922,337,203,685,477.5807.
1 byte per
String 0 to approximately 65,500 bytes $
character
Any numeric value up to the range of a Double or
Variant
any character text

3.2 Declaring variables in Visual Basic

Variable names:

 must start with a letter


 the remaining characters can be a-z, A-Z, 0-9, _, up to 40 characters
 are not case sensitive
 can have a suffix shown in the above table as the last character
 must not be a reserved word viz. names of properties, events, methods, operators,
statements, functions

[email protected] 69
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Note that for compatibility with earlier Basics, Visual Basic allows you to use variables
without declaring them first. As you know from other programming courses, this is a
dangerous practice. Most Visual Basic projects use the statement Option Explicit in a
code module to force the use of declarations. Alternatively, set the appropriate option in
the Project Environment from the Options menu.

There are several different ways to declare variables in Visual Basic, many are provided
for compatibility with other Basics e.g. DefInt or the use of the suffixes shown in the
table above to force a type on a name.

The format you should use for declaring variables is:

DIM variable name AS datatype

The location of the declaration determines its scope. A declaration in an event Sub or
Function means that the variable is local to that Sub or Function. The value of the
variable is not retained between function calls.

If you want the variable to retain the value which it last had, use the STATIC keyword
for the declaration e.g.

STATIC variablename AS datatype

A declaration made in the declarations section of a Form makes the variable available to
all the code associated with that form.

A variable which you want to make available to the entire project must be declared in a
Code Module using the format:

PUBLIC variablename AS datatype

3.3 The Case statement


Use this statement, rather than If Then Elsif, for situations where you have more than 2
choices of action. The syntax is:

a) SELECT CASE expression


CASE value1: statements
CASE value2: statements
.
CASE valuen: statements
END SELECT

b) SELECT CASE expression


CASE value1

[email protected] 70
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
statements
CASE value2
statements
CASE valuen
statements
END SELECT

c) SELECT CASE expression


CASE value1: statements
CASE value2: statements
.
CASE ELSE: statements
END SELECT

d) SELECT CASE expression


CASE value1:
statements
CASE valuen:
statements
CASE ELSE:
statements
END SELECT

3.4 Statements for repetition:

a) the FOR loop


FOR counter = startvalue TO stopvalue [STEP increment]
statements
NEXT counter

b) the WHILE loop


WHILE condition
statements
WEND

c) the DO loop
DO WHILE condition
statements
LOOP

DO UNTIL condition
statements
LOOP

DO
statements
LOOPWHILE condition

DO
statements
LOOP UNTIL condition

[email protected] 71
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Exiting prematurely from loops (only for use in emergencies!)

EXIT FOR
EXIT WHILE
EXIT DO
EXIT FUNCTION

4.0 Exercises

Exercise 1
1.1 Open the Car project and add another image control to the form. Change the Name
property to imgCarStop. Set the Stretch property to True, the Visible property to False
and the Picture property for the new control to Car2.bmp.

1.2 Size the new control so that it is roughly the same size as the imgCar control.

1.3 Select ‘Save As File’ from the File menu. Save the form as CarStop.frm. Select
‘Save As Project’ and save the project as CarStop.vbp.

1.4 Modify the code for the Change button so that instead of returning the car to the
original position after the while loop, the imgCarStop picture is copied into the imgCar
Picture property.

Your application should look like the following when the car stops moving.

Figure 4-1

Exercise 2
In this exercise you will modify the existing Change button code so that the car appears
to skid to a halt.

1.1 Using the form you created above, modify the condition in the while loop so that the
loop terminates when the car is less than 3 cm from the left hand side of the form.

[email protected] 72
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

1.2 Run the application to check your progress.

Figure 4-2

1.3 Copy the while loop and paste it after the imgCar.Picture = imgCarStop.Picture
statement.

1.4 Change the condition so that this loop terminates when the car reaches the left hand
side of the form.

1.5 Run the application to check your progress.

The image control will move more slowly if the distance it is moved is smaller.

1.6 Change the distance moved in the second loop so that the skidding sequence appears
slower.

1.7 Save the project.

Timers, scroll bars, picture boxes and message boxes

1.0 The Timer Control


1.1 Starting and stopping a timer control
1.2 Designing the Clock application
2.0 Using a timer to control animation
2.1 Reusing an existing form
2.2 Controlling the traffic lights
2.3 Controlling the car movement using a Timer
2.4 Constants
3.0 Scroll Bars
4.0 The Picture Box Control

[email protected] 73
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

4.1 Layering
5.0 Message Boxes
5.1 Return Values
6.0 Exercises

Timers, scroll bars, picture boxes and message boxes/1

1.0 The Timer Control


A timer control allows you to generate events at specified time intervals. For example,
you could build your own version of the Windows Clock application by displaying the
time in a label and using a timer control to update the display every second. Your
application might look like the following:

Figure 1-1

1.1 Starting and stopping a timer control


A timer is started by setting the Enabled property to TRUE and giving the Interval
property a value greater than 0.

The timer can be stopped while the application is running by setting the Enabled
property to FALSE or setting the Interval property to 0.

1.2 Designing the Clock application

Step 1 Start a new project and add two labels with Name property set to lblTime
and lblDate respectively. Change the FontName for the labels to Courier
New (a non-proportional font) and choose a suitable FontSize for each
label. Change the caption of the form to Clock.

Step 2 Add a Timer Control to the form. It doesn’t matter where you put this
control because it is invisible when the project is running.

[email protected] 74
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-2

Step 3 Select the Properties window for the Timer Control and set Enabled to
True and the Interval property to 1000.

The units for the interval are milliseconds. With these settings, the code in the event
Timer1_Timer will be executed approximately every second.

Step 4 Add the following event procedure code and try out your application.
Private Sub Form_Load()
lblDate.Caption = Date
End Sub

Private Sub Timer1_Timer()


lblTime.Caption = Time
End Sub

Timers, scroll bars, picture boxes and message boxes/2

2.0 Using a timer to control animation


You can use the event that a timer control generates to move an image across the screen
or change the picture currently displayed in an Image control. The following example
shows you how to adapt the Car and Traffic Light application which you developed in
chapter 5.

2.1 Reusing an existing form


The following sequence shows you how to add an existing form to a new project.

[email protected] 75
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 5 Open a new project.

Step 6 Select Add Form from the Project menu, or click on the icon, and add the
file Car.frm which you saved earlier.

You are going to change this form so it would be appropriate to save the form with a
different file name.

Step 7 Make sure that Car.frm is highlighted in the Project window and select
Save As from the File menu.

Step 8 Save the form as frmCarTimer.frm. Save the project as CarTimer.vbp

You now need to make this form the start up form and get rid of the form Form1 which
you do not need.

Step 9 Select Project Properties from the Project menu and click the General tab.

Figure 2-1

Step 10 Select frmCar and click on OK.

Finally you need to remove the form, Form1.

Step 11 Highlight Form1 in the Project window and select Remove Form1 from
the Project menu.

2.2 Controlling the traffic lights

[email protected] 76
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 12 Add a Timer Control to the form. Name the timer tmrLights.

Step 13 Cut the code from the cmdChange_Click event and paste it into the
tmrLights_Timer event.

Step 14 Amend the code so it looks like


Private Sub tmrLights_Timer()
Select Case imgLight.Picture
Case imgGreen.Picture
imgLight.Picture = imgYellow.Picture
Case imgYellow.Picture
imgLight.Picture = imgRed.Picture
Case imgRed.Picture
imgLight.Picture = imgGreen.Picture
End Select
End Sub

Step 15 Change the Name property for cmdChange to cmdStartLights and the
Caption property to Start Lights.

Step 16 Add another command button to the form to be used for stopping
tmrLights. Set appropriate values for the Name and Caption properties

Figure 2-2

Step 17 Set the Interval property of the Timer to 1000 and the Enabled property to
FALSE.

Step 18 Add code to the Click events for the Command Buttons as follows
Private Sub cmdStartLights_Click()
tmrLights.Enabled = TRUE
End Sub

Private Sub cmdStopLights_Click()


tmrLights.Enabled = FALSE
End Sub

[email protected] 77
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 19 Run the application.

When you click the Start Lights button, the traffic lights should start to cycle through
their colour changing sequence at approximately 1 second intervals.

2.3 Controlling the car movement using a Timer


The code which you wrote in chapter 5, uses a loop to move the car a specified number of
times. You can not synchronise the movement of the car with the traffic lights using this
method because it is difficult to break into the loop to stop the car.

A better method is to use a Timer Control and to move the car in the timer event. You can
then stop the car when you need to by disabling the timer. The following example shows
how to use a second timer so that the car starts when the lights go green and stops when
the lights go red.

The speed at which the car moves depends on the timer interval and the distance the
image control is moved. You will need to experiment with these values to get the best
effect.

2.4 Constants
Values that you think might need to be changed in the future should be declared as
constants so that you only need to change the value once, no matter how often you use it
in the project. The syntax for a constant is:

CONST name = value

Step 20 Open the code window and select Declarations for the General object.

Figure 2-3

[email protected] 78
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Constants declared in the Declarations section of a form are only available to that form.

Add the following declarations for the General Object

Option Explicit
Const LightsInterval = 1000
Const CarInterval = 100
Const Distance = 0.1

Step 21 Add a second timer to your form. Name it tmrCar. Set the Enabled
property to FALSE. Amend the Form_Load, tmrLights_Timer and
cmdStopLIghts event procedures as shown:
Private Sub Form_Load()
imgLight.Picture = imgYellow.Picture
tmrCar.Interval = CarInterval
tmrLights.Interval = LightsInterval
End Sub

Private Sub tmrLights_Timer()


Select Case imgLight.Picture
Case imgGreen.Picture
imgLight.Picture = imgYellow.Picture
Case imgYellow.Picture
imgLight.Picture = imgRed.Picture
tmrCar.Enabled = False
Case imgRed.Picture
imgLight.Picture = imgGreen.Picture
tmrCar.Enabled = True
End Select
End Sub

Private Sub cmdStopLights_Click()


tmrLights.Enabled = False
tmrCar.Enabled = False
End Sub

Add code to the tmrCar event procedure:

Private Sub tmrCar_Timer()


imgCar.Left = imgCar.Left - Distance
End Sub
Step 22 Run the application. Click the button to start the timer for the lights and
check that the car stops when the lights change to red.

Step 23 Save the project as CarTimer.

[email protected] 79
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Timers, scroll bars, picture boxes and message boxes/3

3.0 Scroll Bars


The speed of the animation in the previous example is controlled by the timer interval
and by the distance which the image control is moved.

The Scroll Bar control will provide you with a convenient way to change these values so
that you can experiment with the animation while the application is running.

Figure 3-1

Step 24 Add two horizontal scroll bar controls to your form with appropriate
labels as shown.

Figure 3-2

[email protected] 80
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 25 Change the properties for the scroll bars as shown:


HScroll1: (Clock Interval)
Name = hsbInterval
Large Change = 100
Small Change = 50
Min = 50
Max = 500
HScroll2: (Distance)
Name = hsbDistance
Large Change = 10
Small Change = 1
Min = 1
Max = 100

Note that the property values for changing scroll bars must be integer so the actual
distance value must be calculated in the code.

The distance and interval are going to be changed while the application is running. The
change in interval can be stored directly in the tmrCar.Interval property. You will need
to declare a variable in which to store the distance.

Step 26 Amend the General Declarations for the form as follows


Option Explicit
Const LightsInterval = 1000
Const InitialCarInterval = 100
Dim Distance As Single
Step 27 Amend the Form_Load event code as follows
Private Sub Form_Load()
imgLight.Picture = imgYellow.Picture
Distance = 0.1
tmrCar.Interval = InitialCarInterval
' set the scroll bars to the initial values
hsbDistance = Distance * 100
hsbInterval = tmrCar.Interval
End Sub

The line of code beginning with ‘ is a comment.

Step 28 Add code to the change events for the scroll bars to change the appropriate
values when the scroll bar changes.
Private Sub hsbDistance_Change()
Distance = hsbDistance.Value / 100
End Sub

Private Sub hsbInterval_Change()


tmrCar.Interval = hsbInterval.Value
End Sub
Step 29 Save the form as frmCarTimer1.frm (click File, Save frmCarTimer.frm
as from the main menu). Save the project as CarTimer1.vbp. Run the

[email protected] 81
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

application and try out the scroll bars.

It would be useful to see the value that the scroll bar is currently set to.

Step 30 Add a small label at the end of each scroll bar and name them lblDistance
and lblInterval.

Step 31 Add the following code to the scroll bar change events.
Private Sub hsbDistance_Change()
Distance = hsbDistance.Value / 100
lblDistance.Caption = Distance
End Sub

Private Sub hsbInterval_Change()


tmrCar.Interval = hsbInterval.Value
lblInterval.Caption = hsbInterval.Value
End Sub
Step 32 Save the form as frmCarTimer2.frm (click File, Save frmCarTimer.frm
as from the main menu). Save the project as CarTimer2.vbp. Run your
application and experiment with various intervals and distances.

Figure 3-3

Step 33 Save the application.

Timers, scroll bars, picture boxes and message boxes/4

[email protected] 82
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

4.0 The Picture Box Control


The following table gives a brief comparison of the Image control and the Picture Box
control.

Image Picture Box


Displaying Graphics (*.bmp,
Main Displaying Graphics (*.bmp, *.ico, *.wmf *.ico, *.wmf files).
Purpose files) Acting as a container for user-
drawn graphics.
Uses fewer and repaints faster than Picture
Use of
Box. Because of this, Image controls are
Resources
often better for animation.
AutoSize: automatically resizes
Useful Stretch: scales the graphic to the new size
the Picture Box control to fit the
Properties of the Image control if you change its size.
graphic.

The main difference between the image controls and picture boxes is that, like forms,
picture boxes can be used as containers for graphics.

The following example sets up a simple animation in a picture box.

Step 34 Open a new project. Name the form frmFlying. Save the form as
frmFlying.frm and the project as Flying.vbp

Step 35 Set the Picture property of the form to the picture clouds.bmp which you
will find in the pcskills folder.

Step 36 Add a picture box to the form. Name it picFlying and set its Picture
property to Clouds.bmp also

Figure 4-1

[email protected] 83
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 37 Click the image control button on the toolbox. Click and hold the left
mouse button inside the picture box and drag to create a small image
control.

Figure 4-2

Step 38 Name the image control imgPlane and set the picture property to the icon
plane.ico which you will find in the Icons folder under Industry.

Step 39 Add two command buttons to the picture box with names cmdFly and
cmdGoBack. Give them the captions shown (Fly and GoBack
respectively).

Figure 4-3

Step 40 Add code for the buttons as follows.


Private Sub cmdFly_Click()
Do While imgPlane.Left < picFlying.Width
imgPlane.Left = imgPlane.Left + 3
imgPlane.Top = imgPlane.Top + 1
Loop
End Sub

Private Sub cmdGoBack_Click()


Do While imgPlane.Left > 0

[email protected] 84
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
imgPlane.Left = imgPlane.Left - 3
imgPlane.Top = imgPlane.Top - 1
Loop
End Sub

The units of measurement are the default, twips, and the coordinates are now relative to
the picture box rather than the form.

Step 41 Try out the application.

Step 42 Save the project as Flying.

4.1 Layering
The form you have just created uses layering.

There are three graphical layers associated with forms and picture boxes.

The back layer is the drawing space, where the results of code drawn graphics methods
appear.

Next is the middle layer where graphical controls and labels appear.

The front layer is where all non-graphical controls like command buttons, check boxes,
and file controls appear. Anything in one layer covers anything in the layer behind. You
can create interesting forms by layering controls, image or picture boxes.

Timers, scroll bars, picture boxes and message boxes/5

5.0 Message Boxes


Message boxes provide a quick way to communicate with your user via a pop up box.

The subprogram MsgBox can be used either as a sub program or as a function which
returns a value which tells you which button your user has clicked.

The parameters are:

[email protected] 85
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

MsgBox prompt, buttons, title

Step 43 Save the form as frmFlying1.frm and then save the project as
Flying1.vbp. Put an image control, named imgMe and with Picture
property set to face03.ico from the Misc folder in the Visual Basic icons.
Add a label with caption Click Me! as shown.

Figure 5-1

Step 44 Add code to the imgMe_Click event.


Private Sub imgMe_Click()
MsgBox "Thanks for clicking on me", vbInformation, "Info
Message"
End Sub

The constant vbInformation is provided by Visual Basic and determines the type of icon
displayed in the message box.

The full list of constants is given below at the end of this section.

Step 45 Add a quit button (named cmdQuit) with the code shown to your
application.

Note how the constants for the message box are specified.

[email protected] 86
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 5-2

Private Sub cmdQuit_Click()


If MsgBox("Do you really want to quit?", vbQuestion +
vbYesNo + vbDefaultButton2, "Flying") = vbYes Then
End
End If
End Sub
Step 46 Test the application by running it. Save the project.

Constant Value Description


vbOKOnly 0 Display OK button only.
vbOKCancel 1 Display OK and Cancel buttons.
vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 Display Yes, No, and Cancel buttons.
vbYesNo 4 Display Yes and No buttons.
vbRetryCancel 5 Display Retry and Cancel buttons.
vbCritical 16 Display Critical Message icon.
vbQuestion 32 Display Warning Query icon.
vbExclamation 48 Display Warning Message icon.
vbInformation 64 Display Information Message icon.
vbDefaultButton1 0 First button is default.
vbDefaultButton2 256 Second button is default.
vbDefaultButton3 512 Third button is default.
Application modal; the user must respond to the message box
vbApplicationModal 0
before continuing work in the current application.

[email protected] 87
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

System modal; all applications aresuspended until the user


vbSystemModal 4096
responds to the message box.

Return Values
Constant Value Button chosen
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No

6.0 Exercises

Exercise 1
1.1 Add code to your CarTimer project so that if the car goes off the left of the form, it is
restored to its original position.

Exercise 2
2.1 Add code to your Flying application so that if the plane is at the top left hand corner,
the Go Back button is not visible.

2.2 Add code to the Flying application so that if the plane has flown out of the picture
box, the Go Back button is visible and the Fly button is not visible.

File System Controls, Menu Design, Common Dialog Control, Rich


Textbox Control

[email protected] 88
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

1.0 File System Controls


2.0 Menu Design
3.0 The Common Dialog Control
3.1 Actions for a Common Dialog Control
3.2 Open File Dialogue
3.3 Trapping Errors
3.4 Color Palette Dialog
3.5 Change Font Dialog
3.6 Help Dialog
4.0 Exercises

File System Controls, Menu Design, Common Dialog Control, Rich


Textbox Control/1

1.0 File System Controls


Visual Basic supplies the Drive ListBox, Directory ListBox and File ListBox controls in
order to provide a simple way to access any file on your system.

The following example shows how to use these controls in order to choose and load a file
in graphics format (*.bmp, *.ico or *.wmf ) into an Image control on your form.

Step 1 Start a new project and place the three file system controls plus a Label
with name lblFullPath and an Image control with name imgDisplay (and
with Stretch property set to True) onto your form.

Figure 1-1

Step 2 Set the Pattern property of the File ListBox control to *.bmp;*.wmf;*.ico

The Drive and Dir Change events set up the File1.Path property so that files from the
appropriate directory are listed in the File ListBox.

[email protected] 89
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 3 Add the following code to your form


Sub Drive1_Change ()
Dir1.Path = Drive1.Drive
End Sub

Sub Dir1_Change ()
File1.Path = Dir1.Path
End Sub

The path to the file you want to display is held in File1.Path. The final step is to add the
selected filename to this path.

If the file you want to display is in a root directory, e.g. A:\, the filename is added to the
end of the string. If the file is not in a root directory, you need to put a ‘\’ between the
path and the filename.

Step 4 Add the following code to the File1_Click event.


Private Sub File1_Click()
Dim Fullpath As String
If Right(File1.Path, 1) = "\" Then
Fullpath = File1.Path &
File1.List(File1.ListIndex)
Else
Fullpath = File1.Path & "\" &
File1.List(File1.ListIndex)
End If
lblFullpath.Caption = Fullpath
imgDisplay.Picture = LoadPicture(Fullpath)
End Sub
Step 5 Save the form as frmFile1.frm and the project as File1.vbp. Try out the
application. (The VB5 icons directory contains a lot of icons to view).

Figure 1-2

[email protected] 90
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

File System Controls, Menu Design, Common Dialog Control, Rich


Textbox Control/2

2.0 Menu Design


Visual Basic provides a Menu Editor to enable you to produce menu bars in the
conventional Windows format across the top of your forms.

The following application which builds a simple editor program for rich text format or
ASCII text files, provides an opportunity to use the Menu Designer.

Step 6 To see what you will be able to achieve by the end of this chapter, run the
application Viewer.EXE stored in Files folder.

Step 7 Start a new project. Name the form as frmFileViewer and set the caption
of the form to File Viewer. Save the form as frmFileViewer.frm and the
project as FileViewer.vbp. Add a large Rich TextBox control to the form.
(If this control is not in your toolbox, select Components from the Project
menu, and check Microsoft Rich TextBox Control 5.0). Set the Name
property for the Rich TextBox to rtbDisplay, and the Scrollbars property
to 3-rtfBOTH.

Figure 2-1

In the next steps you will create a menu system of options that will appear at the top of
the window. This menu system is designed using the menu editor.

Step 8 Click on the frame to select it. Select Menu Editor from the Tools menu.

[email protected] 91
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

The following window will appear

Figure 2-2

Step 9 Type &File in the caption cell and mnuFile in the Name cell.

Step 10 Click Next.

Step 11 Click the right facing arrow to create a submenu item. Type &New in the
Caption cell and mnuNew in the Name cell.

Separators in menus are created by typing the - character as the caption. Separators must
also be given names.

Step 12 Click Next. Type - in the Caption cell and mnuSep1 in the Name cell to
insert a separator in the menu. Click Next.

Step 13 Add further menu items with Captions and Names as shown below, using
the arrow keys to set up the hierarchy of main menu and sub-menus.

[email protected] 92
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-3

Step 14 Click OK to close the Menu Editor window and run your application to
check that your menu structure is correct.

You can return to the Menu Editor window at any time.

Currently, the menu options do not do anything when you select them. In the next step
you will create code that is associated with the menu options.

Step 15 Go to Code View for your form and implement New, Exit and About:
Private Sub mnuNew_Click()
rtbDisplay.Text = ""
End Sub

Private Sub mnuExit_Click()


End
End Sub

Private Sub mnuAbout_Click()


MsgBox “I wrote this little editor program”,vbInformation,
“About FileViewer”
End Sub
Step 16 Save the project. Run the application and try out the options you have
implemented so far. The option Exit should end the application and the
option About should display a message box. The option New should clear
the text from the Rich Text box window.

So far, you have created a menu and added the code for some of the options. In the next
sequence, you will add more functionality to this application by using dialog boxes.

[email protected] 93
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Finally, you will have an application that will allow you to select a file (based on the
previous Icon viewer program) and view the contents.

File System Controls, Menu Design, Common Dialog Control, Rich


Textbox Control/3

3.0 The Common Dialog Control


You have seen in earlier examples how to locate files and change fonts. There is a much
easier way!!

3.1 Actions for a Common Dialog Control


Visual Basic provides the Common Dialog control to give you a quick way of
implementing commonly used sequences of dialogue with the user of your application.
The control has methods which determine which dialogue will be carried out.

Method Dialogue
ShowOpen Open File
ShowSave Save File
ShowColor Color Palette
ShowFont Change Font
ShowPrinter Print
ShowHelp Help

Step 17 Add a Common Dialog control to your File Viewer form. If the control is
not in your toolbox, select Components from the Project menu, and check
Microsoft Common Dialog 6.0). When the application is run, the common
dialog box is not visible, so do not worry where it is placed on the form.
Change the Name property to cdlViewer.

[email protected] 94
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 3-1

3.2 Open File Dialogue


The Common Dialog control will be used to select a file for viewing. You need to use the
ShowOpen method and set the Filter property to a suitable pattern to be used for file
selection.

Step 18 Access the code view and add the following code for
menuOpenFile_Click().
Private Sub mnuOpenFile_Click()
Dim strFileName As String
cdlViewer.Filter = "RTF|*.rtf|Text|*.txt|All|*.*"
cdlViewer.ShowOpen
strFileName = cdlViewer.filename
rtbDisplay.LoadFile strFileName
End Sub
Step 19 Save your files. Run the application and select a file to check that the text
appears in the Rich TextBox.

Your File Viewer application should be displaying the selected file in the window.
However, there are still improvements to be made to the application, and there are still
some menu options that are not working yet. Good applications know how to handle the
unexpected, so in the next step you will add some error handling functionality to the
application.

3.3 Trapping Errors


It is possible that an error might occur when the above code is being executed.

[email protected] 95
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

The On Error statement is a quick and simple way of trapping errors while a program is
running. It should be used wherever necessary to avoid the inelegance of a program
crash.

Step 20 Add the code shown to the event procedure.


Private Sub mnuOpenFile_Click()
Dim strFileName As String
cdlViewer.Filter = "RTF|*.rtf|Text|*.txt|All|*.*"
cdlViewer.ShowOpen
On Error GoTo OpenProblems
strFileName = cdlViewer.filename
rtbDisplay.LoadFile strFileName
rtbDisplay.Caption = strFileName
Exit Sub
OpenProblems:
MsgBox "Can’t open the file, select another.",
vbCritical
Exit Sub
End Sub

You have now created a much more robust procedure. If the file cannot be opened, a
message box will appear and display an error message. Now you will do something
similar when a file is saved, by adding the code and error handling statements to the
mnuSave_Click() function.

Step 21 Add the following code to the Save menu event.


Private Sub mnuSave_Click()
Dim strFileName As String
cdlViewer.Filter = "RTF|*.rtf|Text|*.txt"
cdlViewer.ShowSave
On Error GoTo SaveProblems
strFileName = cdlViewer.filename
If cdlViewer.FilterIndex = 1 Then
cdlViewer.DefaultExt = “RTF”
rtbDisplay.SaveFile strFileName, rtfRTF
Else
cdlViewer.DefaultExt = “txt”
rtbDisplay.SaveFile strFileName, rtfText
End If
Exit Sub
SaveProblems:
MsgBox "Can’t save the file, try again.",
vbCritical
Exit Sub
End Sub

Your application is now just about complete. But what about those missing menu options
for changing the fonts and colors? In the next step you will add the necessary code to do
these tasks.

[email protected] 96
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

3.4 Color Palette Dialog


Using the ShowColor method of the Common Dialog control brings up the Color Palette
which is used in this example to change the BackColor property of the Rich TextBox.

Step 22 Add the following code to the Back Colour option on your menu
Private Sub mnuBackColour_Click()
cdlViewer.Flags = cdlCCRGBInit
cdlViewer.ShowColor
rtbDisplay.BackColor = cdlViewer.Color
End Sub

The constant cdlCCRGBInit sets a default value for the colour palette.

3.5 Change Font Dialog


In order to take advantage of the formatting that is possible, you need a way to change the
font styles when your viewer is being used for rtf files. Using the ShowFont method of
the Common Dialog control invokes a font changing dialogue. The values selected are
applied to any text currently selected in the rich textbox and to any new text inserted after
the current cursor position.

Step 23 Write code for the Change Font option on your menu
Private Sub mnuChangeFont_Click()
cdlViewer.Flags = cdlCFBoth Or cdlCFEffects
cdlViewer.ShowFont
rtbDisplay.SelFontName = cdlViewer.FontName
rtbDisplay.SelFontSize = cdlViewer.FontSize
rtbDisplay.SelBold = cdlViewer.FontBold
rtbDisplay.SelItalic = cdlViewer.FontItalic
rtbDisplay.SelUnderline = cdlViewer.FontUnderline
rtbDisplay.SelColor = cdlViewer.Color
End Sub

The constants used to assign a value to the Flags property specify that the fonts listed will
be both screen and printer fonts and that the effects will include underline, strikeout and
colour effects.

Step 24 Save your application. Run the application and try out this code to see the
font dialog box.

The application is just about complete. However, there is no help! In the next steps, you
will add some help functionality to your application by adding a message to the help
option.

[email protected] 97
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

3.6 Help

Step 25 Add a message box to the How To Help menu option to say that help will
be available soon. If you cannot remember how to do this, look at
mnuAbout.
Private Sub mnuHelpRichTextBox_Click()
cdlViewer.HelpFile = "VB5.HLP"
cdlViewer.HelpCommand = cdlHelpKey
cdlViewer.HelpKey = "RichTextbox Control"
cdlViewer.ShowHelp
End Sub
Step 26 Test your completed application. Save your application.

4.0 Exercises
1.1 Demonstrate your File Viewer application and be prepared to explain any code it
contains.

1.2 Add an Edit menu to your application with a Select All option. Give the option the
shortcut Ctrl A. (Use Shortcut in the Menu Editor). Write code for this option. (Hint set
the SelStart property to 0 and the SelLength property to Len(rtbDisplay.text)).

Modules, the Rnd function, Frames, Control Arrays, Drag & Drop

1.0 Modules
1.1 Event procedures
1.2 General procedures
1.3 Scope of procedures
1.4 The Screen object
1.5 Calling a sub procedure
1.6 The Rnd function
1.7 The RGB function
2.0 The Frame control
2.1 Frames and Option (Radio) buttons
3.0 Control Arrays
3.1 Using control arrays in animation

[email protected] 98
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

4.0 Drag and Drop in Visual Basic


4.1 An Example Project
5.0 Exercises

Modules, the Rnd function, Frames, Control Arrays, Drag & Drop/1

1.0 Modules
Code which you want to access from more than one form is usually stored in a module.

You can use modules like code libraries and attach them to different projects.

Modules contain declarations and subprograms (procedures).

1.1 Event procedures


These are associated by name with a particular event e.g. Command1_Click(). Visual
Basic provides you with a template for the code which you wish to attach to a particular
event. Event procedures are stored in the form that contains the control.

1.2 General procedures


General procedures are called at any time from Visual Basic code rather than being
associated with a particular event. These general procedures may be Sub Procedures or
Function Procedures and either form allows for parameters if required.

The format for parameters is: [ByVal] name AS type

The keyword ByVal signifies that the parameter is being passed by value. If ByVal is
omitted, the parameter is passed by reference (address). Passing by value ensures that the
parameter cannot accidentally be changed.

General procedures may be stored in a form or in a code module.

1.3 Scope of procedures


The keyword PRIVATE indicates that the procedure cannot be called from outside the
form or module where it was declared.

[email protected] 99
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

The keyword PUBLIC indicates that the procedure can be called from other forms or
modules. Event procedures are PRIVATE by default. General procedures are PUBLIC by
default.

The following example shows you how to develop a library of procedures which can be
used to manipulate any form.

The purpose of the first sub procedure is to centre a specified form in the middle of the
screen.

Step 1 Start a new project and add a command button to the form. Set the
properties as follows

Form CommandButton
Name=frmMAIN Name=cmdNextForm
Caption=Module Demo Caption=Next Form

Step 2 Select Add Module from the Project menu, then click on Open, making
sure that the ‘New’ tab and module are selected as shown below. Click
Open.

Figure 1-1

Step 3 Select Add Procedure from the Tools menu.

[email protected] 100
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-2

Step 4 Type CentreForm for the name of the new procedure and click on OK.

Visual Basic provides the outline template for your procedure. To make the procedure
more generally useful, the name of the form to be centred is passed as a parameter.

Step 5 Enter the following code


Public Sub CentreForm(theForm As Form)
theForm.Move (Screen.Width / 2 - theForm.Width / 2),
(Screen.Height / 2 - theForm.Height / 2)
End Sub

Save the project as form as frmMain.frm and the project as Main.vbp. Save the module
as Main.bas.

1.4 The Screen object


The code to centre the form uses properties of a special object called Screen which is
only available to you at run-time.

1.5 Calling a sub procedure


Visual Basic allows the alternative forms:

Call SubName(Parameters)

or

SubName Parameters

The second format is the more usual convention.

[email protected] 101
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 6 Put the following statement into the Form_Load event and run your
application to check that your centering works.

CentreForm frmMain

or, using the keyword Me to refer to the current form

CentreForm Me

Step 7 Right-click on the Main.bas module in the project window and select code
view. Add the following new procedure to your code module.
Public Sub ShrinkForm(theForm As Form)
theForm.ScaleMode = vbTwips ' the mode may have been
changed
Do While theForm.Height > 500 And theForm.Width > 500
CentreForm theForm
theForm.Height = theForm.Height - 50
theForm.Width = theForm.Width - 50
Loop
theForm.Hide
frmMain.Show
End Sub
Step 8 Save the project.

Step 9 Add a second form to your project. Give it the name frmSecond and size
the form so that it is square. Set the caption to Seconf Form and save the
form as frmSecond.frm.

Step 10 Add the following code to the Click event for the second form.
Private Sub Form_Click()
ShrinkForm Me
End Sub
Step 11 Add the following code to the command button on the main form so that it
loads and shows the second form.
Private Sub cmdNextForm_Click()
Load frmSecond
frmSecond.Show
Me.Hide
End Sub
Step 12 Save the project. Run the application and click on the command button.
The second form should appear. Click on the second form and it should
shrink.

Step 13 Add the following new procedure to the Main.bas module.


Public Sub RandomlyColour(theForm As Form)

[email protected] 102
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
theForm.BackColor=RGB(Int(256*Rnd),Int(256*Rnd),Int(256*Rnd)
)
End Sub

1.6 The Rnd function


The procedure uses the function Rnd, which is supplied by Visual Basic, to randomly set
the background colour of a form.

To produce random integers in a given range, use the formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

When you use the Rnd function, the statement Randomize should be added to the Load
event for the main form to get a different sequence of random numbers each time the
application is run.

1.7 The RGB function


The Visual Basic function RGB returns a colour determined by the parameters which
have values in the range 0 to 255.

RGB(red component, green component, blue component)

Step 14 Add the line shown in bold to the ShrinkForm procedure in the Main.bas
module.
Public Sub ShrinkForm(theForm As Form)
theForm.ScaleMode = vbTwips ' the mode may have been
changed
Do While theForm.Height > 500 And theForm.Width > 500
CentreForm theForm
theForm.Height = theForm.Height - 10
theForm.Width = theForm.Width - 10
RandomlyColour theForm
Loop
theForm.Hide
frmMain.Show
End Sub
Step 15 Save your files. Try out your application.

[email protected] 103
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Modules, the Rnd function, Frames, Control Arrays, Drag & Drop/2

2.0 The Frame control


A frame control is a box which is used to group other controls together. It is useful in
form design because you can move all the controls it contains by moving the frame.

A frame has a Caption property and an Enabled property. Setting the enabled property to
false disables all the controls that the frame contains.

2.1 Frames and Option (Radio) buttons


The option button control is set up so that only one button can be chosen at a time. The
use of frames is essential if you want to use more than one group of option buttons on a
form.

Figure 2-1

3.0 Control Arrays


A group of option buttons can be set up as a Control Array - a group of controls of the
same type that have the same name.

This allows you to refer to an individual control by its index value rather than having to
refer to an individual name.

The following example demonstrates how to manipulate the option buttons as control
arrays.

Step 16 Start a new project and put a frame control on the form, so that the frame
control takes up about half the left side of the form. Name the form as
frmOption and set the caption to Groups of Option Buttons. Save the
form as frmOption.frm and the project as Option.vbp. Change the
caption of the frame control to Foreground Colour.

[email protected] 104
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 3.0-1

Step 17 Click once on the option button control in the toolbox and use the mouse
to position a new option button inside the frame. Change the name of the
option button to optForeground.

Step 18 Click on the option button on the frame to select it. Choose Copy from the
Edit menu.

Step 19 Make sure that the frame is selected and select Paste from the edit menu.

You will be asked if you want to create a control array.

Figure 3-2

Step 20 Click on Yes.

The option buttons in the frame will now have the names optForeground(0) and
optForeground(1) as shown in the figure below.

[email protected] 105
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 3-3

Step 21 Select the frame again and Paste a third option button into the frame.
Change the captions as shown

Figure 3-4

Step 22 Add a label to the form with caption Hello! and name lblHello. Set the
forecolor property to red and backcolor to black.

Figure 3-5
Step 23 Add another frame with caption Background Colour containing three

[email protected] 106
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

option buttons named optBackground in a control array. Change the


captions as shown in Figure 3-6.

Figure 3-5

You now need to add code that will change the foreground and background colours for
lblHello.

There is one Click event for each set of option buttons. The select case statement selects
the action depending on the value of the parameter, Index.

Step 24 Add code to the events as shown.


Private Sub optForeground_Click(Index As Integer)
Select Case Index
Case 0: lblHello.ForeColor = vbRed
Case 1: lblHello.ForeColor = vbYellow
Case 2: lblHello.ForeColor = vbBlue
End Select
End Sub

Private Sub optBackground_Click(Index As Integer)


Select Case Index
Case 0: lblHello.BackColor = vbBlack
Case 1: lblHello.BackColor = vbWhite
Case 2: lblHello.BackColor = vbGreen
End Select
End Sub
Step 25 Save the project and form. Run the application to test it.

3.1 Using control arrays in animation


Control arrays are useful when you have a long sequence of pictures to load into an
image control to create an animation.

Step 26 Start a new project and add a Timer control named tmrCyclist, and an

[email protected] 107
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Image control named imgMovingCyclist to the left hand side of the form.
Name the form as frmCyclist. Set the caption on the form to Cyclist
Demo. Save the form as frmCyclist.frm and the project as Cyclist.vbp

Figure 3-7
Step 27 Set the Stretch property of the image control to True.

The animation sequence for this exercise requires seven different pictures. You will need
to set up seven image controls across the bottom of the form, as shown below.

Step 28 Add a new image control named imgCyclist to the form in the bottom left
corner. Set the stretch property to True.

Step 29 Copy and paste this image control until you have a control array of seven
image controls along the bottom of the form.

Figure 3-8

Step 30 Change the Backcolor property of the form to white.

The animated sequence is stored in pcskills\cyclist as the files CYCLE1.BMP,


CYCLE2.BMP, CYCLE3.BMP, CYCLE4.BMP, CYCLE5.BMP, CYCLE6.BMP and
CYCLE7.BMP.

Step 31 Load the picture CYCLE1.BMP into imgCyclist(0), CYCLE2.BMP into

[email protected] 108
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

imgCyclist(1) etc.

Step 32 Load the picture CYCLE7.BMP into imgMovingCyclist.

Figure 3-9
Step 33 Set the Interval property for the Timer to 100 and add the following code
to the Timer event.
Private Sub tmrCyclist_Timer()
Static Index As Integer
imgMovingCyclist.Picture = imgCyclist(Index).Picture
imgMovingCyclist.Left = imgMovingCyclist.Left + 150
Index = (Index + 1) Mod 7
End Sub
Step 34 Drag the bottom of the form over the control array sequence of pictures so
that the control array is no longer visible on the form. Save the files. Run
the application.

You can see that this kind of animation has its limitations. There are better methods to
use for more experienced users of Visual Basic.

Modules, the Rnd function, Frames, Control Arrays, Drag & Drop/3

4.0 Drag and Drop in Visual Basic


Drag and drop is a useful feature of most Windows applications. It is not difficult to add
such a feature to your Visual Basic application interface. Dragging a control does not
physically move it. If you want the dragged control to move, you must write code to
achieve this.

[email protected] 109
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

4.1 An Example Project


This form is designed to allow letters to be dragged into the grid below.

Figure 4-1

Step 35 Start a new project. Name the form frmDragDrop and set the caption to
Drag and Drop Example. Save the form as frmDragDrop.frm and the
project as DragDrop.vbp. Add a label to the form. Set the Name property
to lblLetter. Set the Caption property to A. Set the Font property to about
size 18. Set the DragMode property to 1. You can optionally also set the
DragIcon property.

Step 36 Copy the label and Paste to create a control array. Repeat for as many
letters as you require. Change the captions appropriately.

The control to be dragged is called the SOURCE.

Step 37 Add a new label to the form. Set the Name property to lblWord. Set the
Caption property to _. Set the Font property to size 18 to display the
underscore character as shown in the form below. Copy and Paste to make
a control array with 5 members.

Figure 4-2
Step 38 Write code for the DragDrop event for the lblWord control array.

[email protected] 110
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Private Sub lblWord_DragDrop(Index As Integer, Source As
Control, X As Single, Y As Single)
' Index identifies which element of lblWord the letter was
dropped on.
' Source is the control which was dropped.
' X and Y give the current mouse coordinates in the
target.
lblWord(Index).Caption = Source.Caption
Source.Visible = False ‘ if this is what you want to
happen
End Sub

The control that detects the Drop is called the TARGET.

Step 39 Save the project files. Run the application and drag the letters from the top
to the bottom to create a word.

5.0 Exercises

Exercise 1
1.1 Demonstrate the cyclist application.

1.2 Demonstrate the Label colour application.

Exercise 2
Write an application that generates and displays a column of 6 lotto numbers in a
ListBox. (i.e. 6 random numbers in the range 1 to 40).

You may find it helpful to write and save the following procedure function in a module.
This will save you having to remember how to use Rnd when you need a random
number.

Public Function RandomInRange(LowerBound As


Integer,UpperBound As Integer)
RandomInRange = Int((UpperBound - LowerBound + 1) * Rnd +
LowerBound)
End Function

[email protected] 111
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Running Other Applications from Visual Basic, Creating Applications,


Using DLLs, DoEvents

1.0 Running other applications


1.1 The Shell function
2.0 Creating a Windows application
3.0 Using DLLs
3.1 The DECLARE statement
3.2 Using a DLL subprogram
3.3 Things to remember
3.4 The Sleep function
4.0 DoEvents
5.0 Exercises

Running Other Applications from Visual Basic, Creating Applications,


Using DLLs, DoEvents/1

1.0 Running other applications

1.1 The Shell function


This Visual Basic function can be used to run any executable program from your Visual
Basic application.

The syntax is:

integervariable = SHELL(commandstring [, windowstyle])

where

 integervariable is required to store the return value of the function. If the Shell
function successfully executes the named program it returns the instance handle
(task identifier) of the started program.
 commandstring is the name of the .COM, .EXE, .BAT, or .PIF file to execute,
plus arguments or command line switches.
 windowstyle is a number corresponding to the style of the window in which the
program is to be executed. The following table identifies the constants you can
use for windowstyle and the resulting style of window:

[email protected] 112
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Constant Description
vbHide Window is hidden and focus is passed to the hidden window.
vbNormalFocus Window has focus and is restored to its original size and position.
vbMinimizedFocus Window is displayed as an icon with focus.
vbMaximizedFocus Window is maximized with focus.
Window is restored to its most recent size and position. The
vbNormalNoFocus
currently active window remains active.
Window is displayed as an icon. The currently active window
vbMinimizedNoFocus
remains active.

Note The Shell function runs other programs asynchronously. That means that you
cannot depend on a program started with Shell to be finished before the next Visual Basic
statement is executed.

The following example demonstrates the Shell function:

Step 1 Start a new project and add two command buttons and a common dialog
control to the form. Name the form as frmAppManager and set the
caption of the form to Application Manager. Save the form as
frmAppManager.frm and the project as FormManager.vbp

Figure 1-1

Step 2 Name the command buttons cmdCalculator and cmdOtherEXE and set
their captions appropriately.

Step 3 Name the common dialog control cdlGetFile.

Step 4 Add the following code to the command buttons


Private Sub cmdCalculator_Click()
Dim TaskID As Long
TaskID = Shell("calc.exe", vbNormalFocus)
End Sub

Private Sub cmdAnyEXE_Click()


Dim TaskID As Long
cdlGetFile.Filter = "EXE File|*.exe"

[email protected] 113
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
cdlGetFile.ShowOpen
TaskID = Shell(cdlGetFile.filename, vbNormalFocus)
End Sub
Step 5 Save the files. Run the application and test the buttons. Select an EXE file
such as Notepad.exe to test the RunAnyEXE button.

2.0 Creating a Windows application


You can freely distribute any application you create with Visual Basic to any Microsoft
Windows user. Users will need copies of the following:

 The Visual Basic run time file (Vbrunxxx.dll)


 Any .ocx files
 Any additional DLLs, as required by your application or by ActiveX controls

The following example shows you how to make an.exe file for a simple application. For
complex applications, you should use the Setup Wizard to ensure that all necessary files
are distributed to your user and installed correctly.

Step 6 Use the same project you currently have open (the Application Manager).
Click on the form. In the properties window, set the Icon property for the
opening form to a suitable icon. (There are lots of icons in subfolders of
the Visual Basic Icons folder).

Step 7 Save the file as frmAppManager1.frm. Save the project as


AppManager1.vbp. Add a command button named cmdCompanyName
to the main form of your project. Set the caption to Company Name.

Figure 2-1

This button will be used to retrieve version information from your application.

Step 8 Add the following code.


Private Sub cmdCompanyName_Click()
MsgBox App.CompanyName,vbInformation
End Sub

[email protected] 114
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 9 Select Make EXE File... from the File menu. You will be prompted for the
location and name for the EXE file.

Figure 2-2

Step 10 Select options.

The options panel enables you to enter version information which will be stored in the
EXE file. This information can be accessed from code using properties of the App object.

Figure 2-3

Step 11 Enter some suitable data into the Company Name field.

Step 12 Click on OK.

Step 13 Save the .EXE file.

[email protected] 115
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 14 Save the files and project. Close Visual Basic.

Step 15 Run the EXE file from the folder where you saved it.

Step 16 Click on the Company Name button to display the company information.

If you have the Professional or Enterprise Edition of Visual Basic 6.0, you can compile
your code either in standard Visual Basic p-code format or in native code format. Native
code compilation provides several options for optimizing and debugging that aren’t
available with p-code. P-code, or pseudo code, is an intermediate step between the high
level instructions in your basic program and the low-level native code your computer’s
processor executes. At run time, Visual Basic translates each p-code statement to native
code. By compiling directly to native code format, you eliminate the intermediate p-code
step.

The compile tab under Project Properties in the Project Menu allows you to select
compilation code options.

Running Other Applications from Visual Basic, Creating Applications,


Using DLLs, DoEvents/2

3.0 Using DLLs


The Microsoft Windows API (Applications Programming Interface) consists of a
collection of DLLs (Dynamic Link Libraries). You can access the functions in these
libraries from Visual Basic.

The three most commonly used DLLs are KERNEL (system services), GDI (graphics
device interface) and USER (window management).

3.1 The DECLARE statement


Before you can use a subprogram from a DLL in Visual Basic, you must declare the
interface. The statement to declare a subprogram has the syntax:

[email protected] 116
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

[Public|Private] Declare Function name Lib “DLLname” ([parameters])


AS type

or

[Public|Private] Declare Sub name Lib “DLLname” ([parameters])

The declaration is usually placed in the declarations section of a form or module and
must be typed on one line.

Step 17 Start a new project. Set the frame name to frmDLL and set the caption to
DLL Example. Save the form as frmDLL.frm and the project as
DLL.vbp. Insert a new Module.

Step 18 Type the declaration shown below into the declarations section of the new
module. It must be on one line.

Declare Function GetWindowsDirectory Lib "kernel32" Alias


"GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As
Long) As Long

The ByVal keyword refers to passing by value rather than by reference.

The first parameter, lpBuffer, is the string in which the path will be stored
(most DLL functions were originally written in C and the different way in
which strings are handled in Visual Basic is the reason that this parameter
is passed by value).

The second parameter, nSize, is the declared length of the string lpBuffer.

The function returns a long integer which tells you the actual length of the
path found.

3.2 Using a DLL subprogram


Once you have declared the function or sub, you can use it as often as you wish from
your code by supplying the appropriate actual arguments.

Step 19 Save the module as DLL.bas. Add a label named lblPath to your form
and write the following code:
Private Sub Form_Load()
Dim Path As String
Dim pathLength As Long

[email protected] 117
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Path = Space$(100) ' set up a string for the path
pathLength = GetWindowsDirectory(Path, 100)
lblPath.Caption = Path
End Sub
Step 20 Save the files. Run the application.

In this exercise you used some functions that already exist in Windows. This meant
adding a declaration for the function you were going to use and specifying the correct
parameters. The advantage of using these DLL’s is that many of the complex things you
might want to do already exist in Windows, so why rewrite them!

3.3 Things to remember

 declare the DLL subprogram


 type the declare statement on one line
 match the number of actual arguments to the number of formal parameters
 match the type of the actual arguments to the type of the formal parameters
 if you make a mistake with the declaration or use of a DLL, you might crash
Windows so SAVE often

3.4 The Sleep function


You can use this API function when you need a delay in your program.

The declaration is:

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

The sub program is used as in the following example

Sleep 1000 ‘ gives a one second delay

4.0 DoEvents
The Windows environment is event driven and commercial applications are programmed
to temporarily yield control to Windows when a time-intensive calculation is in progress.

The DoEvents statement allows you to do this from Visual Basic. It is built-in to Visual
Basic. You do not need a DLL declaration.

[email protected] 118
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

You should always use DoEvents to ensure that any event which happens while a lengthy
loop is being processed can be attended to.

Do While Ctr < 100000


DoEvents

5.0 Exercises

Exercise 1
The API function GetTickCount returns the number of milliseconds that Windows has
been running.

You are to develop an application which tells the user how long Windows has been
running. The application be run by double clicking an icon on the desktop. The main
form will look something like the following:

Figure 5-1

Your application will include an About menu which opens a form providing similar
information to the About form for Visual Basic or other Microsoft products. The About
form uses properties which are set when the application is made into an EXE file. Your
form should look something like:

Figure 5-2

Clicking the System Information button will start up the MS System Information program
shown below.

[email protected] 119
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 5-3

Steps
1.1 Design the main form. It needs a menu and a label to display the Windows has been
running... message. Choose a suitable icon for the form.

1.2 Find the API declaration GetTickCount and paste it into a new module. (You may
wish to develop a module containing the dll declarations which you use commonly).

1.3 Add code to the Form Load event to display the message shown in the label. For
example:

frmMain.Show
NumOfMins = calculation
lblMinutes = “Windows has been running for “ & NumOfMins & “
minutes.”)

For the calculation of NumOfMins, remember that the GetTickCount function returns the
number of milliseconds since windows started so you will need to divide by 60000 and
use the Int function to round the result.

1.4 Select Add form from the project menu and select an ABOUT DIALOG form. Look
at the code attached to this form and see how it uses dlls to find the location of the
program MSInfo32.exe.

1.5 Return to your main form and add code to the About menu item to show the about
form.

1.6 Add labels to the About form to display values for CompanyName (to the name of
someone who is buying your software), Legal Copyright and Legal Trademarks. Add
code to the load event to display in these labels, suitable properties for these values.
Make the application into an EXE file. When you do this, select Options and enter values
for the new labels. Save the EXE file on your desktop.

[email protected] 120
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Grid Control, Data Controls, OLE Control

1.0 The Data control


2.0 Data Bound controls
3.0 The OLE control
3.1 Creating a new object
3.2 Linking to an existing object
3.3 Activating an object from code
3.4 Closing an Application
4.0 OLE Automation
5.0 Exercises

Grid Control, Data Controls, OLE Control/1

1.0 The Data control


Visual Basic provides facilities for creating and managing data bases. A comprehensive
section in the Help system and in Visual Basic Books Online describes these facilities.

Visual Basic also provides a data control which provides simple access to Microsoft
Access databases from your Visual Basic application. The following simple example
shows you how to view the data from a table.

Step 1 Copy the file pcskills/employees.mdb to your working folder.

Step 2 Start a new project and put a data control, three text boxes and a label on
your form. Name the form as frmDataControl and set the caption to
Data Control Demo. Save the form as frmDataControl.frm and save the
project as DataControl.vbp

[email protected] 121
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-1

Step 3 Set the properties as shown

Control Name Caption/Text


Data control datEmployees Get Next record
Label1 lblMessage
Text1 txtFirstName
Text2 txtSurname
Text3 txtSalary

Step 4 Set the DatabaseName property of the Data control to the name and path
of the Employees database.

Step 5 Set the RecordSource property to the name of the Table “Employee
Details”.

Now that the Data control is attached to the Employee Details table, you can use the Text
Boxes to display the values of fields from that table.

Step 6 Set the DataSource and DataFields properties of the Text Boxes as
shown.

Control DataSource DataField

[email protected] 122
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

TxtFirstName datEmployees First Name


TxtSurname datEmployees Surname
TxtSalary datEmployees Salary

Step 7 Save the files. Run the application and use the data control to step through
the records in the Employee Details table.

Figure 1-2

If you type into the text boxes which are bound to the data control, you will change the
data in the underlying field unless the database is in read only mode. You can protect the
data by setting the Locked property of the text boxes or by using labels instead of text
boxes to display the data.

Step 8 Set the Locked property for each of the bound text boxes to True.

The Label control is going to be used to display a message depending on the salary of the
current employee. The code to do this is placed in the Reposition event for the data
control. This event is triggered each time a new record is selected.

Step 9 Add the following code to the Reposition event for the data control.
Private Sub datEmployees_Reposition()
Select Case txtSalary.Text
Case Is > 40000: lblMessage.Caption = "seriously
rich"
Case 30000 To 39999: lblMessage.Caption = "almost
rich"
Case Else: lblMessage.Caption = "has far to go"
End Select
End Sub
Step 10 Save the project. Run the application and change the records to see the
label caption change.

[email protected] 123
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-3

Grid Control, Data Controls, OLE Control/2

2.0 Data Bound controls


Visual Basic 6.0 provides the DBList, DBCombo, DBGrid and MSFlexGrid controls
which can be bound to data in a database.

The DBList ad DBCombo controls are data bound list boxes and combo boxes which are
automatically populated from a field in an attached Data control, and can be used to
optionally update a field in a related table of another Data control.

The DBGrid control displays and enables data manipulation of a series of rows and
columns representing records and fields from a Recordset object.

The MSFlexGrid control displays and operates on tabular data. It allows complete
flexibility to sort, merge, and format tables containing strings and pictures. When bound
to a Data control, MsFlexGrid displays read-only data.

The following simple example shows how to use the DBList, DBCombo and DBGrid
controls to select values from a field in a table from an Access database. The values
selected are added to a listbox. See visual Basic Books Online for more complex
examples.

Step 11 Start a new project. Add a Combo box and set the name to dbCombo.
Add a dbList object (you may need to select Components from the project

[email protected] 124
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

menu). Add a Data Control object. Add a dbGrid object. Add three list
boxes. Name the form as frmDataBound and set the caption to Data
Bound Demo. Save the form as frmDataBound.frm and the project as
DataBound.vbp

Figure 1-2

Step 12 Set the DatabaseName property of the Data control to the name and path
of the Employees database.

Step 13 Set the RecordSource property to the name of the table “Employee
Details”.

Step 14 Select the DBCombo control. Set the RowSource property to Data1 and
the ListField property to Surname.

Step 15 Save the project and files. Run the application. You should see the
employees names in the drop down combo box.

Step 16 Add the following code to the Click event for DBCombo1.
Private Sub DBCombo1_Click(Area As Integer)
If Area = dbcAreaList Then
List1.AddItem DBCombo1.Text
End If
End Sub

The Area parameter is used to detect that the user has clicked an item in the list rather
than the drop down arrow.

Step 17 Select DBList1. Set the RowSource property to Data1 and the ListField
property to Surname.

Step 18 Add the following code to the Click event for DBList1.
Private Sub DBList1_Click()
List2.AddItem DBList1.Text
End Sub

[email protected] 125
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Note that the DataSource and Datafield properties for the DBList and DBCombo controls
are Not used to fill the control.

Step 19 Select the DBGrid control. Set the DataSource property to Data1.

The default settings will display all the fields in the grid. You can specify only certain
fields by using the Custom property.

The following step shows how to retrieve the data value from a specified column in the
grid by clicking anywhere in the row.

Step 20 Add the following code to the MouseUp event for DBGrid1.
Private Sub DBGrid1_MouseUp(Button As Integer, Shift As
Integer, X As Single, Y As Single)
Dim theCol As Integer, Bookmark As Variant
theCol = DBGrid1.ColContaining(X)
Bookmark = DBGrid1.RowBookmark(DBGrid1.RowContaining(Y))
List3.AddItem DBGrid1.Columns(1).CellValue(Bookmark)
End Sub
Step 21 Save the project and files. Run your application and select an item from
each of the data bound controls to test that your code works.

Grid Control, Data Controls, OLE Control/3

3.0 The OLE control


This is the control to use when you want to link or embed an object into your Visual
Basic application.

OLE allows you to display and edit data from other applications. An object is data plus
the link to the application software where the data originated e.g. an Excel Worksheet, an
Excel Chart, a Word document.

As with objects in other applications, you can choose to

Link i.e. share the data with other applications. The data remains in its
original location.

or

[email protected] 126
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Embed i.e. to copy the original data into your application and store the
copy there.

Double clicking the OLE control on your form will activate the object’s application.
Visual Basic also allows you to activate the object from your code.

The following steps show you how to create a form like the following to demonstrate
some of the power of OLE.

Figure 1-1

3.1 Creating a new object

Step 22 Start a new project and add an OLE control to the form. Name the form as
frmOLE and set the caption to OLE Demo. Save the form as
frmOLE.frm and save the project as OLE.vbp

When you put an OLE control on the form, a dialog box appears.

Step 23 Select Create New and Microsoft Word Picture from the Object Type
list.

Figure 1-2

[email protected] 127
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Creating a Word Picture will allow you to access the WordArt application to define the
text and style for your title. You may need to adjust the scrollbars to position the wordart
in the centre of the screen.

Figure 1-3

Step 24 Select Insert; Picture; WordArt from the menu and choose a suitable style.
Enter ‘OLE Demonstration’ in the font and style of your choice and click
on OK.

Step 25 Close the Word window to return to the Visual Basic application. Set the
BackStyle property of the OLE control to Transparent and the SizeMode
property to Stretch.

Step 26 Save the files and project. Run your application. Double click on the OLE
control and WordArt to make adjustments to your title.

3.2 Linking to an existing object

Step 27 Add a second OLE control to the form.

Step 28 Select Create from File and use the Browse button to find the Word
document pcskills/oledemo.doc.

Step 29 Select Link and click on OK.

[email protected] 128
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-5

This Word document page has been sized so that it will fit onto a form.

Save the form as frmOLE1.frm. Save the project as OLE1.vbp.

Step 30 Change the SizeMode property of the OLE control to Stretch.

Figure 1-6

Step 31 Save your project and files. Run your application. Double click the OLE
control to see that Word is activated with the selected document opened.

Step 32 Close Word and stop your application.

3.3 Activating an object from code


An object can be activated from code rather than by double clicking.

If you have a sound card and speakers, you can use a .wav file for the following example.
Otherwise, create and save a Powerpoint presentation.

Step 33 Add a third OLE control to your form.

[email protected] 129
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 34 Select create from file and select a .wav file or a Powerpoint presentation.
Select Link.

Step 35 If you have chosen a Powerpoint presentation, check the Display as Icon
box.

Step 36 Click on OK. Save the form as frmOLE2.frm. Save the project as
OLE2.vbp.

Step 37 Change the Name property to oleWaveFile (for using a wave file) or
olePowerpoint (if using a powerpoint).

Step 38 Set the Autoactivate property to 0.

Step 39 Add a command button to the form. Set the Name property to
cmdActivateSound or cmdActivateSlideShow and set the Caption
property to something appropriate.

The DoVerb method for an OLE control allows you to carry out the specified action. For
example, an object can be opened for editing or can be played. You can find out what
actions are available for an object by clicking the right mouse button on the object at
design time.

The constant vbOLEPrimary will carry out the primary (most usual) action for the object.
Otherwise use the numeric position in the list of actions (starting at zero).

Step 40 Add the following code to the Click event for the command button.
Private Sub cmdActivateWave_Click()
oleWaveFile.DoVerb vbOLEPrimary
End Sub

or

Private Sub cmdActivateSlideShow_Click()


olePowerPoint.DoVerb vbOLEPrimary
End Sub

[email protected] 130
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 1-7

Step 41 Save your project and files. Try out your application.

3.4 Closing an Application


If you embed an object into your application, you may not find a Close Application
option on the toolbars which you have available. You can close the object’s application
from your Visual Basic application by adding a command button which executes the code
OLEcontrolname.Close.

4.0 OLE Automation


OLE automation enables you to create and control an object in another application from
Visual Basic code. The following example shows how to print an Access report from a
Visual Basic application.

Step 42 Find an Access database which contains a short report.

Step 43 Start a new Visual Basic project and add the following code to a command
button on the form.
Private Sub cmdPrintReport_Click()
Dim DBPath As String
Dim appAccess As Object
Set appAccess = CreateObject("Access.Application.7")
DBPath = " path and name of your database … "
appAccess.OpenCurrentDatabase DBPath
appAccess.DoCmd.OpenReport "name of your report…"
End Sub

This code activates Access, prints the report to the printer and returns to your Visual
Basic application.

[email protected] 131
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

If you are worried about your print budget, change the last line of the code to
appAccess.DoCmd.OpenReport "name of your report…",2

The report will be opened in Print Preview mode.

5.0 Exercises

Exercise 1
Add an image control to the form for the Data control application you developed in Steps
2 to 10. Use this control to display a suitable picture for each of the three categories of
salary as you step through the Employee Details table.

Exercise 2
Add an embedded spreadsheet in an OLE control to your OLE Demo application. Set the
visible property for the OLE control to False.

Add a command button to the form and write code so that when the button is clicked, the
OLE control becomes visible and opened for editing.

Multiple Document Interface (MDI) Applications, Toolbars, Using the


Clipboard, Popup Menus

1.0 Multiple Document Interface Applications


2.0 Building the Application
2.1 Creating the MDI form
2.2 Adding the child form
2.3 Resizing the rich textbox
2.4 Setting up the menus
3.0 Closing MDI application forms
3.1 Deciding if changes to data in a child form have been saved
3.2 Closing the application
4.0 Using the Clipboard
5.0 Adding a toolbar
5.1 Using an ImageList control to store button pictures for the toolbar
5.2 Setting up the toolbar
5.3 Adding the code

[email protected] 132
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

5.4 Adding an option to view the toolbar


6.0 Popup Menus
7.0 Exercises

Multiple Document Interface (MDI) Applications, Toolbars, Using the


Clipboard, Popup Menus/1

1.0 Multiple Document Interface Applications


WordPad and Notepad are examples of applications using the single document interface
(SDI) style. Applications such as Word and Excel which allow you to display multiple
documents at the same time are known as MDI (Multiple Document Interface)
applications.

In an MDI application, the main form is called the MDI form, and the document forms
are called MDI child forms. You usually design only one child form for an MDI
application. This form is then copied for each document that is opened.

In this chapter, you will create an MDI application based on the SDI FileViewer which
you developed in Chapter 7.

2.0 Building the Application

2.1 Creating the MDI form

Step 1 Start a new project and remove the existing Form1 (select Remove Form1
from the Project menu).

Step 2 Select Add MDI Form, New, from the Project menu. Click on MDI Form.
Click Open.

[email protected] 133
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-1
Step 3 Change the Name property for this form to MDIEditor.

2.2 Adding the child form

Step 4 Select Add Form, Existing, from the Project menu and add the form you
developed for the FileViewer application (frmFileViewer.frm).

Step 5 Select the Fileviewer form. Change the MDIChild property to True.

Step 6 Change the Name property to frmDoc. Save the form as frmDoc.frm.
Save the MDI form as mdiEditor.frm and the project as MDI.vbp

You will write code to create a new instance of this form each time a new document is
opened.

2.3 Resizing the rich textbox


The child forms in an MDI application can be resized independently. The rich textbox
control should grow or shrink with the form. The resize event for the form can be used to
achieve this.

Step 7 Add the following code to the Resize event for the frmDoc form
Private Sub Form_Resize()
rtbDisplay.Move 0,0,Me.Width – 100, Me.Height - 300
End Sub

[email protected] 134
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.4 Setting up the menus


You have a choice of how you set up menus for an MDI project:

 attach all the menu options to the MDI form and disable the options not available
until there is a child form open
 attach menu options to the child form and use a different menu on the MDI form –
the menu on the MDI form will automatically be replaced by the menu on the
child form as soon as a child form is opened

The child form that you have just added to the project, already has a menu attached so the
second option is preferable for this project.

Step 8 Select code for the frmDoc form and amend the mnuNew and
mnuOpenFile options as shown

A new instance of a document form is created by declaring a variable as type New


frmDoc.

Private Sub mnuNew_Click()


Dim newDoc As New frmDoc
newDoc.Show
newDoc.Caption = "Untitled"
newDoc.rtbDisplay.Text = ""
End Sub

Private Sub mnuOpenFile_Click()


Dim strFileName As String
Dim newDoc As New frmDoc
newDoc.Show
newDoc.cdlViewer.Filter = "RTF|*.rtf|Text|*.txt|All|*.*"
newDoc.cdlViewer.ShowOpen
On Error GoTo OpenProblems
strFileName = newDoc.cdlViewer.filename
newDoc.rtbDisplay.LoadFile strFileName
newDoc.Caption = strFileName
Exit Sub
OpenProblems:
MsgBox "Can’t open the file, select another.",
vbCritical
Exit Sub
End Sub

The main MDI form can be given a simple menu to enable the first document to be
opened.

Step 9 Select the MDIEditor form and use the Menu Editor to set up a menu
which looks like the following

[email protected] 135
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 2-2
Caption Name
&File mnuFile
&New mnuNew
&Open mnuOpen
- mnuSep1
E&xit mnuExit

Step 10 Add a common dialog control to form MDIEditor. Change its Name
property to cdlViewer.

Step 11 Copy the code from the frmDoc form New and Open options to the New
and Open options for the MDIEditor form.

Step 12 Add code for the mnuExit option to the MDIEditor form
Private Sub mnuExit_Click()
End
End Sub
Step 13 Save the project and files. Run the application to test the main menu
options. (You will need to set Start Up Object to MDIEditor).

Figure 2-3

[email protected] 136
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Multiple Document Interface (MDI) Applications, Toolbars, Using the


Clipboard, Popup Menus/2

3.0 Closing MDI application forms


In MDI applications, there is usually an option for the user to close individual child
forms. The close operation might be cancelled if the information in the child form has not
been saved since it was last changed.

You will also need to ensure that the child forms are properly closed if the user presses
the close button on the main MDI form.

3.1 Deciding if changes to data in a child form have been saved


The simplest way to do this is to use a global boolean variable which is set to true when
text in the rich textbox is changed, and set to false when the data is saved.

Step 14 Save the form mdiEditor.frm as mdiEditor1.frm. Save the form


frmDoc.frm as frmDoc1.frm. Save the project as MDI1.vbp. Use the
menu editor to add a Close option (&Close and mnuClose) to the File
menu on the frmDoc1 form.

Step 15 Add the following declaration to the General Declarations section of the
frmDoc1 form (below the Option Explicit statement).

Dim Changed As Boolean

Step 16 Add this code to the Change event for the rtbDisplay (the rich textbox).
Private Sub rtbDisplay_Change()
Changed = True
End Sub
Step 17 Amend the code for the mnuSaveFile option for frmDoc1 form as shown
Private Sub mnuSave_Click()
Dim strFileName As String
cdlViewer.Filter = "RTF|*.rtf|Text|*.txt"
cdlViewer.ShowSave
On Error GoTo SaveProblems
strFileName = cdlViewer.filename
If cdlViewer.FilterIndex = 1 Then
cdlViewer.DefaultExt = “RTF”
rtbDisplay.SaveFile strFileName, rtfRTF

[email protected] 137
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Else
cdlViewer.DefaultExt = “txt”
rtbDisplay.SaveFile strFileName, rtfText
End If
Me.Caption = strFileName
Changed = False
Exit Sub
SaveProblems:
MsgBox "Can’t save the file, try again.",
vbCritical
Exit Sub
End Sub
Step 18 Add code to the mnuClose option of the frmDOC1 form.
Private Sub mnuClose_Click()
Unload Me
End Sub

The Unload event will cause the child form to be unloaded but before it does this, it
triggers the QueryUnload event for the form. This event allows you to cancel the unload
if you wish.

Step 19 Add the following code to the QueryUnload event for the frmDoc1 form
(select Form, QueryUnload in the code window)..
Private Sub Form_QueryUnload(Cancel As Integer, _
UnloadMode As Integer)
Dim Response As Long
If Changed Then
Response = MsgBox("Are you sure you want to close_
without saving?", vbYesNoCancel, Me.Caption)
Select Case Response
Case vbNo: Cancel = True
Case vbCancel: Cancel = True
End Select
End If
End Sub

This QueryUnload code will also be executed if the user clicks the Close button on a
child form.

3.2 Closing the application


The Exit option on the File menu should also close down the application properly. Using
an Unload statement for the main MDI form will trigger the QueryUnload events for any
open child forms and allow changes to be saved before the application terminates.

Step 20 Amend the code for the mnuExit option on the frmDoc1 as shown
Private Sub mnuExit_Click()
Unload MDIEditor

[email protected] 138
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
End
End Sub

An Unload event for the main form is triggered if the Close button on the main form is
clicked so you don’t need to do anything further to deal with this event.

Save the project and files and test the program.

Figure 2-4

4.0 Using the Clipboard


Adding Cut, Copy and Paste options to the Edit menu for this application will show you
how to manipulate the clipboard from a Visual Basic application.

Step 21 Save mdiEditor1.frm as mdiEditor2.frm. Save frmDoc1.frm as


frmDoc2.frm. Save the project as MDI2.vbp. Use the Menu Editor to add
Cut, Copy, Paste and Delete sub-options to a new Edit menu on the
frmDoc2 form.

Caption Name
&Edit mnuEdit
C&ut mnuCut
C&opy mnuCopy
&Paste mnuPaste
&Delete mnuDelete

[email protected] 139
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 22 Add the following code for these menu options.


Public Sub mnuCopy_Click()
Clipboard.Clear
Clipboard.SetText rtbDisplay.SelText, vbCFRTF
End Sub

Public Sub mnuCut_Click()


Clipboard.Clear
Clipboard.SetText rtbDisplay.SelText, vbCFRTF
rtbDisplay.SelText = ""
End Sub

Public Sub mnuPaste_Click()


rtbDisplay.SelText = Clipboard.GetText(vbCFRTF)
End Sub

Private Sub mnuDelete_Click()


rtbDisplay.SelText = ""
End Sub
Step 23 Save the project and files. Test the edit menu options.

Multiple Document Interface (MDI) Applications, Toolbars, Using the


Clipboard, Popup Menus/3

5.0 Adding a toolbar


The Microsoft Windows Common Controls 5.0 component provides the controls such as
ToolBar, StatusBar, ProgressBar, TreeView, ListView and TabStrip which are part of a
typical Windows 95 application interface.

The collection also includes the ImageList control which is used as a central repository to
supply other controls with images. An ImageList control contains a collection of
ListImage objects, each of which can be referred to by its index or key.

This section shows you how to use the Toolbar and ImageList control to add an edit
toolbar containing Cut, Copy and Paste buttons to your application.

Save mdiEditor2.frm as mdiEditor3.frm. Save frmDoc2.frm as frmDoc3.frm and


save the project as MDI3.vbp.

[email protected] 140
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 24 Select Microsoft Windows Common Controls 6.0 from Components on


the Project menu.

5.1 Using an ImageList control to store button pictures for the toolbar
The imagelist control will be used as a repository for the images on the toolbar buttons.

Step 25 Add an ImageList control to form MDIEditor3. (The control is not


visible when the application is running).

Step 26 Change the Name property for the ImageList control to imlToolbar.

Step 27 Right click on the ImageList control and select Properties to bring up the
property pages.

Figure 5-1
Step 28 On the General tab, select Custom size. (This will size the images to the
size of the first image added).

Step 29 Select the Images tab and select Insert Picture.

The folder Program Files\Microsoft Visual Studio\Common\Graphics\Bitmaps\


Tlbr_Win95 contains the images you will need to create typical Windows toolbars.

Step 30 Add an image for the Cut button and set the Key property to Cut.

Step 31 Repeat the last step for Copy and Paste. Then click OK to close the
Property Pages dialog box.

[email protected] 141
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 5-2

Note that the cut picture has an index value of 1, the copy image an index value of 2, and
the paste image an index value of 3. The images in the imagelist control can be
referenced either by using the index or the key values.

5.2 Setting up the toolbar

Step 32 Add a ToolBar control to the MDIEditor3 form. Change the Name
property to tlbEditor.

Step 33 Right click on the toolbar control and select Properties to bring up the
property pages.

Step 34 Set the ImageList property to imlToolbar.

Figure 5-3
Step 35 Select the Buttons tab and select Insert Button.

[email protected] 142
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 36 Set the Key, ToolTip Text and Image values as shown.

Figure 5-4
Button Index ToolTipText Key Image
Cut 1 Cut text Cut 1
Copy 2 Copy text Copy 2
Paste 3 Paste text Paste 3

Step 37 Repeat the last step for the Copy and Paste buttons.

Your form should now look like

Figure 5-5

[email protected] 143
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

5.3 Adding the code


The code for the Cut, Copy and Paste options has already been added to the menu options
on the frmDoc form. This code can be accessed from the MDIEditor form if it is made
Public rather than Private. The ActiveForm property is used to refer to the currently
active child form.

Step 38 View the code for form frmDoc3 and change the Private declaration to
Public for the Cut, Copy and Paste menu options.
Public Sub mnuCut_Click()
Clipboard.Clear
Clipboard.SetText rtbDisplay.SelText, vbCFRTF
' Delete selected text.
rtbDisplay.SelText = ""
End Sub
Step 39 View the code for form MDIEditor3 and add the following event code
Private Sub tlbEditor_ButtonClick(ByVal Button As
ComctlLib.Button)
On Error GoTo NoActiveForm
Select Case Button.Key
Case "Cut": Me.ActiveForm.mnuCut_Click
Case "Copy": Me.ActiveForm.mnuCopy_Click
Case "Paste": Me.ActiveForm.mnuPaste_Click
End Select
Exit Sub
NoActiveForm:
Exit Sub
End Sub

The error code is added to deal with the buttons being clicked when there is no child form
open.

5.4 Adding an option to view the toolbar

Step 40 Using the Menu Editor, add an Options menu to the MDIEditor3 form
menubar. Add a submenu to this called toolbar.

Caption Name
&Options mnuOption
&Toolbar mnuToolbar

[email protected] 144
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Figure 5-6
Step 41 Select the checked option for the toolbar menu item. Close the menu
editor.

Step 42 Add code to the Toolbar menu option.


Private Sub mnuToolbar_Click()
mnuToolbar.Checked = Not mnuToolbar.Checked
tlbEditor.Visible = Not tlbEditor.Visible
End Sub

Multiple Document Interface (MDI) Applications, Toolbars, Using the


Clipboard, Popup Menus/4

6.0 Popup Menus


Windows applications usually provide a popup menu (or context menu) when you click
the right mouse button. A popup menu is designed using the Menu Editor. Setting the
Visible property to false ensures that the popup menu is not displayed on the menu bar.
Invoking the PopupMenu method for the form when the right mouse button is clicked
displays the menu as a popup menu.

This example displays a pop-up menu at the cursor location when the user clicks the right
mouse button over the rich textbox displaying a document.

[email protected] 145
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 43 Add a menu to the frmDoc3 form that contains the options shown

Figure 6-1

Caption Name
&Popup mnuPopup
&Cut mnuPopupCut
C&opy mnuPopupCopy
P&aste mnuPopupPaste
C&hange Font mnuPopupChangeFont

Step 44 Make sure that the Visible box for the menu header is not checked.

Step 45 Add the following code to the popup menu options.


Private Sub mnuPopupCopy_Click()
mnuCopy_Click
End Sub

Private Sub mnuPopupCut_Click()


mnuCut_Click
End Sub

Private Sub mnuPopupFont_Click()


mnuChangeFont_Click
End Sub

Private Sub mnuPopupPaste_Click()


mnuPaste_Click
End Sub

[email protected] 146
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Step 46 Add the following code to the MouseUp event for rtbDisplay (the rich
textbox) on form frmDoc3.
Private Sub rtbDisplay_MouseUp(Button As Integer, Shift As
Integer, x As Single, y As Single)
If Button = 2 Then
Me.PopupMenu mnuPopup
End If
End Sub

Save the project and files and test the application. You should now get a context menu if
you click the right mouse button anywhere in a document.

7.0 Exercises

Exercise 1
Add an undo option to the Edit menu which undoes the last delete. (Hint: declare a public
string variable and copy the selection to this variable when Delete is executed).

Exercise 2
Add a Windows menu to your application which includes the options to Tile or Cascade
the currently open child windows. (Hint: use the Arrange method for MDIEditor).

Data Access

1.0 Data Access using Visual Basic


2.0 Using the data control
2.1 Attaching the data control to a database at run-time
2.2 Attaching to a database in the same folder as the application
2.3 Accessing a query
2.4 Using SQL to create the query
2.5 A simple way to build a parameter query
2.6 Moving to a record
2.7 Adding, amending and deleting records using bound controls
2.8 Adding a new record using code

[email protected] 147
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.9 Finding and amending fields using code


2.10 Displaying field values in unbound controls

Data Access/1

1.0 Data Access using Visual Basic


“All applications use structured information of one kind or another, whether it is
accounting data, scientific measurements, employee information, or a list of recipes.
Data access in Microsoft Visual Basic gives you the tools to create and use structured
database systems to manage your application's data.

These tools include the Microsoft Jet database engine, the Data control, and the data
access objects (DAO) programming interface.

Using data access objects, you can create databases and build full-featured applications
that access existing databases in many popular formats, including Microsoft Access,
Btrieve, dBASE, Microsoft FoxPro, and Paradox, as well as Open Database Connectivity
(ODBC) client/server databases like Microsoft SQL Server.

The ability to create and access structured database systems gives you many
programming advantages:

 It lets you write programs that use existing databases.


 It allows your application to share data with other programs.
 It simplifies your programming, since you do not need to handle low-level file
accessing and searching.

Visual Basic provides data access capability based on the Microsoft Jet database engine,
the same database engine that powers Microsoft Access.”

[Cited from VB Books Online]

2.0 Using the data control


You saw in Chapter 9 how easy it was to use a data control with bound label or text box
controls to display or change data stored in Access database tables.

The following examples show you how to use the data control with more flexibility. The
examples use a database called TheWarehouse.mdb which includes table Customers
(with fields CustomerID, CustomerName, Address, City).

[email protected] 148
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.1 Attaching the data control to a database at run-time


The DatabaseName and RecordSource properties of the data control can be set at run-
time. Note that you must set the DataSource property of any bound controls at design
time.

Private Sub Form_Load()


Data1.DatabaseName = "a: \thewarehouse.mdb"
Data1.RecordSource = "Customers"
Label1.DataField = "CustomerName"
End Sub

Private Sub Form_Load()


CommonDialog1.ShowOpen
Data1.DatabaseName = CommonDialog1.filename
Data1.RecordSource = "Customers"
Label1.DataField = "CustomerName"
End Sub

2.2 Attaching to a database in the same folder as the application


If you put a database in the same folder as the application, you can use the Path property
of the App object to specify the location.

Private Sub Form_Load()


If Right(App.Path, 1) <> "\" Then
Data1.DatabaseName = App.Path & "\
theWarehouse.mdb"
Else
Data1.DatabaseName = App.Path & "theWarehouse.mdb"
End If
Data1.RecordSource = "Customers"
Label1.DataField = "CustomerName"
End Sub

2.3 Accessing a query


The RecordSource property for a data control can be set to an existing query in the
database. Check that the RecordsetType property for the data control is set to 1-Dynaset
if you wish to use a query.

[email protected] 149
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.4 Using SQL to create the query


You can attach a data control to a query that you generate when your Visual Basic
application is running. To do this, you set the RecordSource property to an SQL string.

Data1.RecordSource = "SELECT [CustomerName], [Address] FROM


Customers
WHERE [City] = 'London'"
Label1.DataField = "CustomerName"
Label2.DataField = "Address"

Note the single quotes around London. These would not be necessary if you were
matching a numeric field.

2.5 A simple way to build a parameter query


This example shows how to enter a search criterion while the program is running.

Dim theCity, theSQL As String


theCity = InputBox("Which city are you looking for?")
theSQL = "SELECT [CustomerName], [Address] FROM Customers
WHERE
[City] = '" & theCity & "'"
Data1.RecordSource = theSQL
Label1.DataField = "CustomerName"
Label2.DataField = "Address"

2.6 Moving to a record


The data control can be moved to a specific record using code.

Private Sub Command1_Click()


Data1.Recordset.MoveFirst
Data1.Recordset.FindFirst "[CustomerName] = 'Thomas
Hardy'"
If Data1.Recordset.NoMatch Then
MsgBox "Couldn't find Mr Hardy"
End If
End Sub

[email protected] 150
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2.7 Adding, amending and deleting records using bound controls


If you want to add a new record via bound controls, set the EOFAction property of the
data control to 2-AddNew.

Changes made to the contents of a bound control will be made to the underlying recordset
unless the Locked property of the control is set.

The current record can be deleted using the Delete method but take care because there is
no prompt to check that you really mean it!

Private Sub cmdDelete_Click()


Data1.Recordset.Delete
End Sub

2.8 Adding a new record using code


Remember that you are adding a new record to a relational table so you will probably
have a primary key field to ensure that the records are unique. For this example, the
primary key is the CustomerID field which is type AutoNumber so an ID will
automatically be generated.

Private Sub cmdAdd_Click()


Data1.Recordset.MoveLast
Data1.Recordset.AddNew
Data1.Recordset![CustomerName] = "Hari Davis"
Data1.Recordset.Update
End Sub

2.9 Finding and amending fields using code


This example shows how to find a specified customer and change the associated address
fields.

Private Sub cmdAmend_Click()


Dim theName, theSearch As String
Data1.Recordset.MoveFirst
theName = InputBox("Who are you looking for?")
theSearch = "[CustomerName] = '" & theName & "'"
Data1.Recordset.FindFirst theSearch
If Not Data1.Recordset.NoMatch Then
Data1.Recordset.Edit
Data1.Recordset![Address] = InputBox("Enter new
address")
Data1.Recordset![City] = InputBox("City?")
Data1.Recordset.Update
End If

[email protected] 151
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
End Sub

2.10 Displaying field values in unbound controls


This example shows you how to set up a combo box to contain a list of all the customer
names.

Private Sub cmdSetUpCombo_Click()


Data1.Recordset.MoveFirst
Do While Not Data1.Recordset.EOF
Combo1.AddItem Data1.Recordset![CustomerName]
Data1.Recordset.MoveNext
Loop
End Sub

INTRODUCTION TO BASIC PROGRAMMING

Central Institute of Technology


Author: B Brown
Date : 09-Feb-87
Rev 2.0

Instructions in the BASIC Programming Language, using an IBM-PC or compatible.

Requirements: IBM-PC
One 5.25" floppy diskette (supplied by tutor,
returnable at end of course)

1 Preparing the IBM-PC ready for use

1.1.1 Insert the special tutor supplied diskette into Drive A (the topmost slot) of the
IBM-PC.

1.1.2 The IBM-PC has a red power switch on the right-hand side, towards the
rear of the base unit. This switch has two positions marked 0 and
1. Flip this power switch to the position marked 1.

[email protected] 152
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

1.1.3 If the computers power switch is already at the position marked 1, re-
initialise the computer by pressing the Ctrl Alt Del keys
simultaneously.

1.1.4 The computer will display the messages similar to those which follow, at
the top of the screen.

IBM Personal Computer DOS Ver 3.2


BASIC Programming Disk For 4176 Computer Principles

The final prompt shown on the screen is,

A>

1.1.5 You are now in a position to use the BASIC language.

[email protected] 153
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

2 STARTING BASIC

2.1 In order to program in BASIC, a program called the BASIC


INTERPRETER must first be loaded into the computers memory.
This program interprets the actual programs you will write,
changing them into a format that the computer understands and
can execute. To load the Basic Interpreter, type GWBASIC, eg,

A>GWBASIC<enter>

The <enter> signifies that you must press the enter key after
entering the keyword GWBASIC. In fact, in order for the
computer to accept all commands, they must be terminated with
the <enter> key. This informs the computer that you have
finished typing, and it may now act on your instructions.

The screen will clear, the cursor prompt should now have
changed to an underscore, and a message informing you that
basic is available.

62762 Bytes free


Ok
_

3.0 WRITING YOUR FIRST BASIC PROGRAM

3.1 BASIC stands for Beginners All Purpose Symbolic Code. It is a


computer language designed for beginners, using English
statements to program the computer.

A Computer Program comprises a list of computer instructions,


in BASIC, or maybe some other computer language. The
computer executes the sequence of instructions or statements
contained in the program, thus accomplishing the desired task.

A Programmer writes the sequence of instructions making up the


program. In order to do this, the desired task is analyzed, broken
down into a series of small steps, then each step is written in the
desired computer language.

Coding is the task of converting the small steps into the actual
computer language, then combining these steps into one unit (ie,
the program.

[email protected] 154
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

3.2 The BASIC language

- was designed for 'home computers' as an easy way of making a


computer do something
- uses English statements to accomplish a task
- each statement is preceded by a line number
- includes mathematical functions, file handling etc

3.3 BASIC Operating Modes


The BASIC language has two operating modes

3.3.1 Command Mode


This mode is used to write, input, edit and debug programs.
Whenever you first start the BASIC INTERPRETER, you will be
in command mode. The cursor will be an _

3.3.2 Execute Mode


This mode is used to execute programs once they are either
written or 'loaded' into the computer. This mode is only available
when the RUN command is entered into the computer.

3.4 A Simple BASIC Program


The following is a simple BASIC program that displays the value
of a variable called 'A' on the computers screen.

10 LET A = 3
20 PRINT A
30 END

3.4.1 Analysis of above program


In BASIC, each statement is preceeded by a line number. Line
numbers generally start with 10, with a line spacing of ten. This
leaves room to insert other lines if need be later on.

LINE 10

This line assigns the value of decimal 3 to the variable A.

LINE 20

This uses the PRINT command to display the value of the


variable A on the screen. In this case the computer will display
the value 3

[email protected] 155
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

LINE 30

Each BASIC program must have a single END statement. This


normally has the highest line number. When the computer
executes this statement, it will switch back into COMMAND
MODE.

3.4.2 Entering in the BASIC Program


To enter the BASIC program, type each of the following
statements (shown in BOLD). The _ represents the cursor prompt
being displayed by the computer, and <enter> represents the key
press for the Enter key.

_10 LET A = 3<enter>


_20 PRINT A<enter>
_30 END<enter>
_

To verify that the above program is actually in the computer's memory,


type LIST to display it.

_LIST<enter>

The computer will then display the program, eg,

_LIST
10 LET A = 3
20 PRINT A
30 END
Ok
_

3.4.3 Running the Program


To RUN the program, type RUN as a command, eg,

_RUN<enter>

The computer will start execution at the lowest line number, line
10, and continue executing each statement until the END
statement is encountered in line 30. The resultant display will be,

_RUN

[email protected] 156
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

3
Ok
_

3.4.4 Saving you first program to disk


Programs may be transferred between the computers memory and
diskette. If you turned the power off now, your program would be
lost. The SAVE command copies your program to diskette,
whereas LOAD copies the program stored on diskette into the
computers memory.
Save the program to disk by typing

_SAVE "Myprogram"<enter>

The textstring enclosed in double quotes following the word


SAVE define what you are calling the program. It will be stored
under this name on the diskette.

ONLY THE FISRT EIGHT CHARACTERS OF A


FILENAME ARE USED.

3.4.5 Clearing the computers memory


At present, even though you have just saved the program to disk,
a copy of it still resides in the computers memory. In order to
erase this copy so you may precede with other programs, type

_NEW<enter>

3.4.6 Calling a program from disk into memory


To load a program from disk into the computer's memory, type

_LOAD "Myprogram"

The textstring enclosed in double quotes following the word


LOAD defines the program being loaded. It will be stored under
this name on the diskette. Once the program is loaded, it may be
listed and run.

3.4.7 Displaying the programs on the diskette


To display all the BASIC programs on your diskette, type

_FILES<enter>

[email protected] 157
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

3.4.8 Obtaining a printout of the BASIC program


The LLIST command is used to list the current BASIC program
stored in the computer's memory to the printer.

_LLIST<enter>

3.4.9 Deleting lines


Lines of a BASIC program may be deleted by

_DELETE 10<enter>
_DELETE 20-50<enter>

3.4.A Exiting from BASIC back to DOS


To exit from BASIC, ie, return to the NETWORK DOS, type

_SYSTEM<enter>

The cursor prompt will change to

A>

[email protected] 158
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

SUMMARY OF BASIC COMMANDS

DELETE Deletes lines of a BASIC program


DELETE 10-20 deletes lines 10 to 20

FILES Displays all files on the current drive/directory


FILES "A:*.BAS" displays all BASIC files on drive A

LIST Lists lines of the BASIC program


LIST 10-20 lists lines ten to twenty
LIST 30 - lists line 30 to the end of program

LLIST Lists the lines of the program to the printer. The program will not be printed
until you exit from BASIC.
LLIST 100-200 lists lines 100 to 200 to the printer

LOAD Loads a BASIC file into the computer's memory.


LOAD "A:STAR" loads the file STAR.BAS into memory
LOAD "A:MYPROG",r loads MYPROG.BAS into memory and
runs it

NEW Erases the contents of the computers memory area

RUN Runs the program currently residing in memory.


RUN 20 runs the program starting at line 20

SAVE Saves the program in memory to the diskette


SAVE "A:EXONE" saves to a file called EXONE.BAS
SAVE "A:EXTWO",a saves to a file called EXTWO.BAS,
using an ascii format.
SAVE "A:TRY" saves a file called TRY to drive A

SYSTEM Exits BASIC and returns to DOS (Disk Operating System). Any
programs waiting to be printed will now go to the printer.

[email protected] 159
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

BASIC

BEGINNERS ALL PURPOSE SYMBOLIC INSTRUCTION CODE BASIC


programs consist of a series of English type commands (statements , where each
command is given a preceding line number. The BASIC program starts execution from
the lowest line number. Each BASIC program must have a single END statement, placed
at the highest line number, to signify the end of the program.

Example of a BASIC program Given a rate of 500mph and time traveled of 6 hours,
display the distance traveled.

10 REM Program by ..................


20 REM Initialize variables
30 Time = 6
40 Speed = 500
50 Distance = Time * Speed
60 PRINT Distance
70 END

ARITHMETIC OPERATORS These allow variables to be combined or assigned


values.

Assignment = Means let the variable be equal to.


In assignment statements, the value on the right side of the = sign is copied into the
variable on the left side, thus the statement

10 LET X = 4

has the effect of assigning the value 4 to the variable X

Addition + Means add two or more values together.

10 LET A = 1
20 LET B = 2
30 LET Y = A + B Y = ___________

Subtraction - Means subtract one value from another

10 LET X = 1
20 LET C = 4
30 LET X = X - C X = ___________

[email protected] 160
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Multiplication * Means multiply two values together

10 LET D = 2
20 LET Z = D * 3 Z = ___________

Division / Used to divide one value by another

10 LET E = 8
20 LET W = E / 8 W = ___________

Exponential ^ Means a number raised to the power of, ie, 102 means 10 * 10, and Y3
means Y * Y * Y

10 LET F = 2
20 LET V = F ^ 3 V = ___________

OPERATOR PRECEDENCE The arithmetic operators are evaluated in a pre-


determined order. This order may be over-ridden by the use of parenthesis (brackets).
The rules of operator precedence are,

1 Exponential ^
2 Multiplication and division * /
3 Addition and Subtraction + -
4 The operators are always evaluated left to right

Parenthesis can be used to override the order of precedence. Consider the following
equation,

Y+B
X = -------
C

In BASIC, we might be tempted to write this as,

10 LET X = Y + B / C

HOW-EVER, this is wrong, as because of operator precedence, division is always


performed before addition. Thus, the value of B gets divided by the value of C first, and
the result is then added to the variable Y.

[email protected] 161
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Brackets can be placed around terms to instruct BASIC about how to perform
calculations. BASIC always performs those calculations inside brackets first, so the
above statement is actually written as

10 LET X = (Y + B) / C

/*------------------------------------------------------------------*/
SELF TEST on Operator precedence Given that

10 LET A = 1
20 LET B = 2
30 LET C = 4

What does X equal after each of the following statements,

40 LET X = A / B / C _____________
50 LET X = A + B / C _____________
60 LET X = A * B * C _____________
70 LET X = A * B - C _____________
80 LET X = A ^ B + C _____________
90 LET X = A / B * C _____________
100 LET X = A * B / C _____________
110 LET X = A ^ B - 1 _____________
/*------------------------------------------------------------------*/

The mathematical equation,

A+B
X = -------
C+D

can be re-written in BASIC as the statement,

10 LET X = ( A + B ) / ( C + D )

and

B
X=A+-+D
C

is re-written in BASIC as,

[email protected] 162
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

10 LET X = A + ( B / C ) + D

/*------------------------------------------------------------------*/
SELF TEST on Expressions Write statements in BASIC to correctly evaluate each of
the following expressions.

2 2
1. Z = X + Y 2. Z = ( X + Y )

A+B+E B
3. Z = ----------- 4. Z = A + -
D+E C

A+B B
5. Z = ------- 6. Z = A + -------
C D-C
/*------------------------------------------------------------------*/

In BASIC, all calculations must be performed on the right hand side of the = sign. The
statement

10 LET -C = Y

is wrong, because you cannot do assignments ( - ) on the left side. The statement should
be re-written as,

10 LET C = - ( Y )

This has the desired effect of negating the value of Y.

[email protected] 163
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

/*------------------------------------------------------------------*/
SELF TEST on BASIC STATEMENTS for each of the following statements, re-write
them correctly.

10 LET Y = 2X + A

10 _________________________

20 LET 4 = X - Y

20 _________________________

30 LET A = 1 / ( X + ( Y - 2 )

30 _________________________

40 LET -J = K + 1

40 _________________________

50 LET S = T / * 3

50 _________________________

60 LET Z + 1 = A

60 _________________________
/*------------------------------------------------------------------*/

DATA NAMES Names given to variables which represent data can be a maximum of
32 alphanumeric characters. Some BASIC versions only recognize the first two
characters. The first letter of the data name must be ALPHABETIC and lowercase letters
are treated as uppercase.
Examples of NUMERIC VARIABLES are,

RATE.OF.PAY HOURS.WORKED B41 X y Home.score

Data names should be meaningful and self explanatory. It is pointless having cryptic
variable names.

CHARACTER STRINGS Character strings are used to store non-numeric data, ie


ABCD and ALFRED are both character strings. The rules for character strings are the
same as those for numeric variables, except that the last character must be $ Examples,

[email protected] 164
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

NAME$ ADDRESS$ TEXT$ X$

Assigning string variables,

10 LET A$ = "Mud in your eye"


20 LET X$ = A$
30 LET N$ = ""
40 REM "" is a null string

THE PRINT STATEMENT The PRINT statement in BASIC is provided to allow the
displaying of text and the value which variables contain, on the screen. There are many
variations to the PRINT statement.

10 PRINT D When executed, the value of D will be displayed at


the current cursor location.

10 PRINT "D" This prints whatever is inside the quotes, ie, D

10 PRINT A,B The comma specifies that the value of B should be


displayed at the next TAB position. These are
every 14 characters.

10 PRINT "A";"B" The semi-colon specifies that the next item, B is


is to displayed immediately after the previous item.

10 PRINT A;B In this case, a space will occur between the values
of A and B.

Referring back to the first program, the displayed result can be made easier by changing
line 50 as,

50 PRINT "The distance covered is ";Distance;" miles."

/*------------------------------------------------------------------*/
SELF TEST on PRINT What would you expect to be displayed after the following
program is executed.

10 LET A = 1
20 LET B = 5
30 LET C = 1.20
40 PRINT "A=";A
50 PRINT "B= ",B

[email protected] 165
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

60 PRINT B+A;B
70 PRINT "C = ";C
80 END

(NOTE: The END statement signifies the end of the program and must have the highest
line number. If execution is to stop elsewhere then use a STOP statement)
/*------------------------------------------------------------------*/

EXERCISE ONE Write a program to calculate the time required to travel 3000 miles at
a speed of 500 mph.

EXERCISE TWO Write a program to calculate the gross pay for a worker named
FRED given that FRED worked 40 hours at $2.90 per hour.

INPUTTING DATA DIRECTLY INTO A PROGRAM It is convenient to accept data


whilst a program is running. The INPUT statement in BASIC allows the programmer this
option. There are variations of the INPUT command,

10 INPUT C When executed, a ? will be displayed as the


when the user responds with a numeric value,
it is assigned to the variable C

10 INPUT "Time traveled ";Time When executed the message


in quotes will be displayed followed by the
cursor

EXERCISE THREE Write a program which converts a temperature in CELCIUS, and


converts it to FAHRENHEIT ( displaying the result). The algorithm is F = (9 / 5) * C +
32

EXERCISE FOUR Write a program which inputs a temperature in FAHRENHEIT and


converts it to degrees CELCUIS. The algorithm is C = (5 / 9) * (F - 32)

INCORPORATING REMARKS OR COMMENTS INTO A PROGRAM Comments


which explain the program flow and use of variables are very important. They are
included by the use of the REM statement.

10 REM This program was written by

Everything after the REM statement on that line is treated as a comment and is ignored
by the computer when the program is executed. The student should use lots of comments,
especially for subroutines. The entry and exit conditions and variables used should be
clearly listed for each subroutine.

[email protected] 166
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

DECISION MAKING (SELECTION in Jackson Structured Programming) Most


programs need to make decisions. There are several statements available in the BASIC
language for this. The IF THEN statement is one of the them.

The relational operators used to compare two values as part of the decision making
process are,

= Equal to these are used in-conjunction


> Greater than with the IF THEN ELSE clause
< Less than to implement decisions
<> Not equal to
<= Less than or equal to
>= Greater than or equal to

When the condition associated with the IF statement is true, the program statement
following the THEN keyword is executed.

Examples,

10 IF A < 6 THEN PRINT A


20 IF A$ > "test" THEN PRINT "invalid"
30 IF Z = M THEN LET X = M

IF THEN ELSE STATEMENTS This includes an ELSE statement, which specifies


the block (statements) to be executed when the IF statement is not satisfied (ie, fails).

10 IF DEPT = 3 THEN LET RATE = 3.00 ELSE LET RATE = 1.00

/*------------------------------------------------------------------*/
SELF TEST on IF THEN ELSE What is displayed when the following program is
executed?

10 LET A = 5 : B = 3 : C = 99 : D = 5
50 IF A > 6 THEN PRINT "A"
60 IF A > B THEN PRINT "B"
70 IF B = C THEN PRINT "C" : PRINT "D"
80 IF B <> C THEN PRINT "E" ELSE PRINT "F"
90 IF A >= C THEN PRINT "G" ELSE PRINT "H"
100 IF A <= D THEN PRINT "I" : PRINT "J"
110 END
/*------------------------------------------------------------------*/

[email protected] 167
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

EXERCISE FIVE Write a program which inputs two values, call them A and B. Print
the value of the largest variable.

EXERCISE SIX Modify the program you wrote in response to EX 5, to accept three
values, A B C, and print the largest value.

THE AND OR NOT STATEMENTS

AND The statement is true only if BOTH arguments are true,

10 IF A = 1 AND B = 2 THEN PRINT X

OR The statement is true if EITHER argument is true,

10 IF A = 1 OR B = 2 THEN PRINT X

NOT Converts TRUE to FALSE and vsvs

10 IF NOT ( A = 1 AND B = 2) THEN PRINT X

/*------------------------------------------------------------------*/
SELF TEST on AND OR NOT What is displayed when the following program is
executed?

10 LET A = 5
20 LET B = 3
30 LET C = 99
40 IF A = 5 OR B > 2 THEN PRINT "A"
50 IF A < 5 AND B > 2 THEN PRINT "B"
60 IF A = 5 AND B = 2 THEN PRINT "C"
70 IF C <> 6 OR B > 10 THEN PRINT "D" ELSE PRINT "E"
80 IF B = 3 AND C = 99 THEN PRINT "E"
90 IF A = 1 OR B = 2 THEN PRINT "F"
100 IF NOT (A < 5 AND B > 2) THEN PRINT "G"
110 END
/*------------------------------------------------------------------*/

EXERCISE SEVEN Write a program which inputs the ordinary time and overtime
worked, calculating the gross pay. The rate is given as $4.20 per hour, and overtime is
worked out at time and a half.

[email protected] 168
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

EXERCISE EIGHT For the first twenty values of Celsius, print out the equivalent
degree in Fahrenheit ( Use a tabular format, with appropriate headings). Use the CLS
command to initially clear the screen.

EXERCISE NINE Modify exercise seven to also calculate the NET pay ( Gross - tax).
Tax is to be calculated as follows,

GROSS <= 100 20% GROSS


GROSS >100<=150 20% + 30%(GROSS-100)
GROSS >150<=200 35% + 40%(GROSS-150)
GROSS >200 45% + 50%(GROSS-200)

LOOPS (ITERATION in JSP) The most common loop in BASIC is the FOR NEXT
loop. Whatever is inside the for next block will be executed a number of times depending
on the iterated condition. Its format is,

FOR variable name = initial condition TO final condition STEP value


program statements
program statements
NEXT variable name

10 CLS
20 PRINT "DEG C","DEG F"
30 FOR C = 1 TO 20 STEP 1
40 LET F = (9 / 5) * C + 32
50 PRINT C,F
60 NEXT C
70 END

If a step count is omitted, a step increment of one is assumed. The variable name after the
NEXT should be included.

/*------------------------------------------------------------------*/
SELF TEST on FOR NEXT What is the output of this program.

10 S = 0
20 FOR J = 1 TO 5
30 PRINT J;
40 LET S = S + J
50 NEXT J
60 PRINT S
70 FOR K = 0 TO 1 STEP .3
80 PRINT K;
90 NEXT K

[email protected] 169
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

100 FOR I = 10 TO 1 STEP -1


110 PRINT I
120 NEXT I
130 J = 3: K = 8 : L = 2
160 FOR I = J TO K STEP L
170 PRINT I
180 NEXT I
190 END
/*------------------------------------------------------------------*/

[email protected] 170
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

NESTED LOOPS For next loops may be nested one within another, so that the inner
loop ( which contains a block of statements ) is repeated by the outer loop.

RULES FOR NESTED 'FOR-NEXT' LOOPS


1. Each loop must use a separate variable
2. The inner loop must begin and end entirely within the outer
loop.

/*------------------------------------------------------------------*/
SELF TEST on NESTED FOR NEXT LOOPS What is the output of the following
program,

10 PRINT "LINE"
20 FOR L = 1 TO 6
30 PRINT L,
40 FOR C = 1 TO 4
50 PRINT "COLUMN ";C,
60 NEXT C
70 PRINT
80 NEXT L
90 END
/*------------------------------------------------------------------*/

EXERCISE 10 The factorial of an integer is the product of all integers up to and


including that integer, except that the factorial of 0 is 1.

eg, 3! = 1 * 2 * 3 = 6

Evaluate the factorial of an integer less than 20, for five numbers input successively via
the keyboard.

THE READ AND DATA STATEMENTS The read and data statements can be used to
simplify programming. The two statements are used together, eg,

10 DATA 3000, 500


20 READ D,R
30 LET T = D / R
40 PRINT "Time =";T
50 END

10 DATA 8,2,1,78,3,91,7

[email protected] 171
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

20 READ N
30 FOR I = 1 TO N
40 READ A
50 PRINT A;
60 NEXT I
70 STOP
80 DATA 13,11
90 END

/*------------------------------------------------------------------*/
SELF TEST on READ and DATA What is displayed after the following code is
executed?

10 READ A,B,C
20 PRINT A + B + C
30 LET S = 0
40 FOR I = 1 TO 5
50 READ X
60 LET S = S + X
70 NEXT I
80 PRINT S
90 STOP
100 DATA 11,2
110 DATA 6,18,21
120 DATA 3,5,19
130 END
/*------------------------------------------------------------------*/

STRING VALUES IN DATA LISTS

10 DATA FRED, BERT


20 READ N$, M$
30 PRINT N$;M$
40 STOP

(where a comma is part of the data string to be read)

10 DATA "SHELTON, FRED ","JONES, MR."

THE WHILE WEND LOOP Loops should not be implemented using GOTOS. These
are considered harmful and make a program difficult to debug and to follow program
logic.

[email protected] 172
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

10 SUM = 0
20 READ NUMBER
30 WHILE NUMBER > 0
40 SUM = SUM + NUMBER
50 READ NUMBER
60 WEND
70 PRINT SUM
80 DATA 10, 20, 30, 15, 40, 0
90 END

Notice that the program has been implemented without the use of a GOTO command.
This has benefits in that changing the line numbers, inserting code etc, will not effect the
program.

NOTE: The program also illustrates the READ AHEAD technique. Before entering the
while loop the data is first read (Line 20). It is tested for validity on entry to the loop
(Line 30) and then processed (Line 40). Before looping again, the data is read again (Line
50), which allows escaping from the while loop.

/*------------------------------------------------------------------*/
SELF TEST on WHILE WEND What is the output?

10 LET PASSED = 0
20 READ NAME$, MARK
30 WHILE NAME$ <> "LAST"
40 IF MARK >= 50 THEN PASSED = PASSED + 1
50 READ NAME$, MARK
60 WEND
70 PRINT PASSED
80 STOP
110 DATA "ALF", 33
120 DATA "BERT",81
130 DATA "DAVE",50
140 DATA "ERIC",49
150 DATA "FRED",49
160 DATA "LAST",0
170 END
/*------------------------------------------------------------------*/

RESTORE This statement resets the data list pointer back to the beginning of the list so
that it may be processed again.

[email protected] 173
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

5 REM Find average price of microcomputer


10 COUNT = 0
20 READ N$, N
30 WHILE NS <> "LAST"
40 COUNT = COUNT + 1
50 READ N$, N
60 END
70 COUNT = COUNT - 1
80 RESTORE
90 LET T = 0
100 FOR X = 1 TO COUNT
110 READ N$, P
120 LET T = T + P
130 NEXT X
140 PRINT"AVERAGE PRICE IS $";T / N
150 STOP
160 DATA "TRS80", 1600, "APPLE", 3000
170 DATA "C64", 1000, "SEGA SC3000", 600
180 DATA "IBM PC", 9000, "LAST", 0
190 END

EXERCISE 11 Given data as in the self test on the while/wend statement above, write a
program to list the grade achieved by each student. Given

A grade 70 - 100
B grade 60 - 69
C grade 50 - 59
D grade 40 - 49
E grade 0 - 39

Also grade ABC as passes, DE as failures. Print each student's name and grade, and at the
end print the total number of passes and failures.

ARRAYS Arrays are defined using the DIM statement. The array consists of so many
elements, specified within the brackets, where each element can hold a piece of data. The
DIM statement informs the computer to find enough space for the array. You cannot use
a variable to specify the number of elements in the array as part of the DIM statement.

eg, 10 DIM A(5) This dimensions an array called A which has five
elements. The elements are accessed using an index (subscript).

eg 20 DATA 7, 13, 12, 4, 3

[email protected] 174
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

30 FOR I = 1 TO 5
40 READ A(I)
50 NEXT I

After execution of the above program, the contents will be as follows,

A(1) = 7 A(2) = 13 A(3) = 12


A(4) = 4 A(5) = 3

Arrays in BASIC have the following syntax,

x(i)

so that x(5) refers to the fifth element in an array called x. In BASIC, array elements start
with 1. Assigning values to array elements is done by,

100 LET x(10) = g

and assigning the contents of an array element to a variable is done by,


120 LET g = x(10)

DECLARING ARRAYS Arrays may consist of any of the valid data types, characters or
numeric. Arrays are declared along with all other variables in the declaration section of
the program, which occurs at the beginning of the program, eg,

10 DIM x(20), y(10)


20 LET x(10) = 20 : LET x(10) = x(10) - 10
40 PRINT x(10)
50 END

The above program declares two numeric arrays, assigns 10 as the contents of the tenth
element of array x, subtracts ten from this value, and finally prints the value.

MULTIDIMENSIONED ARRAYS The following statement declares a numeric array


called m of 10 by 10 elements ( 100 in all). Remember that arrays are split up into row
and columns. The first is the row, the second is the column.

10 DIM m(10,10)

/*------------------------------------------------------------------*/
SELF TEST on ARRAYS What is displayed after the following code is executed?

10 DATA 1.1, .9, 1.0, 2.1, 3.2, 1.7, 2.3, 2.5


20 DIM F(8)

[email protected] 175
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

30 FOR I = 1 TO 8
40 READ F(I)
50 NEXT I
60 PRINT F(3), F(6)
70 LET S = 0
80 FOR I = 1 TO 8 STEP 2
90 LET S = S + F(I)
100 NEXT I
110 PRINT S
120 LET L = 0
130 FOR I = 1 TO 8
140 IF F(I) > L THEN L = F(I)
150 NEXT I
160 PRINT L
170 END

What is displayed when the following program is executed?

10 DATA 33, 81, 72, 58, 63, 71, 90, 85, 83, 53
20 DIM N(10)
30 FOR I = 1 TO 10
40 READ N(I)
50 NEXT I
60 PRINT "STUDENT NUMBER","MARK"
70 FOR P = 1 TO 10
80 LET M = 0
90 FOR I = 1 TO 10
100 IF N(I) > M THEN LET M = N(I) : LET S = I
140 NEXT I
150 PRINT S,M
160 LET N(S) = 0
170 NEXT P
180 END
/*------------------------------------------------------------------*/

EXERCISE 12 Given the following marks achieved in a programming test, and that the
pass mark is the average of all the marks, write a program to list those students who have
passed.

FRED 21
GEORGE 56
ANNE 52
MARY 89
ROBERT 71

[email protected] 176
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

ALFRED 71
CECIL 33
MIKE 54
JENNIFER 41
PAULINE 48

EXERCISE 13 For a multi-choice test in chemistry the correct answers were,


A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D

Five students gave the following results,

FRED A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B
BERT A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A
JEAN A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D
ADRIAN A,B,C,D,A,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E
ALISON A,B,C,A,A,B,C,A,A,B,C,A,A,B,C,A,A,B,C,A

Write a program which has the above information set up in data statements, and then
mark each student, displaying name and mark (%).

EXERCISE 13A Given the data for exercise 12, write a program that sorts the students
into ascending order of marks and prints them out ( name and mark).

SUBROUTINES A subroutine is a module which is called by the GOSUB command.


Each subroutine is terminated by a RETURN statement. Eg,

10 T = 0
20 INPUT C
30 LET S = 2 * C
40 GOSUB 100
50 INPUT C
60 IF C = 5 THEN LET S = 20 ELSE LET S = 15
70 GOSUB 100
80 STOP
100 LET T = T + S
110 PRINT C, S, T
120 RETURN
130 END

Subroutines help support structured program design, by allowing the independent


development of hierarchical modules which are implemented as needed.

/*------------------------------------------------------------------*/

[email protected] 177
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

SELF TEST on SUBROUTINES What is displayed after the following code is


executed?

10 LET A = 0
20 GOSUB 200
30 FOR I = 1 TO 5 STEP 2
40 GOSUB 200
50 NEXT I
60 A = A / 2
70 GOSUB 200
80 STOP
200 LET A = A + 1
210 PRINT A;
220 RETURN
230 END
/*------------------------------------------------------------------*/

[email protected] 178
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

FUNCTIONS There are many special functions which can be used to return specified
values. Two of these are RND and INT.

RND Returns a random number between 0 and 1 eg, 0.422638

INT Returns the largest integer not greater than the numeric
expression. eg,
INT(16.753) will give 16
INT(-3.2) will give -4

Sample program,
5 CONTINUE = 1
10 WHILE CONTINUE <> 0
20 LET B = RND
30 LET B = INT(B * 20)
40 LET C = INT(RND * 20)
50 PRINT B;" + ";C;" = ";
60 INPUT TA
70 IF TA = 0 THEN CONTINUE = 0
80 LET A = B + C
90 IF TA = A THEN PRINT "Correct"
100 ELSE GOSUB 200
110 WEND

200 INPUT "WRONG ***TRY AGAIN";TA


210 IF TA = A THEN PRINT "Correct on SECOND try"
220 ELSE PRINT "You have BLOWN IT..Answer is ";A
230 RETURN
240 END

TAB The TAB(c) command in the print list moves the cursor the number of spaces
specified by the variable c, on the current line, eg,

PRINT TAB(5);"A";TAB(11);"B";"C"

1234567890123456789 are the column positions


A BC is the printed output.

LOCATE row, column is used to move the cursor to the co-ordinates specified by the
variables row and column. The screen is arranged as 80 columns across (0-79) by 25
rows down (0-24).

10 LOCATE 0,0: PRINT "*" prints an * in the top left corner,

[email protected] 179
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

FORMATTED OUTPUT This is achieved by the use of the USING statement.

# specifies the position for each digit.


zero suppress ( a blank )
. indicates the decimal point position.
Eg,

PRINT USING "##";21 gives 21


PRINT USING "###";5.13 gives 5
PRINT USING "#.##";5.9 gives 5.90

You can use a string variable and multiply values, eg,

10 LET A = 1.1
20 LET B = 20
30 LET F$ = "#.# ##"
40 PRINT USING F$ ; A,B

displays 1.1 20

/*------------------------------------------------------------------*/
SELF TEST on FORMATTED OUTPUT What will be displayed for the following
code?

10 A = 1.2
20 B = 333
30 C = 0.121
40 F$ = " ## ####.# #.##"
50 PRINT USING " ### ###.#"; B,B
60 PRINT USING F$; A,B,C
70 PRINT USING F$; A,A,A
80 PRINT USING F$; C,C,C
90 END
/*------------------------------------------------------------------*/

FUNCTIONS TO HANDLE NUMBERS

ROUNDING CINT( value )


CINT( 34.567 ) gives 35
CINT( 34.4 ) gives 34

TRUNCATION

[email protected] 180
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

FIX( 34.567 ) gives 34

EXERCISE F7 Given a list of wages terminated by a zero, eg

210.33, 119.78, 191.05, 222.94, 0

calculate the total breakdown of required coins ( ignore dollars) into 50c, 20c, 10c, 5c, 2c,
1c pieces.

STRINGS

ASSIGNMENT OF STRINGS

10 LET N$ = S$
20 LET S$ = "STEM"
30 LET N$ = "" ! "" is a null string

Strings can also be assigned by using a data statement, ie,

10 READ A$
20 DATA FRED ! assigns FRED
30 DATA " FRED " ! assigns ...FRED.

where . is equal to a space

NOTE: Leading spaces, commas, and semicolons must be inside quotes if they are
included as part of the string.

STRING COMPARISONS Each character of a string is assigned an internal code. The


code for each character ( A - z, 0 9 etc) ranges from 0 to 127. Internally the computer
stores each character in ASCII format.
eg,
A = 65 0 = 48
B = 66 1 = 49
a = 97 9 = 57
z = 122 etc

Thus, the code for A is less than the code for B so,

10 IF "A" < "B" THEN PRINT "A is less than B"

When strings are being compared, comparison is done from left to right until a non-match
is found, thus

[email protected] 181
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

"CODE" < "COOL" and "ELEPHANT" < "ELF"

"TRAIL" < "TRAILER" and "TRAIL" < "TRAIL "

"APPLE" < "Apple" and "A1" < "AA"

CONCATENATION OF STRINGS Simply, this is adding one string to another.

10 LET X$ = "ABC" + "DEF" ! gives ABCDEF


20 LET X$ = "*" + X$ + "*" ! gives *ABCDEF*

NOTE: The + is the concatenation symbol.

/*------------------------------------------------------------------*/
SELF TEST on STRING CONCATENATION Work out what will be printed when
the following program is run.

10 LET A$ = "BAT"
20 LET W$ = A$ + "TY"
30 PRINT W$
40 PRINT A$ + A$ + A$
50 LET A$ = A$ + A$
60 PRINT A$
70 LET M$ = ""
80 FOR I = 1 TO 5
90 LET M$ = M$ + "*"
100 PRINT M$
110 NEXT I
120 END
/*------------------------------------------------------------------*/

SUB STRINGS Parts of strings are called sub strings.

A$ = "ABCDEFGH" ! A is position 1, B is position 2,


and H is position 8.

The BASIC format to obtain a substring from a string is,

LET Substringname$ = MID$( A$, M, N) where M is the start


position and N is the number of characters to extract.

Example, LET X$ = MID$( A$, 3, 4 ) gives CDEF


LET X$ = MID$( A$, 1, 8 ) gives ABCDEFGH

[email protected] 182
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

LET X$ = MID$( A$, 4, 2 ) gives DE


LET X$ = MID$( A$, 3, 1 ) gives C

/*------------------------------------------------------------------*/
SELF TEST on MID$ What does the following statements assign to X$

LET X$ = MID$(A$,7,9) ____________________

LET X$ = MID$(A$,0,1) ____________________

LET X$ = MID$(A$,6,4) ____________________

What is the output of the following program?

10 LET A$ = "ABCDEFGH"
20 FOR I = 1 TO 7 STEP 2
30 PRINT MID$(A$,I,I + 1)
40 NEXT I
50 FOR I = 9 TO 1 STEP -1
60 PRINT MID$(A$,I,I);
70 NEXT I
80 END
/*------------------------------------------------------------------*/

SUBSTRING REPLACEMENT The format for replacing part of a string with a


substring is,

MID$( A$,M ) = Substring$

Where the Mth to Mth+len(Substring$) characters of A$ is replaced by those characters


of Substring$

Examples,
LET A$ = "ABCDEFGH"

LET MID$(A$,4) = "XX" ! gives ABCXXFGH

DETERMINING THE LENGTH OF STRINGS The LEN command is used to


determine the length of a string.
eg,
LET A$ = "ABCD"

PRINT LEN(A$) ! gives 4


PRINT LEN("AB") ! gives 2

[email protected] 183
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

/*------------------------------------------------------------------*/
SELF TEST on LEN What is printed for each of the statements below, given that A$ =
"ABCD"

PRINT LEN("") ! gives


PRINT MID$(A$,1,LEN(A$)) ! gives
/*------------------------------------------------------------------*/

EXERCISE S1 Input a string and print the string out in reverse order. Also replace all
spaces by asterisks. eg,

AN PQET is printed as TEQP*NA

EXERCISE S2 Input a letter of the alphabet, and print out its alphabetical
position. Find the position by comparing it against a string containing A to Z. Make sure
that the input character is alphabetic, and continue requesting until it is. Continue the
program until a null string is entered.

INSTR This function returns the position number of a substring.

eg, LET A$ = "GRANDSTAND"


PRINT INSTR(startpos,A$,"AN")

will search for AN starting at startpos in A$.

More examples,
PRINT INSTR(A$,"AN") !default start is 1

PRINT INSTR(4,A$,"AN") ! gives

PRINT INSTR(9,A$,"AN") ! gives

/*------------------------------------------------------------------*/
SELF TEST on INSTR$ What is the output from this program?

10 LET B$="THE CAT SAT ON THE MAT"


20 WHILE INSTR(B$," ") <> 0
30 S = INSTR(1,B$," ")
40 B$ = MID$( B$, 1, S-1) + MID$( B$, S+1, LEN(B$) )
50 WEND

[email protected] 184
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

60 PRINT B$
70 END
/*------------------------------------------------------------------*/

EXERCISE S4 Given the data,

THE LAST MAN IN THE WORLD MANAGED TO MEET THE LAST WOMAN
IN
THE WORLD

input two words. For every occurrence of the first word replace it with the second word.
If no match is found for the first word, print a warning, otherwise print the changed
sentence. Repeat until the first word is a null string.

[email protected] 185
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

Example,

First word? MAN


Change to? DOG

THE LAST DOG IN THE WORLD MANAGED TO MEET THE LAST WOMAN IN
THE
WORLD.
First Word? MAN
Change to? DOG
Warning! The word 'MAN' was not found.

FILE HANDLING

FILES Files are a collection of groups of information, known as records.

RECORDS A Record is a grouping of various data items, eg,

RECORD 1,
NAME :
ADDRESS :
PHONE.NUMBER:

FIELDS Each of the above items that make up a record is called a field. Each field is
usually designated as consisting of so many digits or characters.

BUFFER A buffer is not a programmer who works in the nude! It is a partition of


memory which is used by the BASIC language to handle file management. Whenever
files are read or written, a buffer is used for this. Each file is allocated its own buffer
number, and all commands should use that assigned number for file Input/Output.

TYPES OF FILES There are TWO BASIC types of files, SEQUENTIAL and DIRECT
{ also known as Random Access }.

SEQUENTIAL FILES These files consist of a number of records. Normally, the records
are sorted into some logical order, usually by one of the fields. The general format of a
sequential file is,

[Name][Address][Phone#][Name][Address][Phone#][Name][Address][Phone#]
! ....Record 1 .... !! .... Record 2 ... !! .... Record n ... !

Because each field may have a different length, sequential files are normally appended to
( information is added at the end of the file). Individual records are not usually updated
or altered. In practice, a MASTER file holds all the records. When deletions, etc are

[email protected] 186
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

required, the master file is loaded by the program. The records are then UPDATED,
SORTED, and rewritten to a new UPDATE file. This update file then becomes a new
master file.
In order to find out particular details of a customer, each record must be processed until
the correct record is found. This searching is done using one of the fields, Example.. To
find out the details of a client named 'Waldorf', then the following might be done,

READ RECORD
WHILE NAME <> WALDORF
READ RECORD
WEND

Each record will be read until the record containing the details of a customer named
Waldorf is found. The details of that record can then be processed by the program ( ie,
printed out etc). When data is written to a sequential file, it is added to the place after
where the last data was written. This makes it very difficult for the user to update,
because the data is stored serially, ie field after field without any gaps.

DIRECT FILES Direct files are similar to sequential files, but every record also has a
record number. Similar fields of each record normally have the same length. The typical
format of a direct file is,

[RC1][Name][Address][Phone#][......][RCn][Name][Address][Phone#]
! ..... Record 1 ..... !! !! .... Record n .... !

Because each record has a number, details of a particular record can be read without
first processing all the previous records. Example, if record number 10 needs to be read,
then the BASIC command,

GET #1, 10

will achieve this (whereas in the sequential case, records 1 to 9 would have had to be
read first). Records in direct files can be updated, deleted etc easily. Each record, when
written to the file, usually occupies 256 bytes. This translates directly into a small portion
of user space ( called a sector ) on magnetic media (ie, a hard disk unit). When the user
updates a record as part of a direct file, the sector is rewritten. However, in a sequential
file, each sector may hold more than one record, or parts of a record, so the remaining
records in that sector are erased when the updated record is written back to the disk.

PREPARING A FILE READY FOR USE A certain amount of memory space must be
allocated to hold the information passed between the file and the program. The memory
space is called a BUFFER. To prepare a file ready for reading or writing use,

[email protected] 187
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

OPEN "Filename" FOR ACCESS_MODE AS #Buffer_number

where Buffer_number is the number of the buffer that you have allocated for the file to
use (Use numbers from 1 to 8), and ACCESS_MODE is INPUT, OUTPUT, APPEND
(for sequential files) or RANDOM (for direct files. The default record size is 128 bytes)

WRITING TO A SEQUENTIAL FILE Lets create a sequential file consisting of four


clients. The details are,

J BLOGGS 23 WINDTHROW STREET 376098


M SPOOK 12 GHOST LANE 340012
E NOBOBY 00 NOMANS DRIVE 568901
F NANCY 66 STEWART PLACE 789067

The name field is to consist of 10 characters.


The address field is to have 20 characters.
The phone number consists of 6 digits.

Using arrays, the above information can be stored effeciently, or you can use data
statements. The program can be written as follows,

1000 REM OPEN FILE AND BUFFER


1010 OPEN "PEOPLE.DAT" FOR OUTPUT AS #1
1020 REM OUTPUT THE CLIENT DETAILS TO THE FILE
1030 FOR INDEX = 1 TO 5
1040 WRITE # 1, NAME$(INDEX)
1050 WRITE # 1, ADDRESS$(INDEX)
1060 WRITE # 1, PHONE.NUMBER(INDEX)
1070 NEXT INDEX

WRITE #1, Variable command writes the information through the buffer to the file.
Once all data has been written, then it is necessary to inform the system that the buffer
can be closed (ie, it is no longer needed). This is done by,

1080 CLOSE #1

READING DATA FROM A SEQUENTIAL FILE The command to read data from a
file is,

INPUT #1, Variablename

In order to read the five client details, the following is done,

1200 OPEN "PEOPLE.DAT" FOR INPUT AS #1

[email protected] 188
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA

1210 FOR INDEX = 1 TO 5


1220 INPUT #1, NAME$(INDEX)
1230 INPUT #1, ADDRESS$(INDEX)
1240 INPUT #1, PHONE.NUMBER(INDEX)
1250 NEXT INDEX

HANDLING THE END OF A FILE (EOF) There are times when the number of
records associated with a file may not be known. The EOF (end of file ) command is
useful here.
Example,

1200 OPEN "PEOPLE.DAT" FOR INPUT AS #1


1210 LET INDEX = 1
1220 WHILE NOT EOF(1)
1230 INPUT #1, NAME$(INDEX),ADDRESS$
(INDEX),PHONE.NUMBER(INDEX)
1240 LET INDEX = INDEX + 1
1250 WEND

EXERCISE F1 Implement a BASIC program which allows the storing and recalling of
a group of student marks. The program is to output the highest and lowest marks, as well
as the mean. Use an array to store the names and marks. Using an output file, sort the
student names, marks into ascending order, so that the student with the highest mark
will be written first. The details are,

Student 1 Joe Bloggs 56


2 Bill Anderson 24
3 William Tell 78
4 Bob Crane 23
5 Peter Hall 57
6 Charles French 76
7 Bryan Goldwater 65
8 Stewart Phelps 89
9 Dave Stevens 78
10 Ted Rosse 64

- Create an input file which contains the above information

- Write a program which inputs the file, sorts it descending order, then writes the sorted
information to a new output file.

[email protected] 189

You might also like