77
Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content c 1999–2001 Richard Wareham

Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Embed Size (px)

Citation preview

Page 1: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Visual Basic – Level I

Richard Wareham

2001 – 2002 editionContent c©1999–2001 Richard Wareham

Page 2: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

2

Page 3: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 1

Introduction

1.1 About this course

This course has been designed for the newcomer to programming who requiresa basic understanding of this highly popular programming language. Thiscourse covers program planning and design, formulating algorithms, enteringcode, testing and error trapping, creating documentation for programs andproducing a course project. The course will cover level 1 of the City andGuilds Course. Successful students will gain the City & guilds Certificate inComputer Programming 7261-205.

A working knowledge of the Windows 95/98/NT 4.0 operating system isrequired.

The course takes place on Wednesday evenings.The assessment takes the form of both practical and written exercises.

You must undertake three practical assessments and one written test.You should have received a copy of the syllabus in your log book. It is

suggested that you date and sign the entry in the syllabus when you completeit.

1.2 About your tutor

My name is Rich Wareham. I will be your tutor for the course. Please donot hesitate to contact me if you require assistance or you wish to commenton the notes. I can be reached in the following ways:

• My e-mail address [email protected].

• You can find a web-site containing these notes and example programsby pointing your web-browser at http://www.srcf.ucam.org/ rjw57/vb

3

Page 4: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

4 CHAPTER 1. INTRODUCTION

(from October 2002).

Of these methods, e-mail is preferable if you have it. If not, you can askat the office and they will pass a message on.

1.3 About these notes

These notes are designed to be a complete description of the syllabus. Theyshould cover everything you need to know. Despite this I strongly recommendthat you take your own notes, either on the reverse of these sheets or onseparate paper because:

• I may mention or show something to you that is useful but outside thesyllabus.

• The notes may contain errors and/or omissions.

• You may wish to write something in a style you find easier to under-stand or which covers more detail.

They are also written in a ‘tutorial’ style. That is, if you have VisualBasic at home, you can work through the exercises and examples without mestanding over your shoulder. We will go through the examples in the notesin detail during lessons. You may find it useful to have the notes beside youduring these examples.

In order to be able to download and print/view these notes at home, youmust have a PostScript viewer or a copy of LATEX. There is also a web-browsable version. A suitable viewer is Ghostscript. More instructions areavailable on the web-site.

I try to release notes on the web-site the same evening I teach them sothat, should you miss a lesson, you can print them out at home.

1.3.1 Conventions

A number of typographic conventions have been used in these notes to helpyou put some words in context. The following table notes many of them.

Example MeaningBold face Important words, worth remembering or noting.Monospaced Computer code, Input/output to/from the computer.Emphasised Used to denote new concepts or the introduction of Jargon words.Sans Serif Properties or Names of controls

Page 5: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

1.4. WHO IS THIS COURSE FOR? 5

1.4 Who is this course for?

There are a number of reasons people may want to take this course. I willassume knowledge of how to use Windows to do things like:

• Copying files to and from disk.

• Creating directories (folders) on disks.

• Opening and saving files.

• The function of most controls (scroll bars, option buttons, commandbuttons, etc.).

