Learn Visual Basic
Difficulty:   Lessons: 1, 2, 3, 4, 5

by Lorenzo Dalla Vecchia

Introducing Subs

You have learnt that with a loop you can continuously repeat a piece of code, right? But what if you needed to use the same code in many different places of your program? Of course, you could have typed and re-typed it multiple times, but this is not a "smart" way of programming. The best thing is using subs.

A sub is a piece of code that can be "called" from any part of the program. For example, if you want to show a message box each time you click any button in your program you can write the following lines in the Click event of each button:

    MsgBox "This is a repetitive message."

Or, you can use a sub.
To create a new sub (or procedure), go to the General Declarations section of the form and type the following:

    Sub subname

So, in our case:

    Sub ShowMessage

Once you press enter to confirm the line, you will read this:

    Sub ShowMessage
       
    End Sub

"Hey, but that is similar to the event thing!" Yes, in fact VB automatically creates a sub associated with each control event: they are called event procedures and are just particular type of subs.

You probably already know what to do: type the code between the two lines ...

    Sub ShowMessage
        MsgBox "This is a repetitive message."
       
    End Sub

... and you've just created your first sub. Now, to tell VB to execute the sub each time you click a button, put the following in the Click event procedure of each button:

    Call ShowMessage

It means "execute the code in the ShowMessage sub". The general syntax of the Call command is:

    Call subname

Now you're probably asking yourself: what is the advantage? In this case you could have repeated the MsgBox code, because it is very simple, but imagine you had 30 lines of code ... Additionally, if you need to change something in the code, you must do it only once.

The conclusion is that VB programs are literally made up of subs, if we also consider event procedures.

Parameters come into play

You should now have a clear idea of what a sub is. But, what if I want a sub to add two numbers together and show the result in a message box? I must provide it with some information (in this case, the two numbers to sum up). More precisely, the two numbers are parameters of the sub.

To code that, you must add a couple of parenthesis after the sub name, containing a (comma delimited) list of the parameters, each with its name and data type. Syntax:

    Sub subname([param1 As datatype1, param2 As datatype2, ...])

The square brackets indicate that the parameters are optional.
The names you specify will be used to refer to the parameters inside the function: they are like variable declarations, so you don't need to use Dim to declare them again.
Let's see how our example would have been coded:

    Sub Addition(Num1 As Integer, Num2 As Integer)
       
'declare a variable to hold the result
       
Dim Result As Integer
       
'compute result
        Result = Num1 + Num2
        'show result
        MsgBox "The result is " & Result
   
End Sub

Num1 and Num2 are the names of the parameters; they are both of the Integer type and they are used into the procedure code to calculate the addition.

Parameters are a necessary prerequisite for what we are going to see now: an "evolved" type of sub, functions, but before that, let's talk a bit about arithmatical calculations.

Arithmetical operators

A little insert about mathematics. VB uses some standard operators to make calculations.
The general operator syntax is:

    variable = var1 oprt. var2

var1 and var2 are called the operands; oprt. can be replaced by any of the following:

+ addition (i.e. 2 + 3 = 5)
- subtraction (i.e. 7 - 3 = 4)
* multiplication (i.e. 3 * 7 = 21)
/ division (remember that the result may not be of the Integer type - i.e. 9 / 2 = 4.5)
\ integer division (always returns an integer result - i.e. 9 \ 2 = 4)
Mod remainder of an integer division (i.e. 9 Mod 2 = 1)
^ power (i.e. 2 ^ 3 = 8)

You can also use parenthesis ...

    (2 + 5) * 3 = 21

Time for functions now.

Functions

Although functions are very similar to subs, there is a big difference between the two things: in fact a function is a procedure that returns a value.
To create a new function, enter the following in the Declarations section:

    Function funcname([param1 As datatype1, ...]) As returntype

The new thing here is the As returntype: it is there because a function, besides accepting values (parameters), returns a value and returntype is the data type of the returned value.
Don't worry, an example will help you understand it.

Suppose I need to find whether a number is even or odd: I want to have a function called IsEven that returns True if the number is even, False if it is odd.
The following is the way I will use it:

    'There is a textbox on the form to enter
    'the number. This is the code for the
    'command button

    If IsEven(txtNumber.Text) = True Then
        MsgBox("The number you typed is even."
   
Else
        MsgBox("The number you typed is odd."
   
End If

As you see above, we don't use a Call command for functions, but we work with them as with variables/properties.
Now, what does our function need? Well, its name is
IsEven, it needs a single parameter (a number of the Integer type) and returns a Boolean value (True or False).
Just a word about the above If clause: the condition IsEven(txtNumber.Text) = True may also have been typed only as IsEven(txtNumber.Text), because in a logical condition, = True is always underlying.

These are the boundaries of the function:

    Function IsEven(Number As Integer) As Boolean

    End Function

What to type in the middle? An even number is a number that is divisible by 2, in other words, the remainder of its integer division by 2 is 0. Because the operator to find the remainder of a division is Mod, the following will be the code for the function:

    Function IsEven(Number As Integer) As Boolean
        If
Number Mod 2 = 0 Then
           
IsEven = True     'return value
        Else
           
IsEven = False    'return value
        End If

    End Function

The two lines I marked with comments are the most important, because they actually return the value: using the IsEven function as a variable, they "tell" it to take the value True or False.

Visual Basic contains a heap of pre-made functions: for example the Sqr function returns the square root of a number ...

    MsgBox Sqr(25)
    'show a box with the number 5 in it

... or the InputBox function, used to ask the user for information:

    Dim Name As String
    Name = InputBox("Type your name.")
    MsgBox "You typed " & Name

You will learn the names and meanings of VB built-in functions gradually, with practice.

Now that I have explained you all the "bad things" about code (variables, conditions, loops, subs, functions, operators) the big part is over; there are only some more things you need to know about forms, modules and managing your project.

Lesson 3

Your feedback/requests about tutorials?
Let me know! Click here.

Lesson 5

Click Here!


Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
To contact the Webmaster, click here.
Hosted by InWind: www.inwind.it