Visual Basic 2005 Guide
Procedures & Functions

What is A Procedure?

You will need to be able to use 3 types of procedure in Visual Basic,

  • Event Procedures
  • Sub Procedures
  • Function Procedures

So far, you have only used the first type, event procedures. The example below is from the Variables section of this guide.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   intFirstNumber = InputBox("Enter your first number")
   intSecondNumber = InputBox("Enter your second number")
   intTotal = intFirstNumber + intSecondNumber
   MsgBox("The total is " & intTotal)
End Sub

The code above is executed when the form loads. You have also written procedures that execute when a button or a listbox is clicked or double clicked.

No Need To Repeat Yourself

There are many reasons to write your code in procedures. One of the main reasons is to avoid having to write the same code over and over again in the same program.

Example Program

1. Create a new project in Visual Basic.
2. Add 3 horizontal scrollbars to the form.
3. Name them hsbRed, hsbGreen, hsbBlue and set the min property to 0 and the max property to 255.
4. Add labels to the form to label the scrollbars, red, green and blue.

Your form should now look like the example below.

form design

Colours can be made up of differing amounts of Red, Green and Blue form 0 to 255. Our program will set the background colour of the form to the mixture of red, green and blue indicated by the scrollbars.

5. Double click the first scroll bar and type the following code in the Scoll event handler.

Me.BackColor = Color.FromArgb(hsbRed.Value, hsbGreen.Value, hsbBlue.Value)

6. Do exactly the same for the other 2 scrollbars. Save your work and test the program.

You should now have 3 procedures with the same line of code used each time.

7. Now we are going to write this code in its own procedure. Type the following in the code window,

Private Sub changeFormColour()
   Me.BackColor = Color.FromArgb(hsbRed.Value, hsbGreen.Value, hsbBlue.Value)
End Sub

Replace the lines of code in the 3 original event handlers with the following,

changeFormColour()

This line of code calls the procedure and tells Visual Basic to execute the code contained within the procedure. In this program, having the procedure doesn't make a huge saving in time. It does mean, however, that if we have made a mistake, there is only one part of the code that needs to be corrected.

Passing Information To A Procedure

We can send data to a procedure when it is called in our code. The data that we pass to a procedure is called a parameter.

Create a new project and add 3 text boxes to the form. These should be called txtFirstNumber, txtSecondNumber and txtAnswer. Add a command button called cmdAdd. We are going to create a whizz-bang procedure for adding together two numbers.

1. Click on View Code on the menu and type in the following procedure.

Private Sub addNumbers(ByVal intNum1 As Integer, ByVal intNum2 As Integer)
   Dim intAnswer As Integer
   intAnswer = intNum1 + intNum2
   txtAnswer.text = intAnswer
End Sub

Look carefully at the first line. Our procedure has 2 parameters, intNum1 and intNum2. Both are integers. These names are used within the procedure to refer to the numbers that we are going to pass to it.

2. Now, time to write the code that calls the procedure. Double click on the command button and enter the following lines.

Dim intFirst As Integer, intSecond As Integer
intFirst = txtFirstNumber.Text
intSecond = txtSecondNumber.Text
AddNumbers (intFirst, intSecond)

Simple Tasks

1. Add another button to the form. Write a new procedure that will MessageBox the value of the smallest number.

2. Do the same to get the largest number.

3. Write one more procedure that will multiply the two numbers together.

Function Procedures

Functions are procedures which return a value.

We will redesign the program for adding two numbers so that it uses a function instead of a Sub procedure.

1. Create a new project and add 3 text boxes to the form. These should be called txtFirstNumber, txtSecondNumber and txtAnswer. Add a command button called cmdAdd. We are going to create a whizz-bang function procedure for adding together two numbers.

2. Click on View Code on the menu and type in the following Function procedure.

Private Function addNumbers(ByVal intNum1 As Integer, ByVal intnum2 As Integer) As Integer
   Dim intAnswer As Integer
   addNumbers = intNum1 + intNum2
End Function

Look carefully at the first line of the code. We have to say what type of value is being returned by the function. In this case, it's an integer.

3. The code for the button event procedure is now as follows.

Dim intFirst As Integer, intSecond As Integer
intFirst = txtFirstNumber.Text
intSecond = txtSecondNumber.Text
txtAnswer.Text = addNumbers(intFirst, intSecond)

Check that your program works.

4. Time to crank things up a little by adding some new functions. Try this one for starters.

Private Function isSmaller(ByVal intNum1 As Integer, ByVal intNum2 As Integer) As Boolean
If intNum1 lt; intNum2 Then
isSmaller = True
Else
isSmaller = False
End If
End Function

5. Add another button. This one is to tell you which of the two numbers is the larger. The code you will need in this button's event procedure is as follows.

Dim intFirst As Integer, intSecond As Integer
intFirst = txtFirstNumber.Text
intSecond = txtSecondNumber.Text
If isSmaller(intFirst, intSecond) Then
   Msgbox ("First Number Is Smaller")
Else
   MsgBox ("Second Number Is Smaller")
End If

An Example Using Strings

Create a new project. Add a textbox to the form and name it txtWord. Add a button named btnWordLength.

1. Here is a function to tell you how long a string is.

Private Function howLong(ByVal strToCheck As String) As Integer
   howLong = Len(strToCheck)
End Function

In the button event handler, type the following,

MsgBox(howLong(txtWord.Text))

Check that this code works. It should MessageBox the number of letters in the word(s).

The following function will tell you the first letter in the word that has been entered.

Private Function firstLetter(ByVal strToCheck As String) As String
   firstLetter = Microsoft.VisualBasic.Left(strToCheck, 1)
End Function

3. Add another button that will MessageBox the first letter of the word entered.

You can get the last letter of the string by using Microsoft.VisualBasic.Right(strToCheck, 1). Do this as well.

4. The built-in functions UCase(strToCheck) and LCase(strToCheck) convert strings to upper or lower case. Create functions that will do this in your program.

5. With a bit of work you can make your program capitalise the first letter of a string for you. You will need to find out how to use the Microsoft.VisualBasic.Mid() function using the help file.

Extension Task

  1. Enhance the scrollbar colouring program from above so that when a new colour is selected, the red, green and blue values are displayed for the user. You could even convert the result into a hexadecimal string of the kind used to describe colours in HTML.