Procedures
End of tasks


Back to Main Page
Why use procedures?

- to avoid repeating (and retyping) identical code that appears in several places in a program
- to simplify code and make it more readable
- to help debugging by splitting code into defined sectons
- to re-use code easily in a different program, rather than re-writing

Imagine we have a program similar to the shop till used in an earlier example. Each time a price is entered, the VAT on it is calculated and added on.
What if we had to do this for each item in a shopping list of 100 items?
What if the VAT rate changes? We will have to rewrite every calculation!

Instead, we can write a simple sub procedure that sits inside the main program and automatically calculates Vat and adds it on. If the VAT rate changes we make only ONE change - to the VAT rate in the sub procedure.

The algorithm works as follows:

- take the original price
- multiply it by 0.175 (to calculate VAT at 17.5%)
- add the VAT to the original price.

In this task, we will write this sub procedure, imagining that we have 3 items on our shopping list.
Task 1

Read through and then enter the following code:
Notice the line:

Form1.Print "The total with VAT is � " & Format (Total, "0.00")

Formatting using the
Format function allows us to set the number of decimal places that is displayed - for currency we need 2 d.p.

Use the format function as follows:

Format(Name of variable to be formatted, how to format it)

In the code above we format the variable
Total to 2 d.p. by writing "0.00"
If we wanted just 1 decimal place in our display we would write

Format(Total, "0.0")

Always make sure that you format your variables into the correct format before the user sees them - particularly in your assignments!

An age of 17.614 years is meaningless
A price of �128.6 will confuse a user - it must read �128.60

Format is one of VB's
built-in functions.


Now we're going to create a procedure which calculates the VAT. This is the procedure that we call in the line

Call addVAT (Price1)
Task 2

Select from the
Tools menu Add Procedure
Name the procedure addVAT
Make sure that
Procedure and Public are selected
Click OK

VB inserts an empty procedure for you. Type in the following code:
When you call the procedure AddVAT, you pass it the variable Price as a parameter.
You also specify that it is passed as a Single.

You pass
ByRef because you want to change the variable Price in your main program.
If you passed
ByVal, VB could do some maths on Price but the variable would not change in the main program.

The procedure
adds VAT and returns the new value of Price to the main program.

Using this procedure only saved us a little time, but imagine how much time you would save if the procedure contained 50 lines of code!
Hosted by www.Geocities.ws

1