Familiarity with some sort of word-processor, for example Microsoft WordOpenOffice (which can be freely downloaded from http://www.openoffice.org/ )or AbiWord (which can be freely downloaded from http://www.abisource.com/ ),would be useful.

No programming experience is necessary. Of course, some experiencewould be an advantage.

Page 6: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

6 CHAPTER 1. INTRODUCTION

Page 7: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 2

The basics

2.1 So what is programming exactly?

A programmer is, in its simplest definition, someone who gives a list of in-structions to a computer and a set of rules to tell it what instructions tocarry out when. Computers are essentially stupid. They can do only twothings:

• Arithmetic, like adding, subtracting, multiplication and division.

• Logic. An example or this is ‘only do X if Y and Z have happened’.

The reason computers can do such a wide variety of things is that they al-low very large numbers of simple operations, like the ones above, to be strungtogether. The core part of the Linux operating system (no applications, justthe basics which make programs work) has 3,262,165 of them1.

The act of programming is stringing these instructions together in sucha way that they do something useful. They must also be presented in a waythe computer can understand.

Computers cannot (yet) understand English instructions. There are justtoo many words and phrases for the computer to understand (can you imaginetrying to describe the function of a boiled egg to a computer?). Instead, anumber of ‘languages’ have been developed that computers can understandand that people can program in. These are known as programming languages.

There are normally programs that convert this language into the universallanguage of computers, binary. This is a method of encoding informationusing just 1s and 0s. This binary language is called machine code.

1Standard Linux kernel version 2.4.5

7

Page 8: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

8 CHAPTER 2. THE BASICS

2.2 Visual Basic

BASIC is known as one of the easiest programming languages for beginnersto learn and understand. In fact, ‘BASIC’ is an abbreviation for ‘Beginners’All-purpose Symbolic Instruction Code’. Visual Basic is an extension to thislanguage developed by Microsoft to allow you to create windows on the screenby ‘drawing’ them (much like a computer art program) rather than havingto describe them to the computer using just text.

From this point on, for convenience, we shall refer to Visual Basic as‘VB’.

Page 9: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 3

A Brief Tour of VB

3.1 The VB Main Window

In common with most Windows applications, VB is a MDI (Multiple Docu-ment Interface) application. This means that you can have several files openin their own windows inside the main window. There are several areas youshould be familiar with.

An image of the VB main window is shown in figure 3.1.

There are several main areas

• Menu bar

• Toolbar - Buttons which provide a short cut to options available onthe menus.

• Toolbox - This contains the controls that you can ‘paint’ onto a formwhen you create it.

• Project Window - Shows what objects (see later) your project con-tains.

• Properties Window - Allows you to change the properties of objects(see later). You can choose which object’s properties to change bychoosing it from the drop-down list box indicated.

• Help-box - Contains a brief description of what the property means/

• Form layout - Where the form will appear on screen in the finalprogram.

9

Page 10: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

10 CHAPTER 3. A BRIEF TOUR OF VB

Figure 3.1: The main VB window

It is recommended that you experiment with the buttons on the screen.Holding your mouse pointer over a button will pop-up a box containing abrief description.

I draw your attention to the syllabus section 1.2. Read this carefully andwhen you feel you understand the function and use of all of these areas thensign the box off. Of course the best way to gain experience of these areas isto experiment!

Page 11: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 4

Programming Basics

4.1 Objects and Properties

Before we move onto actually using VB, a brief grounding in the theory ofprogramming would be useful. Recently (in programming terms) a new wayof looking at data in programming has become dominant. Anyone who hasused some legacy languages, such as FORTRAN or even earlier versions ofBASIC will be familiar with the fact that, in old languages, there is a distinctseparation between data and operations you can perform on the data (knownas functions, a subject we shall cover later).

VB, in common with many modern languages, takes a new approach toprogramming which is very fashionable at the moment. It is called objectorientated programming, or OOP. As the name suggests, the keystones ofthis technique are objects.

An object, in programming terms, can be any collection of data. Forexample it could be the name, address and age of a person. This data canbe lumped together in an object known as a Person. To take a real-worldexample, consider a Clock object. A definition of the Clock object could be:

• Clock

– Properties

– Seconds

– Minutes

– Hours

– Colour (read-only)

– Methods

11

Page 12: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

12 CHAPTER 4. PROGRAMMING BASICS

– Reset

– Destroy

Note that an object has associated with it properties and methods. Aproperty is some data that distinguishes this particular object from otherobjects that are like it and a method is something you can do to the object.In the Clock example it has properties that allow you to set and read thecurrent time. The Colour property is read-only, that is you can’t change thecolour of the watch, only look at it.

There are two methods, ways of acting on the data. You can Reset thewatch (normally setting it to the current local time) and you can Destroyit. This method is common to all objects. In the context of programming,this frees up any memory that the object has used to store the data aboutitself. You should not have to worry about this as VB automatically Destroysobjects when you no longer need them. VB can do this as it automaticallycreates objects when you need them.

Notice how I am using a different font to refer to objects, properties andmethods. This is so you always know what I am referring to in the text.Whenever text appears in this font, it refers to some programming object.

As an example of a programming object, consider the one object thatalmost all VB applications use, the Form object. This object represents awindow on a screen. Here are the properties and methods you will probablyfind useful.

• Form

– Properties

– Name

– BackColor

– Caption

– Height

– Left

– Top

– Width

– Visible

– Methods

– PrintForm

Page 13: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

4.2. EXERCISES 13

– Show

– Hide

I could go through all of these and tell you what they all mean, howeveryou can use the Visual Basic help which is far better and searchable.

A quick note on how to refer to an object’s methods or properties; gen-erally the method used in VB is to use a full-stop to separate object namesand method names like this.

Object.Property

or

Object.Method

For example, the first Form that VB creates is called Form1. To changethe caption (the text in the title-bar) you can use the following VB code:

Form1.Caption = "Some Text"

Notice that the ‘=’ character should be read as ‘is assigned the value of’.All text that isn’t some program code should be enclosed in quotes. Numbers(in digits) do not. For example, to set the width of the form to 1000, youwould use

Form1.Width = 1000

A similar method is used to do (or call) a method. Suppose I wanted tohide Form1 (to hide a form means the form still exists but is just not shownon the screen). I could use code like this:

Form1.Hide

4.2 Exercises

At the end of most chapters there are some excercises. I may ask you to dothem in class or you may opt to do them in your own time. Unless otherwisestated please do the questions on a seperate sheet of paper.

Answer the following questions:

1. If I had defined an object called Person with the properties Name andAge, write two lines of code that sets the Person object, named Person1,to reflect someone called "John Smith", aged 43.

2. Suppose this object also had a method called Inform that sends anupdate of your company’s status to the person. Write one line of codeto inform John Smith of your company’s status.

Page 14: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

14 CHAPTER 4. PROGRAMMING BASICS

Page 15: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 5

VB Fundamentals

5.1 The Project

An application, like a Word document, typically consists of several differentsorts of files. For example the code you write is stored in text file, pictures inyour forms are stored as bitmap files and of course the forms that you designmust be stored in files. Files that are stored in your project are:

• Form (.FRM) files - Contain a textual description of your forms andthe code which they use.

• VB module (.BAS) files - Contain code which is designed to be re-usedby many forms.

The project is a file which tells VB which files are used in your application.They have the extension .PRJ ot .MAK. You can save these projects by usingthe File→ Save Project menu item (or use the floppy disc icon on the toolbar).This will save all your forms and code and then update the .PRJ file to reflectall the files that your application uses.

It is recommended that you save each project in a separate directorybecause they consist of several files. Let us go through the process of creatinga simple application.

In later versions of VB (such as the onw you are using), te project file isgiven the extension .VBP, and in earlier versions .MAK. All of these meanthe same thing.

5.2 My First Application

Open VB and you will be presented with the default start up screen. Choose‘Standard .EXE’ from the box and click OK. A window is opened containing

15

Page 16: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

16 CHAPTER 5. VB FUNDAMENTALS

the first form in the project. A form is a container of controls.

Change the (Name) property to frmMain. This is the name of the objectused when you refer to it in VB (see previous chapter).

Change the Caption property to "Personal Details".

Use the toolbox to draw the controls on the form shown in figure 3.1. Tochange the text in the labels and buttons, change the Caption property. Tochange the text in the text-boxes, change the Text property.

Change the (Name) properties of the text-boxes and button (not thelabels) to the following values:

• Text-box next to the ‘Name’ label should be called txtName.

• Text-box next to the ‘Age’ label should be called txtAge.

• The button should be called cmdOK.

Note you can’t have any spaces in the name. You could call the controlsanything you like but if you follow the suggestions I have made above, youwill be able to follow this example more easily.

Now would be a good time to save the project. Click the floppy disc iconon the toolbar. A save box will pop up. Move to your home directory (theone with your name in it). Note that you are saving the form. The namegiven (MainForm.frm) should be OK. After this you will be asked to save theproject file (call it something like PersonalDetails.vbp).

Click the play button on the toolbar (it ‘textbfruns’ your program) andplay with your new form. Close the window when you are done.

We will be creating an application that will pop up a new form when youclick the OK button. Let us create the new form. Choose Project → AddForm from the menu. Choose ‘Form’ from the dialog box and click OK.

Set the following properties of the new form (make sure you change thenew form!)

• (Name) - frmDetails.

• BackColor - Change to whatever colour you want.

• Caption - "Your Details".

• MaxButton and MinButton - False (This means that it looks like a dialogbox).

Page 17: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

5.2. MY FIRST APPLICATION 17

Figure 5.1: How the user details form should look

Create some labels so the form looks like the one in figure 5.1. You willneed to alter (amongst other things) the label’s Alignment property to ‘2 -Center’ and the BackStyle property to ‘0 - Transparent’.

Change the (Name) of the Close button to cmdClose and the (Name) ofthe OK button to cmdOK. Change the names of the NAME and AGE labelsto lblName and lblAge respectively.

Go back to the frmMain window. Double-click the OK button. A windowpops up with the following text in.

Private Sub cmdOK_Click()

End Sub

Change it so that it reads:

Private Sub cmdOK_Click()

frmDetails.Show

End Sub

Notice that we have started giving our controls meaningful names. For ex-ample, all Forms have names startinf with ‘frm’, labels with ‘lbl’ and buttonswith ‘cmd’ (as they are technically known as command buttons).

What we have done is add a line of code that tells VB to show thefrmDetails object when the OK button is clicked. Press the play-button on

Page 18: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

18 CHAPTER 5. VB FUNDAMENTALS

the toolbar now. Clicking on the OK button causes frmDetails to pop up.The close button does not yet work as you haven’t yet added any code to it.

Close the two windows to get back to the windows you design forms in.Move to the frmDetails window. Double-click the Close button and changethe code to read:

Private Sub cmdClose_Click()

frmDetails.Hide

End Sub

Notice how, when you start typing the method names, a window pops upwith the valid names in it. This is to help you if you forget the exact name.You can complete any method name by selecting the correct one from thelist and pressing the Tab key.

Pressing the play-button will reveal that the Close button now works.One final thing has to be added. Move to the MainForm window and doubleclick the OK button. Change the code to read:

Private Sub cmdOK_Click()

frmDetails.lblName.Caption = txtName.Text

frmDetails.lblAge.Caption = txtAge.Text

frmDetails.Hide

End Sub

Well Done! You have created your first application.Save the project.

5.3 Project Files (Syllabus 2.3)

When you create a VB program, you are actually creating several files. Thereare two main sorts of files you will be creating:

• .FRM - These hold the definition of a form. Each form that you de-sign will have one .FRM file associated with it. They contain both adescription of the controls on the form and the code which you write.

• .VBP - These contain, conceptually, a list of files that your programuses. Each time you create a form, the corresponding .FRM file isadded to the .VBP file. These are known as project files.

• .BAS - Any code that you type in that does not have a form associatedwith it (i.e. utility programs that do things like calculating stock levelsor pulling data from databases) is stored in these files.

Page 19: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

5.4. EXECUTABLES 19

This information is correct for Visual Basic 5.0. The syllabus was writtento match Visual Basic 3.0. This means that the syllabus uses different files.Should you sit any tests, use the following file extensions. Whenever youactually use VB, remember the filenames above.

The .FRM and .BAS files remain the same but project files are stored witha .MAK extension. When you think .VBP, write .MAK in the test.

5.4 Executables

VB can pack all your Form definitions and code files together into one singlefile which can be distributed and used on computers which do not haveVB installed. These are called executable (.EXE) files and are the standardformat used on all Windows machines to contain programs.

To save out an .EXE file, choose ‘Make XXXX.exe...’ from the File menu.This opens a standard ‘Save As...’ dialog box which you can use to save your.EXE file.

5.5 Exercises

1. Add a button called cmdExit with the caption ‘Exit’ to frmMain. Whenclicked the following line of code should be executed:

End

Check the exit button works as expected.

2. Extend the application to include three address lines and a date ofbirth.

Page 20: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

20 CHAPTER 5. VB FUNDAMENTALS

Page 21: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 6

Controls

There are several types of controls that you can ‘paint’ onto the form. VBhas the ability to include custom-written controls onto forms. A companymay write a dial control or one that displays an Excel worksheet. The useof these advanced controls is not covered in Level 1. The standard controlsare:

• Label control, - These are simply pieces of text on a form. Youcan very the font, the alignment (centre, left and right justified) andmay, optionally, have a border. Very useful for displaying text. Itis recommended that you call them names beginning with ‘lbl’, e.g.‘lblText’, ‘lblAge’, etc.

• Text box control, - A box which you can enter text and/or num-bers. They can be multi-line (i.e. act like a version of Notepad) andcan possess scroll-bars. Names should begin with ‘txt’.

• Frames, - A labelled box that can be used to group related con-trols. They may, optionally, possess a caption in the top-left. It isunlikely you shall have to name a frame.

• Command buttons, - A button that the user can press and apiece of code that you specify will be executed. They should havenames beginning with ‘cmd’.

• Checkboxes, - A tick-box that the user can, well tick! The Valueproperty is 0 when the box is unchecked and 1 when it is checked. Their

21

Page 22: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

22 CHAPTER 6. CONTROLS

names should begin with ‘chk’.

• Radio Buttons, - Like a button on an old-fashioned tranny, onlyone radio button from a group can be selected at once. Their namesshould begin with ‘rad’. These are also called option buttons.

• Combo Box, - A text box with an arrow on the right. Clickingthe arrow pops up a list with possible values. An example of this wouldbe the ‘Look in’ box on an ‘Open’ or ‘Save As’ dialog box. They arealso known as ‘Drop-down list boxes’.

• List Box, - A box that contains a list where you can select anumber of items. You can specify whether you wish only one item tobe selectable or several. Names should begin with ‘lst’.

• Horizontal and Vertical Scroll Bars, - Scroll bars that actas, well scrollbars. You can set the maximum and minimum valuesand they have a Value property dependant on the position of the littleslider tab (which was known in earlier versions as the ‘thumb’). Namesshould begin with ‘scrl’.

• Image, - Not to be confused with a Picture Box (the similar iconin the top-right of the toolbox). This control can not-only display animage but can also respond to mouse-events (such as clicks, drags, etc).Names should begin with ‘img’.

• Line, - Possibly the simplest control. Is simply a line on a Form.May be used as a separator or decoration.

• Timer, - Executes a bit of code every n milliseconds (where n isactually the Interval property). Names should begin with ‘tmr’.

There are other controls of course but these are the ones specified in thesyllabus.

Page 23: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

6.1. CONTROL PROPERTIES (3.2) 23

6.1 Control Properties (3.2)

You have already had experience of changing properties of controls and mov-ing them and resizing them. Luckily this is what the syllabus specifies astarget 3.2.1. You can sign this off now should you wish.

6.2 Exercises

1. For each of the controls listed above, try changing the properties below(if the control has them) and see what they do.

• Alignment

• Caption

• BackColor

• ForeColor

• Width

• Height

• Value

• Text

• BorderStyle

• Visible

Page 24: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

24 CHAPTER 6. CONTROLS

Page 25: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 7

Variables and Comments

7.1 Comments

Often when writing a program you would like to comment your code toindicate what certain lines do. Consider the following example line of code:

frmReport.lblAge.Caption = Person.Age

Although clear at the time of writing, such code can often be confusingto another programmer working on the project or you after not using thatparticular line for some time. When VB sees a ’ character (apostrophe) itwill ignore the rest of the line.

An example of the use of this would be:

‘ This line sets the ‘Age’ field in the frmReport to

‘ reflect the current person’s age.

frmReport.lblAge.Caption = Person.Age

Always comment your code but do not go to extreme. It is sufficient tocomment the function of discrete blocks of code rather than comment everyline. For example, several lines could be commented as ‘Updates frmReport

to reflect the current Person’.

7.2 Variables

If you have ever moved on from the 2 + 2 = 4 area of maths, you will befamiliar with the concept of variables in maths. For example, if I were towrite:

25

Page 26: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

26 CHAPTER 7. VARIABLES AND COMMENTS

x = 1

What I mean is that ‘from here on, when you see x, read it as ‘1”. Incomputer programming we can do the exact analogue. The following is validVB code:

X = 1

Which tells VB ‘every time you see ‘X’ (not part of a word) replace itwith ‘1”. This is not exactly the same as the mathematical example. Forexample, if I were now to write:

x = x + 1

This would make no sense since 1 + 1 is clearly not equal to 1. In VB,the ‘=’ sign is read as ‘is assigned the value of’ (written mathematically as← ). If I were to add a line to the VB code above, to read:

X = 1

X = X + 1

and the corresponding maths:

x = 1x ← x + 1

Then this is valid. VB reads this as ‘X is assigned the value of 1’ (so Xnow is 1) followed by ‘X is assigned the value of X + 1’. Since X + 1 = 1 +1 = 2 then X now becomes 2. A convenient analogy is to imagine that thecomputer creates a box, labels it with ‘X’ and places ‘1’ in it. The secondline takes this value, adds one, and puts it back in the box.

The power of computers lies in the fact they can manage hundreds uponthousands of variables and perform literally millions of simple operations likethis upon them. Combinations of these can do simple things like calculatingyour monthly accounts to modelling the very structure and fabric of theUniverse.

A convenient mathematical theorem states that any computable, math-ematical operation can be performed with a sequence of four operators, ad-dition, subtraction, multiplication and division (actually there is only oneoperation, addition, the others are special cases of it).

The definition of what it means to be computable is subtle and not re-quired (in any way) for this course but provides an interesting insight intowhat computer cannot do even in principle.

Page 27: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

7.3. EXAMPLE 27

Figure 7.1: Mathematics example

7.3 Example

I will start to give these examples more in the style of practical assignmentsto get you used to the style.

1. Create a new project and create a Form named frmMath and changeits Caption property to ‘Math Example’.

2. Create a button called cmdCalc with the Caption ‘Calculate’.

3. Create two TextBoxes called txtInput and txtOutput along with twoLabels with the Captions ‘Input:’ and ‘Output:’. Move these controlsto the positions in figure 7.1.

4. Double-click on cmdCalc and enter the following code:

Private Sub cmdCalc_Click()

’Get input

x = txtInput.Text

’Perform the calculation

x = x * 2

’Reflect answer

txtOutput.Text = x

End Sub

Page 28: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

28 CHAPTER 7. VARIABLES AND COMMENTS

5. Run the program.

If you type a number into the input box, when the ‘Calculate’ buttonis clicked, the variable ‘x’ is assigned the value you typed. It is multipliedby two and the result put in the output box. There are four main types ofoperation:

Character Example Means

+ c = a + b ‘c’ is assigned the value of ‘a’

plus ‘b’ (addition)

- c = a - b ‘c’ is assigned the value of ‘a’

minus ‘b’ (subtraction)

* (asterisk) c = a * b ‘c’ is assigned the value of ‘a’

times ‘b’ (multiplication)

/ (slash) c = a / b ‘c’ is assigned the value of ‘a’

divided by ‘b’ (division)

Try changing the program to add two to the input, subtract two from theinput and half it (divide it by two). Do each task seperately!

7.4 Exercises

1. Change the program we created in this chapter to have a main formthat looks like figure 7.2.

The top TextBox should be called ‘txtInput1’ and the middle TextBoxshould be named ‘txtInput2’. Change the program to, when the ‘Cal-culate’ button is pressed, perform the following operations:

• Create a variable named ‘x’ which contains the contents of thefirst input box.

• Create a ‘y’ variable with the contents of the second box.

• Add a line of the form z = x + y which adds ‘x’ and ‘y’ placingthe resulting answer in a variable called ‘z’.

• Put the contents of ‘z’ in the output box.

Page 29: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

7.4. EXERCISES 29

Figure 7.2: Mathematics example 2

2. Change the program using the table at the top of the page to firstlysubtract the two numbers. Once you have completed this, change it tomultiply them and finally to divide them.

3. Change the line of code that begins ‘z =’ to the following:

z = 2 * (x + y)

This should cause the program to add the two input numbers andmultiply the result by two. Change the line to read:

z = (2 * x) + y

Does this change the functioning of the program. Why? How wouldyou describe the difference the position of the brackets makes.

4. The BoDMAS rule is often used in maths. BoDMAS stands for:

B - Brackets

D - Division

M - Multiplication

Page 30: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

30 CHAPTER 7. VARIABLES AND COMMENTS

A - Addition

S - Subtraction

This defines the precedence of the operations. I.e. you calculate brack-ets before anything else. Use this rule to calculate the following sums:

(2 * 8) + 12 / 6 + 8 - 9

8 / 4 + 6

8 / 4

(6 + 8) / 4

5. Create four buttons with the Captions ‘+’, ‘-‘, ‘/’ and ‘*’. Make thesebuttons add, subtractm divide and multiply the numbers in the inputboxes as required and place the answer in the output box.

Add a label named ‘lblOp’ to the form and make each button changethis label’s Caption to show what just happened (e.g. the ‘+’ buttonmay change lblOp’s caption to read ‘Last operation: addition’).

Page 31: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 8

Sub-procedures

8.1 ‘Blocks’ of code

We have seen already VB code like

Private Sub cmdCalc_Click()

’Get input

x = txtInput.Text

’Perform the calculation

x = x * 2

’Reflect answer

txtOutput.Text = x

End Sub

Just like we can assign controls and forms names, we can assign blocksof code like this names. The first and last lines of this code say delimit (orshow the boundaries of) the block of code. The first line states that thesubroutine should be called cmdCalc Click. The open and close brackets areused for specifying arguments (see later notes).

REBEMBER – WHENEVER YOU START A NEW PROGRAMIN VB, CLOSE DOWN VB AND RE-START IT!

31

Page 32: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

32 CHAPTER 8. SUB-PROCEDURES

Figure 8.1: Procedure example 1

Create a new project and name (set the (Name) property) the new formcreated as MainForm. Add a label named lblMessage and two commandbuttons named cmdButton1 and cmdButton2. Arrange the controls so thatyour form looks like figure 8.1. Remember, the window has a grid onit. Use it!

SAVE THE PROJECT AT THIS POINT. Revision:

• Minimise VB (Click the little icon).

• Double-click the ‘My Work’ icon on the desktop.

• Right-click over the window that came up and select New → Folder.

• Call the new folder ProcedureEx

• Go back to VB. Choose File → Save Project As....

• Save all the files in your new ProcedureEx directory.

Double-click on both Button 1 and Button 2. This adds some code toyour project. Remember that things we want to do when Button1 is clickedupon goes between the lines that refer to it. Similarly for Button 2.

Change the code so that it reads:

Private Sub cmdButton1_Click()

lblMessage.Caption = "Button 1 pressed."

Page 33: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

8.1. ‘BLOCKS’ OF CODE 33

Figure 8.2: Procedure example 2

End Sub

Private Sub cmdButton2_Click()

lblMessage.Caption = "Button 2 pressed."

End Sub

Run the program (click the ‘play’ icon on the tool-bar) and confirm thatit behaves as you would expect. Note that we have already created twosub-routines, cmdButton1 Click() and cmdButton2 Click(). When Button 1 ispressed, VB runs the code in the cmdButton1 Click() sub-routine and whenButton 2 is pressed, VB runs the code in the cmdButton2 Click() sub-routine.

Add a label named lblSubMessage in between the two buttons. The win-dow will now look like figure 8.2.

Go to the code window (the place you edit the code) and add the followingto the bottom of the text.

Private Sub printMessage()

lblSubMessage.Caption = Rnd()

End Sub

When you run the program, VB treats Rnd() like a special variable thatalways holds a random value. Change the lines in the Click sub-procedures,to read as

Private Sub cmdButton1_Click()

Page 34: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

34 CHAPTER 8. SUB-PROCEDURES

lblMessage.Caption = "Button 1 pressed."

printMessage

End Sub

Private Sub cmdButton2_Click()

lblMessage.Caption = "Button 2 pressed."

printMessage

End Sub

You should see that we have added a new sub-routine to the programcalled printMessage(). This sets the caption of lblSubMessage to a randomvalue. The two lines of code added to the existing sub-routines mean ‘do thecode contained in the sub-procedure we have defined called printMessage()’.

8.2 Exercises

1. Remove the line of code that reads printMessage (i.e. delete one line)from the cmdButton2 Click() sub-procedure. What effect does it haveon the functioning of the program. Is this what you expected?

2. Change the code defining printMessage() to read

Private Sub printMessage(num)

lblSubMessage.Caption = num

End Sub

and then the code for the Click() sub-procedures to be

Private Sub cmdButton1_Click()

lblMessage.Caption = "Button 1 pressed."

printMessage (1)

End Sub

Private Sub cmdButton2_Click()

lblMessage.Caption = "Button 2 pressed."

printMessage (2)

End Sub

And run the program. What has changed? Why do you think theprogram now works as it does? A new variable called num appears to

Page 35: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

8.3. EVENT ROUTINES 35

Figure 8.3: Event driven programming example

have been created in printMessage. What determines its value? [Theseare called ‘arguments’ and are very useful ways of passing data betweensub-procedures.]

8.3 Event Routines

An event routine is a sub-procedure which is called when something happensto a control. This may be due to a user interacting with the control or theprogrammer changing the control from the program code. You have alreadybeen using some event routines, the Click event is used by buttons to callcode when buttons are clicked upon.

The practice of defining certain blocks of code to be executed (or carriedout) when certain events occurr is termed event-driven programming.

Add a label named lblStatus to the Form created above so it looks likethis. Note that you will need to alter some of its properties. Specificallythose dealing with its colour and border style.

The new label at the bottom is lblStatus. Your completed form shouldlook like figure 8.3.

Bring up the code window (e.g. by double clicking on Button 1). Thereare two drop-down list boxes on this window (figure 8.4).

Choose cmbButton1 from the combo box (the white bar with the arrowattached to it) on the left and MouseMove from the one on the right. You

Page 36: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

36 CHAPTER 8. SUB-PROCEDURES

Figure 8.4: Event boxes on code-editor window

should notice that a new sub-procedure has been created. This is an EventProcedure. Add code to this procedure so that it looks like this.

Private Sub cmdButton1_MouseMove(Button As Integer, Shift As Integer,

X As Single, Y As Single)

lblStatus.Caption = "MouseMove - cmdButton1"

End Sub

Similarly create a procedure for cmdButton2. Do this by choosing cmdButton2from the list on the left and MouseMove on the right. This time, it shouldread like

Private Sub cmdButton2_MouseMove(Button As Integer, Shift As Integer,

X As Single, Y As Single)

lblStatus.Caption = "MouseMove - cmdButton2"

End Sub

Run the program. As you can see, the MouseMove event is called when-ever the mouse passes over the corresponding control.

8.4 Exercises

1. Add a MouseMove event handler to the Form object (MainForm). Itshould clear the caption of lblStatus (Hint: try changing the caption to"").

2. Experiment with other event handlers and add other controls. Makethe event handler change lblStatus to announce when it is called. Seeif you can find what the following events are for:

• Change event from VScrollBar and HScrollBar controls (Hint: prob-ably a good idea for the event handler to display the Value propertyof the scroll bar in lblStatus).

Page 37: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

8.4. EXERCISES 37

• DoubleClick event from CommandButtons.

Page 38: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

38 CHAPTER 8. SUB-PROCEDURES

Page 39: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 9

Properties by the bucket load!

This lesson has short notes. I will summarise every property you wil beexpected to know about. The practical exam may ask you to ‘set the la-bel lblBob to be center aligned’. In this case you should set the Alignmentproperty of the label to 2 - center.

First a bit of jargon. When you are drawing your controls onto a Formin VB (i.e. when your program isn’t going, you are writing it), it is calleddesign-time. When your program is actually going (when it is doing things),it is called run-time. Some properties (like (Name)) can only be set atdesign-time (it would make little sense for VB to change the names it iscalling controls throughout the program!). Others, like Caption can be setboth at design-time run-time.

Further, some properties can only be read. Some only can be set. Whena property is read. For example like this:

x = lblBob.Caption

It is said to return a value. So when the list below says ‘Returns ...’it means that it has some value when used in a statement above. We willdiscuss these properties in class.

There are several important things that must be learnt for the exam:

• Any one control has only a subset (a small number) of these properties.

• The control and the properties associated with it are called an object.

• The properties of a control may not always be changeable at run-time(see syllabus 3.2.10).

39

Page 40: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

40 CHAPTER 9. PROPERTIES BY THE BUCKET LOAD!

9.1 Text related properties (3.2.3)

1. Alignment – Returns or sets a value that determines the alignmentof the text in a CheckBox or OptionButton control. Read-only at runtime for CheckBox, OptionButton, and TextBox controls

2. Caption – Has different meanings for different controls

• Form – determines the text displayed in the Form or MDIForm ob-ject’stitle bar . When the form is minimized, this text is displayedbelow the form’sicon.

• Control – determines the text displayed in or next to a control.

3. FontBold & FontItalic & FontUnderline – Returns or sets fontstyles in the following formats: Bold, Italic, Strikethru, and Underline.

4. FontTransparent – Returns or sets a value that determines whetherbackground text and graphics on a Form or Printer object or a Picture-Box control are displayed in the spaces around characters. (see laternotes)

5. FontSize – Sets the size of the font used in the control.

6. MultiLine – Returns or sets a value indicating whether a TextBoxcontrol can accept and display multiple lines of text. Read only at runtime.

7. (Name) – Sets the name VB calls this control. This cannot be chgangedduring the running of a program. The user does not normally seethis.

8. PasswordChar – If not empty, a TextBox will display this characterinstead of what you type in, useful for password boxes. The Textproperty still holds what the user typed in.

9. Text – Returns or sets the text that is contained in a TextBox.

10. Wordwrap – Returns or sets a value indicating whether a Label con-trol with its AutoSize property set to True expands vertically or hor-izontally to fit the text specified in its Caption property. (i.e. if thisis TRUE then a label will wrap the text to fit its size. If FALSE allthe text will be on the same line.

Page 41: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

9.2. COLOUR RELATED PROPERTIES (3.2.4) 41

9.2 Colour related properties (3.2.4)

Many controls have the following properties. Their names are quite descrip-tive. Notice that they are spelt the AMERICAN way.

1. BackColor – Returns or sets the background colour of a control.

2. ForeColor – Returns or sets the foreground colour of a control.

3. FillColor – Returns or sets the colour sed to fill solid shapes in acontrol (e.g. see the Shape control).

4. BorderColor – Returns or sets the border colour of a control (best toexperiment, applies to Lines, Shapes and TextBoxes.

9.3 Functional Properties (3.2.5)

1. Checked – For Checkboxes, if TRUE then the box is checked, FALSEotherwise

2. Enabled – If TRUE, the user can use the control. If FALSE then thecontrol is ‘greyed out’

3. Interval – For Timers. Every Interval milliseconds, the event sub pro-cedure created by double-clicking on the Timer will be called.

4. LargeChange – Returns or sets the amount of change to the Valueproperty setting in a scroll bar control (HScrollBar or VScrollBar) whenthe user clicks the area between the scroll box and scroll arrow.

5. SmallChange – Returns or sets the amount of change to the Valueproperty setting in a scroll bar control when the user clicks a scrollarrow.

6. Max – The maximum value a scroll-bar can have.

7. Min – The minimum value a scroll-bar can have.

8. Value – The value of a scroll-bar (subject to above properties).

Page 42: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

42 CHAPTER 9. PROPERTIES BY THE BUCKET LOAD!

9.4 Positional properties (3.2.6)

1. Height – The Height (in a silly unit called a ‘twip’) of a control orForm.

2. Left – The position relative to the screen (Form) or containing Form(any other control) of the Left edge of the control.

3. Top – Similar to Left but gives the position of the Top of the controlfrom the top of the screen/containing form.

4. Width – Like Height but the width of the control.

5. X and Y – The X and Y co-ordinates of some point (see Line control).

9.5 Exercises

1. Create a new project and draw one label and name it lblMessage, onevertical scroll-bar called vscrlSlider and one command button namedcmdDoIt. Change the Caption of cmdDoIt to be Click Me and theCaption of lblMessage to be blank.

Change appropriate properties so that the Value of vscrlSlider changesbetween 50 and 100, moving by 10 when the scroll bar is ‘paged’ andmoving by 1 when the arrows at the top and bottom are clicked upon.

Add event sub-procedures to do the following:

• When the command button is clicked, change the caption of lblMes-sage to You clicked the button and change the FontSize of thelabel to 20.

• Add a vsrclSlider Change() event sub-procedure to change thecaption of lblMessage to the value of the Value property of thescroll-bar.

2. Some display-related properties are shown below. Use the Visual BasicHelp feature to write a description of what they do. Items marked with(*) may be deffered until later in the course.

• BackStyle

• BorderStyle

• BorderWidth

Page 43: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

9.5. EXERCISES 43

• FillStyle

• MousePointer (*)

• Opaque (*)

• Shape (*)

• Transparent (*)

• Visible

• WindowStare

3. Create a Form suitable for use in a data entry package which containsthe following fields. They should be TextBoxes with appropriate prop-erties set. The boxes should be labeled with labels.

• The name of a person.

• Their date of birth (DOB).

• A multi-line TextBox for their address.

• A password field which displays what is typed into is as stars (*).

Page 44: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

44 CHAPTER 9. PROPERTIES BY THE BUCKET LOAD!

Page 45: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 10

Timers and Shapes

Timers and shapes are ‘fun’ controls. They are useful for adding specialeffects of decoration to your program.

10.1 Timers

Timers are special controls that don’t appear on Forms. Their entire purposeis to call an event handler sub-procedure after a specified interval. This canbe used pretty much where you would use a stop-watch in real-life. Forexample, if you are writing a desktop clock application, you can use thetimer to update the clock once every second.

Create a new project and design a form like the one in figure 10.1. The

ellipse is a Shape control ( ). The picture of a stop-watch is a Timer.The text is a Label. MAKE SURE YOU USE THE GRID. Set theproperties of the controls to have the following values:

• Timer1

– Interval = 100

• Label1

– BackStyle = 0

– Alignment = 2

• Shape1

– Shape = 2

– FillStyle = 0

45

Page 46: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

46 CHAPTER 10. TIMERS AND SHAPES

Figure 10.1: A Form with a Shape and a Timer

• Form1

– BorderStyle = 1

– Caption = Flashing Oval

Double-click the Timer icon to add the following code (the lines you haveto type are in bold).

Private Sub Timer1_Timer()

Shape1.FillColor = CLng(Rnd() * &HFFFFFF)

End Sub

Run the program. The oval is now flashing. What we are doing is torandomly change the colour every time the Timer ‘fires’.

A quick note on how we do this. Colours are specified as numbers between&0 and &FFFFFF. 1 The Rnd() function allows us to choose a randomnumber between these numbers. This will give the answer as a ‘Double’(one with numbers after the decimal point). We use the CLng to convert itto a ‘Long’. A Long is like an integer in that they are whole numbers but

1These are special numbers, I’ll explain them in class

Page 47: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

10.2. SHAPES 47

Figure 10.2: An exaple of using a Shape control.

integers can only be between -32768 and 32768 whereas Longs can be between-2147483648 and 2147483648 (but they do require twice the storage).

10.2 Shapes

You have experience of shapes already. You have been using them this lesson.It is best to experiment using them. A Shape is just that; a shape in yourForm. Specifically, Ovals, Rectangles and ‘Rounded-Rectangles’.

Create a Form with an oval in it (Set the Shape property of the controlto 2). Add two command buttons. It will look like Figure 10.2.

Next add the following lines to the code (create the sub-routines bydouble-clicking on the command buttons).

Private Sub Command1_Click()

Shape1.Shape = 0

End Sub

Private Sub Command2_Click()

Shape1.Shape = 2

End Sub

Page 48: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

48 CHAPTER 10. TIMERS AND SHAPES

Figure 10.3: Counter Form

Figure 10.4: Stretchy shape

Run the program.

10.3 Exercises

1. Create a new project with a window like Figure 10.3 that counts up(adding one ever 100 milliseconds)

The timer event should add one to the caption of the Label (rememberto add 1 to a variable called x, you type x = x + 1).

2. Create a new project with a form that looks like Figure 10.4 and addthe following code to the Timer event:

Private Sub Timer1_Timer()

Shape1.Width = Shape1.Width + 100

If Shape1.Width > 4000 Then Shape1.Width = 1000

End Sub

What happens when the program is run. Why?

Page 49: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

10.3. EXERCISES 49

Figure 10.5: Flashy shape

3. Write a program similar to the one above with Buttons to change be-tween all the different shapes available. Create some TextBoxes (in-cluding two called txtWidth and txtHeight) and add a Change eventhandler to them with the following code:

Private Sub txtWidth_Change()

Shape1.Width = txtWidth.Text

End Sub

Private Sub txtHeight_Change()

Shape1.Height = txtHeight.Text

End Sub

(a) What happens when you change the contents of these boxes.

(b) Can you modify the event handlers so that an error is not gener-ated when the box is empty [Hint: Check in the event handler tosee if Text = ”” (the empty string), you can use an ‘If ’ statementlike before].

(c) Add a Load event handler to the Form. Write the correct code tomake sure the text boxes have the right contents.

4. Create a form that looks like Figure 10.5 when run and add the correctcode to make it work

Page 50: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

50 CHAPTER 10. TIMERS AND SHAPES

Figure 10.6: Flashy shape with label names

The correct code is as follows. Please do not look at this code beforeattempting the question!

Private Sub Command1_Click()

theshape.Shape = 0

End Sub

Private Sub Command2_Click()

theshape.Shape = 2

End Sub

Private Sub Command3_Click()

theshape.Shape = 4

End Sub

Private Sub Form_Load()

txtFlashRate.Text = Timer1.Interval

End Sub

Private Sub Timer1_Timer()

theshape.FillColor = CLng(Rnd() * &HFFFFFF)

End Sub

Private Sub txtFlashRate_Change()

If txtFlashRate.Text <> "" Then Timer1.Interval = txtFlashRate.Text

End Sub

The controls are named as in Figure 10.6.

Page 51: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 11

Decisions

It would be fairly boring if all computers could do was add up. Recall thatthere are two parts to computing, arithmetic and logic. Logic, as we useit, means if something has happened then do something. Such a decision iscalled an IF...THEN decision. For example, imagine you had a program thatasked you to multiply 2 and 6 and enter the answer in a box and click on abutton. In the button’s Click event handler you may use some code like this:

If lblAnswer.Caption = (2*6) Then

...

’ Tell the user they are right

...

Else

...

’ Tell them they are wrong

...

End If

Here the comments represent what the code that goes there should do.Even though the lines here are perfectly valid VB code, you can almost ‘read’what is going on.

Generally there are two types of IF...THEN statements that you can use:Type 1

IF A = B THEN ... ELSE ...

Description: Generally you should use this form when you want to dosomething which fits on one line. The part from ELSE onwards is optional.

Type 2

51

Page 52: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

52 CHAPTER 11. DECISIONS

Examples Name Description

A = B Equals Does A equal B?A <> B Not-equal Is A different from B?A > B Greater-than Is A bigger than B?A < B Less-than Is A smaller than B?A >= B Greater-than or equals A has the same or a greater value than B?A <= B Less-than or equals A has a smaller or the same value as B?

Table 11.1: Useful things to put in IF...THEN statements

IF A = B THEN

...

ELSE

...

END IF

Description: Here you can have several lines between THEN and ELSE orEND IF. You should use this when you want to do lots of things if, in thiscase, A = B. Again the ELSE part is optional but one very important thing;if you use this form remember to end it with END IF since missingthis off is well into the top ten of common VB mistakes!

Type 1 is really just a shorthand form of Type 2. You can write otherthings instead of A = B. These are summarised in Table 11.1.

Finally you can collect different things with the words And and Or. Forexample, if the following variables were declared:

A = 23

B = 12

C = 46

D = 7

Then in the following examples only Sub Routine 1 would be called.

If A > B Then

Sub_Routine_1

Else

Sub_Routine_2

End If

If (A < C) And (B >= D) Then

Sub_Routine_1

Page 53: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

11.1. EXERCISES 53

Else

Sub_Routine_2

End If

If (B = C) Or (D > C) Then

Sub_Routine_2

Else

Sub_Routine_1

End If

If (B = C) Or (B < A) Then

Sub_Routine_1

Else

Sub_Routine_2

End If

11.1 Exercises

1. With the values of A, B, C and D above, which of the following aretrue?

(a) B > A

(b) (A < B) Or (C > D)

(c) (A = B) Or (A <> B)

(d) (D < C) Or (A < B)

2. For the false expressions above, are there any values of A,B,C and Dwhich make them true? If so what are they. Similarly are there anyvalues which make the true statements false?

Page 54: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

54 CHAPTER 11. DECISIONS

Page 55: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 12

Breakpoints

Often when writing a program, one finds that it produces unexpected outputbut does not cause VB to exit with an error. In these cases, the concept ofa breakpoint is useful.

These are called run-mode or run-time errors. They happen, not becauseyour VB is wrong, but because it does not catch problems that can occurr.

A run-time error can occur due to errors in coding (see below) or due tounanticipated user actions. For example, a calculator may allow you to entertwo numbers, A and B and then divide them with the VB command answer

= A / B. This is fine in terms of logic and syntax (see paragraph below) butif B = 0 then VB moans it can’t divide by zero. This would result in anunfriendly error message to the user (which is bad!).

Simlarly design-mode errors are errors in design. Either your code is notcorrect (syntax errors) which results in VB shading the line red and moaningat you when you try and type it, or errors in the logic, for example takingthe square of a number with the code x = x * 2 rather than x = x * x.

A breakpoint allows you to stop VB at a point in your program and allowone to examine contents of variables, etc. To see where the error occurred.

Take the exmaple of the program in figure 12.1. It appears quite valid butwhen we run it, figure 12.2 it doesn’t owrk as expected. Visual Basic doesn’tmoan so it can’t be a syntax error, most likely a logic error or incorrectlyusing VB.

Recreate the program shown and confirm to yourself that it does indeednot work as anticipated. Note that the text boxes containing A and B arenamed txtA and txtB respectively. The label the result goes in is namedlblResult.

Go to the code editor window and click on the grey bar on the left ofthe window level with the line lblResult = txtA + txtB. It should nowlook like figure 12.3. We have set a breakpoint here because:

55

Page 56: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

56 CHAPTER 12. BREAKPOINTS

Figure 12.1: A simple but wrong program

Figure 12.2: What goes wrong

Page 57: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

57

Figure 12.3: Setting a breakpoint

• It is the only line of code we wrote so is probably where the error is.

• It refers to the variables to do with the wrong answer.

• It is as good a place as any (!)

Also VB is possibly getting confused as we haven’t told it to use the Textproperty of the text box. Perhaps it is uding the wrong property!

Run the program. Enter some numbers and click the button. The pro-gram now stops and VB puts a little yellow arrow next to the line we set abreakpoint on.

VB is telling you that it is ready to execute this line but hasn’t yet.While we are stopped at this position, we can check to see what VB thinks isgoing on using the Immediate or Debug window at the bottom of the screen.Type the following into it:

Print txtA

and press Return. VB responds with the number you types in box A.OK well VB seems to have been clever wnough to work out we were talkingabout the Text property. Confirm this by typing:

Print txtB

And confiming this is as expected. OK, so it is getting the numbers OK.How about the adding bit? Try:

Print txtA + txtB

Page 58: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

58 CHAPTER 12. BREAKPOINTS

Figure 12.4: Running

Ah! This is the problem. It is treating the numbers as text. Make surethat it is using the correct property again by typing:

Print txtA.Text + txtB.Text

Right so the solution may be to try telling VB that the numers are infact numbers. Lets try that using the CLng command we have come accross:

Print CLng(txtA.Text) + CLng(txtB.Text)

Thats it! So we now know what we should have as our code. Let theprogram continue by pressing the ‘play’ button on the toolbar and exit toget back to the code-editor. Change the line to be:

lblResult.Caption = CLng(txtA.Text) + CLng(txtB.Text)

Figures 12.4 and 12.5 give examples of this.Clear the break point by clicking on the red-dot.

12.1 Exercises

1. Add the following line under the code you typed above:

Debug.Print "Result caption = " & lblResult.Caption

Run the program, enter some numbers and click ‘Calculate’. Look atthe Immediate window. What is there? Is it what you expected?

Page 59: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

12.1. EXERCISES 59

Figure 12.5: Diagnosing

2. Go back to one of the variable-using programs you created previously(e.g. the one that multiplied two numbers together). Set a breakpointjust before the result is written and check using the Print commandthat all the variables have the values you think they should.

Unset the breakpoint.

3. Again run the program, enter some numbers and calculate. PressCtrl+Break. VB now has let you specify a breakpoint while it isrunning. Again check the variables.

4. Look up breakpoints in the help and find out how to do a single-stepcontinuation (this only executes the next line after the brakpoint). Seta breakpoint at the beginning of a long sub-procedure in a previouspiece of code you have written, and single-step through examining thecontents of any variables as you go.

Page 60: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

60 CHAPTER 12. BREAKPOINTS

Page 61: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 13

For ... Next Loops

13.1 Factorials

In much the same way as x2 or ‘x-squared’ means multiply the number xby itself, x!, or ‘x-factorial’ means multiply the number x by all the integerssmaller than it until you reach 1. For example

4! = 1× 2× 3× 4 = 24 (13.1)

Note that it can be proved straight-forwardly1 that 0! = 1.How would you implement such a thing in VB? You would really like

some way of doing the same thing over and over again. Possibly changingthe value of a variable as you did it. Luckily there are such things, they arecalled loops because VB reads through it then goes back a bit then does itagain and so on. If you join up the points VB visits in your program you geta ‘loop’ of execution.

13.2 For .. Next loops

Consider the following VB code:

For x = 1 To 10

Debug.Print x

Next x

If this were to occurr in a VB program it would result in the followingoutput to the Immediate window (remember debugging).

1Ask me if you want

61

Page 62: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

62 CHAPTER 13. FOR ... NEXT LOOPS

1

2

3

4

5

6

7

8

9

10

Clearly VB has excecuted the instructions between the For and Next tentimes, increasing x by one each time. Now think about the following code:

factorial = 1

For x = 1 To 4

factorial = factorial * x

Next x

Debug.Print factorial

This time VB prints out

24

The bit of VB code we have written calculates the factorial of 4 (or 4!).Such loops now complete our mathematics toolbox. We can now computejust about anything, from balancing you books to the maths to simulate agame to calculating2

∫ π2

0η dν =

d

dψ[θ · φ] +

√42Q (13.2)

We will use our factorial generator in a real program. We will also bedoing other things with the program so there are some strange controls onthe form not related to factorials.

I will lay out the instructions for coding the program much like a prac-tical examination. Figure 13.1 shows the completed Form but Don’t drawanything until asked to.

1. Create a new project in VB and give the default form the Caption ofFactorial Test.

2Ask me if you really want to know what this is

Page 63: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

13.2. FOR .. NEXT LOOPS 63

Figure 13.1: The Factorial program window at design time.

2. Create one TextBox and name it txtNum. Set the following properties:

• Height = 270

• Width = 975

• Text = blank, i.e. nothing in it!

3. Create two Labels and set one to have the following properties:

• Height = 255

• Width = 2655

• Caption = Enter Number to find Factorial of:

• Alignment = 1 - right Justified

and the other to have:

• Height = 255

• Width = 4335

• Caption = The result will go here.

• Alignment = 2 - Center

4. Create one Command Button named cmdGo and give it the followingproperties:

• Height = 375

• Width = 1215

• Caption = Go

5. Position them as in Figure 13.1.

Page 64: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

64 CHAPTER 13. FOR ... NEXT LOOPS

6. Create a Form1 Load event sub-procedure and put code in it to set thefollowing properties:

Control | Property | Value

-----------+------------+--------

lblResult | Visible | False

7. Create a cmdGo Click event sub-procedure and add the following code

Dim x As Long

Dim factorial As Long

Dim count As Long

’Gets the number from the textbox and

’stores it in the variable ’x’.

x = Val(txtNum.Text)

If x < 0 Then

’If user has entered a number less than

’zero then tell them not to and clear text box.

MsgBox "Please enter a value greater than 0"

txtNum.Text = ""

Exit Sub

End If

If x = 0 Then

’If x is 0 then special case

factorial = 1

Else

’Compute factorial

factorial = 1

For count = 1 To x

factorial = factorial * count

’Show the programmer some useful stuff!

Debug.Print " count = " & count

Debug.Print "factorial = " & factorial

Next count

End If

’Show result

lblResult.Caption = "Factorial of " & x & " is " & factorial

Page 65: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

13.3. FRAMES 65

’And make sure it is visible

lblResult.Visible = True

8. Save and run the program, verify it works as expected and demonstrateit to your tutor.

13.3 Frames

We are going to add some Option Buttons to our Form but a brief note aboutthem. VB assumes that all Option Buttons in a Frame belong to the samegroup. I.e. only one can be on at any one time. Perform the following

1. Create one Frame on the form and set its Caption to Food. Positionit as in Figure 13.1.

2. Click on the Frame and draw three Option Buttons in the Frame.Name them optSaus, optSand and optTom, and give them the captionsSausages, Sandwiches and Tomatoes respecitvely. Position them as inFigure 13.1. [Note: You cannot drag them outside the frame].

3. Create one Label in the Frame and give it the following properties

• Height = 255

• Width = 1575

• Caption = How Many:

• Alignment = 1 - Right Justified

4. Create one TextBox in the Frame and name it txtFoodNum. Give itthe following properties:

• Height = 270

• Width = 1095

• Text = blank, i.e. nothing in it!

5. Position the Label and TextBox as in Figure 13.1.

6. Add the following code to the end of the cmdGo Click event sub-procedure.

Page 66: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

66 CHAPTER 13. FOR ... NEXT LOOPS

’Food handling code

’Get amount of food

foodnum = Val(txtFoodNum.Text)

’Set ’foodname’ to the name of the food

’selected by the user.

If optSaus.Value = True Then

foodname = "Sausages"

End If

If optSand.Value = True Then

foodname = "Sandwiches"

End If

If optTom.Value = True Then

foodname = "Tomatoes"

End If

’Now print it out

For count = 1 To foodnum

Debug.Print "Amount of " & foodname & " = " & count

Next count

7. Add the following lines immediately after the line in cmdGo Clickthat reads Dim count As Long:

Dim foodnum As Long

Dim foodname As String

8. Add the following code to the end of the Form1 Load event sub-procedure.

optTom.Value = True

9. Save and run the program and verify it performs as expected and de-mostrate to your tutor.

Notice how we used comments to annotate the code. Always annotateyour code with comments, practical exams are marked down if youhave not. The functioning of the code will be discussed in class but noticehow we used If ... Then statements to verify data the user entered.

Page 67: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

13.4. EXERCISES 67

13.4 Exercises

1. Add similar code as was used to check the validity of the factorial inputnumber to the program so that it checks that the user has not requesteda negative amount of food. What happens if the user enters 0 or justleaves the box blank?

2. (a) Add a timer named tmrBlank to the form. Set the Interval propertyto 0 (disabled).

(b) Create the tmrBlank Timer event sub-procedure and add the fol-lowing code:

lblResult.Visible = True

tmrBlank.Interval = 0

(c) Add the following line to the end of the cmdGo Click event sub-procedure:

tmrBlank.Interval = 1000

(d) Run the program. What has the code we added done? How hasit done it?

3. Add a Flashing shape to the Form.

Page 68: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

68 CHAPTER 13. FOR ... NEXT LOOPS

Page 69: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 14

Decisions, Decisions (again!)

14.1 Select Case ... End Select

If ... Then statements are great for making decisions. Indeed, many BASICshave it as their only decision making mechanism. VB however has a slightlymore sophisticated mechanism. Consider a program like the one shown infigure 14.1. It shows a simple program where a user types a number into thetext box (e.g. ‘4’) and a textual version of the number appears in the windowbelow it, in this case ‘Four’. How would this program be implemented? Wecould have something like this:

’Get the number from the text box txtNumber and write it

’to the label lblResult

If lblNumber.Text = "0" Then lblResult.Caption = "Zero"

If lblNumber.Text = "1" Then lblResult.Caption = "One"

If lblNumber.Text = "2" Then lblResult.Caption = "Two"

If lblNumber.Text = "3" Then lblResult.Caption = "Three"

If lblNumber.Text = "4" Then lblResult.Caption = "Four"

If lblNumber.Text = "5" Then lblResult.Caption = "Five"

If lblNumber.Text = "6" Then lblResult.Caption = "Six"

.

.

.

but this is very tedious. Instead it would be nice if VB allowed us to testa single variable multiple times and do different things depending on whatits value was. Well, conveniently, it does. It is called the Select Case ... End

69

Page 70: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

70 CHAPTER 14. DECISIONS, DECISIONS (AGAIN!)

Figure 14.1: The Select Case example program

Case construct1. Using one of these, the above code could be written, withless typing as:

Select Case txtNumber.Text

Case "0"

lblResult.Caption = "Zero"

Case "1"

lblResult.Caption = "One"

Case "2"

lblResult.Caption = "Two"

Case "3"

lblResult.Caption = "Three"

Case "4"

lblResult.Caption = "Four"

.

.

.

End Select

1This is like a statement as it is a ‘lump’ of VB code but is different in that they oftenspan several lines

Page 71: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

14.1. SELECT CASE ... END SELECT 71

The dots (ellipsis) showing that one has to fill in the remaining (infinite!)number of lines. The block consists of a number of lines separated by Case

lines. Clearly, the lines after Case "1" and before Case "2" are executuedif, and only if, the value of txtNumber.Text is "2". One can imagine it aseive with each Case line being a hole shaped like a particular value. If thevalue is 2, it falls thought the Case "2" ‘hole’ and executes the lines underit and moves to the bottom. If it gets all the way through without fallingthrough a hole, it comes out the bottom.

What if the user types a number greater than 4, or even something whichisn’t even a number? We would like a final Case statement which catchesall the values which have fallen though the seive so far. This is the, almost,sensibly named Case Else statement:

Select Case txtNumber.Text

Case "0"

lblResult.Caption = "Zero"

Case "1"

lblResult.Caption = "One"

Case "2"

lblResult.Caption = "Two"

Case "3"

lblResult.Caption = "Three"

Case "4"

lblResult.Caption = "Four"

Case Else

lblResult.Caption = "Please type a NUMBER less than FOUR"

End Select

Let us try it. The final form will look like the one in figure 14.1.

1. Create a new project and name the default form frmNumber. Ensureits title includes your name, the current date and the text “Select CaseExample”.

2. Create two labels, one text box and one command button. Give onelabel a background colour of White and name it lblResult. Name thetext box txtNumber and the command button cmdDoIt. Position themas in the image provided.

3. Set the initial caption of the text box to be blank, that of the commandbutton to be “Do It”, the white label to be “text here will relate to thecontents of the text box” and the other label to be “Enter a number:”.Right-align this label.

Page 72: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

72 CHAPTER 14. DECISIONS, DECISIONS (AGAIN!)

Figure 14.2: The Select Case currency converter

4. Code a Form Load event sub-procedure for the form to set the Captionof lblResult to be blank.

5. Code a cmdDoIt Click event sub-procedure to set the contents of lblRe-sult to the textual-representation of the number typed in the text box[Hint: The code is above! ]. Ensure the code possesses a Case Else state-ment.

6. Run the program to check it works as expected.

14.2 Exercises

1. Create a new project and draw the controls in figure 14.2. The namesof the controls have been superimposed on the image.

(a) Code the Form Load sub-procedure of the form to set the captionof lblResult to be blank.

(b) Code the cmdDoIt Click sub-procedure to contain the followingcode:

Private Sub cmdDoIt_Click()

Dim pounds As Double

Page 73: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

14.2. EXERCISES 73

Dim foreign As Double

pounds = CSng(txtAmount.Text)

Select Case txtCurrency.Text

Case "F"

foreign = pounds * 10.5

End Select

lblResult.Caption = pounds & " Pounds = " & foreign _

& " " & txtCurrency.Text

End Sub

(c) Run the program and request 4 pounds in French Francs by en-tering in an amount of “4” in currency “F”. Can you see wherethe line comes from considering that there are 10.5 Francs in aPound. (Note that in the last line the “ ” character tells VB tocontinue to the next line when reading it, ask me for details).

(d) By noting that there are approximately 1.8 Deutschemarks (DM)in one Pound and 0.656 Euros (EURO) in one Pound add similarlines to handle the user typing the currencies “DM” and “EURO”.

(e) Use a Case Else statement to execute the following lines if the usertypes an unknown currency:

MsgBox ("Currency can be F, DM or EURO")

Exit Sub

(f) Add one real (or imaginary if you wish) currency to the program.

2. Why is it on the whole a bad idea to put a Case Else statement at thetop of a Select Case block? [Hint: Remember it is like a seive].

Page 74: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

74 CHAPTER 14. DECISIONS, DECISIONS (AGAIN!)

Page 75: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

Chapter 15

Misc stuff

15.1 Alignment Grid

There is not much to say about the alignment grid except that one can useit to create controls which are of a similar size. For example, try to createthe form in figure 15.1. Note the buttons are both 9 units wide and 3 unitstall. It is usual to make buttons 3 units tall as it corresponds to the size setby the Microsoft design guide.

Notice you can also accurately place the buttons a constant distance fromone another (1 unit). Little things like this help to give your application afeeling of consistancy.

15.2 Lines

A Line control is exactly what is says! It simply draw a line on a Form be-tween two points you specify. It has four properties which define its position:X1, X2, Y1 and Y2. The way these define its position are shown in figure15.2.

Lets try using this now to make a fun little dial program. Don’t worryabout the details of the program, it uses a little maths to work out theco-ordinates of points on a circle.

Create a blank form and create a Timer called Timer1 on it and a Linecalled Line1. Add the following code to the Form

Dim angle As Double

Private Sub Form_Load()

angle = 0

75

Page 76: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

76 CHAPTER 15. MISC STUFF

Figure 15.1: Using the alignment grid

���

���

���

���

Figure 15.2: The properties which define a line

Page 77: Visual Basic – Level I - Welcome to the SRCF - …rjw57/vb/notes.pdf · Visual Basic – Level I Richard Wareham 2001 – 2002 edition Content °c 1999–2001 Richard Wareham. 2

15.3. SCROLL BARS 77

End Sub

Private Sub Timer1_Timer()

angle = angle + 0.1

Line1.X2 = Line1.X1 + 1000# * Sin(angle)

Line1.Y2 = Line1.Y1 + 1000# * Cos(angle)

End Sub

Set the Timer’s Interval property to 100. Make sure the line is roughlycentral on the Form and run the program.

15.3 Scroll Bars

Create a new project. Add a horizontal scrollbar called HScroll1 to the form.Add a label called Label1. Double-click on the HScroll1 control to enter somecode into the HScroll1 Change event sub-procedure:

Private Sub HScroll1_Change()

Label1.Caption = HScroll1.Value

End Sub

Try putting the same code into a HScroll1 Scroll event sub-procedure.Notice the difference; Scroll procedures are called as the scrollbar moves andChange procedures are called when the scrollbar has changed and the user letgo of the mouse.

15.4 Images

These controls you don’t need to know anything about... no really! Theirintended use is to load a picture from disk and display it but you will onlybe asked to use it as a sort of ‘event box’. For example, you might be askedto create an Image amd attach a MouseMove event procedure to it.

Just to test what it is like, create a new project and form with an Image(check back for the corrent toolbar button, make sure you don’t confuse itwith a Picture). Add a Label. Code a MouseDown event procedure for theImage and get it to change the label’s contents.

15.5 Exercises

Ask me questions on the course!