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

by Lorenzo Dalla Vecchia


After the previous recapitulations, you should be familiar with the use of controls, properties, methods and events. Now I'll go back explaining code, which is the most important part of a program.

One of the fundamentals of programming is storing of information for use. For this purpose, VB uses variables. It is difficult to talk about a variable such as a physical thing: you can imagine it as a part of he computer memory, with a given name, in which you can store data.

Each variable, to be used, must first be declared. To declare a variable, you generally use the Dim command.

    Dim variablename As variabletype

For variablename, you type any name you like, easy to remember. variabletype defines the type of data the variable will contain. The following are some of them:

String Plain text.
Integer Numbers in the range -32,768 to 32,767.
Long For big numbers, ranging from -2,147,483,648 to -2,147,483,647.
Single High precision. Up to 5 decimals.
Double Very high precision. Up to 14 decimals!
Boolean Used as a "switch". Can be either True or False.

There are many other type of data, such as Currency, Decimal, Object, Variant, Date: don't worry you don't need to learn them until you need it.

Now, some examples:

    Dim EmployeeName As String    'a string to hold text
    Dim ItemPrice As Integer      'up to $30,000, wow!
    Dim LightsOn As Boolean       'True or False, light or dark

If you type the above code (declarations) in a event procedure, the three variables will be accessible only within that area (the code associated to the event). Very often you will need to have variables that can be used by every control throughout the form. So, is there a "neutral" area to declare variables into? Yes, it is the General Declarations section of the form. To access it, when in Code View mode, select (general) from the dropdown list on the top-left: the other box should read (declarations).

This area is not related to any control: all the code typed here will affect the whole form. The variables created here will have a form-level scope. The scope is just the validity area of a variable: variables created inside event code have a procedure-level scope.

To assign (store) a value to a variable, type the following:

    variablename = newvalue


    EmployeeName = "Robert"
    ItemPrice = 300
    LightsOn = True

If you try to force a variable to contain data of the wrong type (for example you assign text to an Integer var.) you will get the very common Type Mismatch error.
As mentioned before, text must be enclosed into quotation marks. Additionally, numbers must be typed as plain rows of digits, without commas or quotes: you can only type the dot, when needed.. For Boolean variables, you simply type the keyword True or False.

Now, to get the concept, let's make an application that makes use of variables.
Create a new form with a command button and a label. How to show a message box each time the button is clicked, containing the number of times it was clicked? You will need a variable to hold the number of clicks, and it must be valid throughout the whole form, because it mustn't be re-declared (and set to 0) each time the button is clicked. So, go to the General Declarations section of the form and type this:

Dim NumClicks As Integer

Now, here's the code for the Click event of the button:

    'Increase NumClicks by 1
NumClicks = NumClicks + 1

    'Show the message box
    'note the use of the & (ampersand) to concatenate text

MsgBox "This button has been clicked " & NumClicks & " times."

I think you understand the great importance of variables in programming. The next step is facing some basic code structures.

When code takes decisions

I'll now explain you some very important code structures, that are the fundamentals of programming.

One of those structures is the command that lets VB "take decisions": in other words you can set up a condition and act differently whether it is true or false. It is the If structure.
Its syntax is the following:

    If condition Then
    End If

Or, if you want to specify an alternative operation:

    If condition Then
    End If

There are also shorter forms of the If construct, that can be typed on a single line:

    If condition Then ...

    If condition Then ... Else ...

Remember that, this way, you can put only one line of code after Then and Else.

You first write the condition: it can be Var = 2 or N > 10 and so on. For example, the following tests the variable Num to see if it is greater than 5:

    If Num > 5 Then
        MsgBox "Number is greater than 5"
        MsgBox "Number is lesser or equal to 5"
    End If

In the above example, if the variable Num contains a number greater than 5, the code after Then is executed, otherwise, the code after Else (if present) is executed.
In the above code, I made use of indentation. It consists in putting a Tab at the beginning of each line inside a block (such as If..Then..Else) to make it more readable.

When writing conditions, you can make use of many compare operators: heare they are.

= Equal to
> Greater than
>= Greater or equal to
< Lesser than
<= Lesser or equal to
You can use compare operators to compare a variable with a consant value or to compare to variables.

And if you wanted to join two or more conditions into a single one, such as "that string begins with A and ends with Z" or "that number is greater than 27 or lesser than 12"? You should have used logical operators.


Both conditions must be true. Example:

    If (Num > 27) And (Num < 12) Then

(note that the two conditions are enclosed in parenthesis).

Or At least one of the conditions must be true:

    If (Age = 18) Or (Gender = "F") Then

The above will be true either Age is 18, or Gender is "F", or both of them.

XOr (exclusive or) Only one of the conditions can be true:

    If (Flavour = "Salty") XOr (Flavour = "Sweet") Then

Flavour can be either "Salty" or "Sweet", but not both.

Not The condition must be false:

    If Not (Age > 65) Then

The above will be true for all values of Age minor than 65.

Let's make use of the If clause and of variables to create a quiz program.
Put 3 labels on a blank form and fill their caption property with quiz questions. Create a frame control for each label and put multiple answers choices into each frame in the form of option buttons.

Remember that you need to group option buttons into frames (or picture boxes).

Now we want to write code for the Score command button. The code should:

  1. Check that all questions are answered.
  2. Count correct answers.
  3. Give a feedback (score).

To accomplish the first task, VB should check that the Value property of at least one of the option buttons in each group is True. So, the If clause will contain the Or operator (or, better, XOr).

    'Create a variable to count given answers   
    Dim Answers As Integer

    'Check the first question   
    If (opDiaz.Value = True) XOr (optColombo.Value = True) _
(optMagellano.Value = True) Then
Answers = Answers + 1
    End If
    'Check the second question   
    If (optAmsterdam.Value = True) XOr (optCopenaghen.Value = True) _
(optBruxelles.Value = True) Then
Answers = Answers + 1
    End If
    'Check the third question   
    If (op0.Value = True) XOr (opt4.Value = True) _
(opt17.Value = True) Then
Answers = Answers + 1
    End If

    'If less than 3 answers, notice the user
    If Answers < 3 Then
    MsgBox "Answer all the questions!"
Exit Sub
    End If

Two new things in the code above: the underscore ( _) at the end of the lines is used to "split" a line into shorter physical lines of text; the Exit Sub command is used to terminate the code associated to the event before its normal end (at the End Sub line).

To count the correct answers, we will need another variable and other If clauses. Add the following code to the previous one.

    'Create a variable to count correct answers   
    Dim CorrectAnswers As Integer

    'Check the first question   
    If optColombo.Value = True Then
CorrectAnswers = CorrectAnswers + 1
    End If
    'Check the second question   
    If optBruxelles.Value = True Then
CorrectAnswers = CorrectAnswers + 1
    End If
    'Check the third question   
    If opt0.Value = True Then
CorrectAnswers = CorrectAnswers + 1
    End If

Last part, give feedback. More If clauses then, but we are going to type them in their shorter form, ...

    If CorrectAnswers = 0 Then MsgBox "0 out of 3: what a disaster!"
CorrectAnswers = 1 Then MsgBox "1 out of 3: you need more study!"
CorrectAnswers = 2 Then MsgBox "2 out of 3: you are almost there!"
CorrectAnswers = 3 Then MsgBox "3 out of 3: perfect!"

That's all. Run the program and look at it with satisfaction.
In the next lesson you will face the other important structure of programming: loops.

The power of loops

Another relevant feature of VB is the support of loops. A loop is a special code structure that can repeat a piece of code: its application are countless!

A brief example: how would you type code to calculate the sum of the first 10 numbers?
The following code is acceptable ...

    Dim Sum As Integer
    Sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

But you could also write the following:

    Dim Sum As Integer
    Sum = Sum + 1

    Sum = Sum + 2

    Sum = Sum + 9
    Sum = Sum + 10

If only was there a way to tell VB "take Sum and sequentially add a number from 1 to 10"... there is!
It is a For..Next loop. The For..Next loop is used to execute a piece of code a definite number of times (in this case, 10 times); it has the following syntax:

    For countvariable = min To max

Next countvariable

In our case ...

    For i = 1 To 10

Next i

The variable i (countvariable) is used by VB to "keep count" of the number of times the loop has been executed. Let's see how it works in detail.
The first line means "take the variable
i and let it assume all the possible values between 1 and 10": so i is set to 1. VB then executes all the code after For, until the Next command is encountered. The Next command means "give i the next value" (2): so i is set to 2 and VB returns to the For line and asks itself the following question "is i greater than 10?"; in this case it isn't, so the code inside the loop is executed again and again, until i reaches and overcomes 10.

Now, our example:

    Dim i As Integer    'the count variable
Dim Sum As Integer  'to hold the sum

For i = 1 To 10     'try all numbers from 1 to 10
        Sum = Sum + i  
'i assumes increasing values each time
Next i              'try the next value of i

    MsgBox "The result is: " & Sum

All clear? Just wanted to let you know that other types of loop exist, such as Do..Loop and While..Wend, but we will study them in detail another time.

Let's try another example that also involves If and listboxes: we want to make a program to record air temperature every day and then find the maximum, minimum and average values.
The form will contain a listbox (to store temperatures), a textbox and a button (to add a new value) and 3 command buttons to get the max, the min and the avg.
I named the controls: lstTemperatures, txtNewTemp, cmdAdd, cmdMax, cmdMin.

The first step is writing code from the cmdAdd button (to add a new temperature): as you probably remember, we must use the AddItem method of the listbox.

    lstTemperatures.AddItem txtNewTemp.Text

Now, let's see how to make the "maximum" button work: the code should go through all listbox items and find the maximum; remember that the total number of listbox elements is returned by the ListCount property. To return a specific element, you use the List property as follows:


Now, the code:

    Dim Max As Integer      'the max value found
Dim i As Integer        'count variable

    'set Max to a so low value to be sure that all others are higher
    Max = -50

For i = 0 To lstTemperatures.ListCount - 1    'index range from 0
        'check if current value is higher
        'than the maximum found

If lstTemperatures.List(i) > Max Then
            'if it is, make it the new Max
            Max = lstTemperatures.List(i)
End If
Next i

    MsgBox "Maximum temperature was: " & Max & " degrees."

The code for the "minimum" button is very similar:

    Dim Min As Integer      'the min value found
Dim i As Integer        'count variable

    'set Min to a so high value to be sure that all other are lower
    Min = 50

For i = 0 To lstTemperatures.ListCount - 1    'index range from 0
        'check if current value is lower
        'than the minimum found

If lstTemperatures.List(i) < Min Then
            'if it is, make it the new Min
            Min = lstTemperatures.List(i)
End If
Next i

    MsgBox "Minimum temperature was: " & Min & " degrees."

To calculate the average, we should sum all the temperatures and divide by the total number of values; the latter is returned by the ListCount property of the listbox.

    Dim Sum As Integer     
    Dim Avg As Single       'Single because can contain decimals      
    Dim i As Integer        'count variable

For i = 0 To lstTemperatures.ListCount - 1    'index range from 0
        'update the sum
        Sum = Sum + lstTemperatures.List(i)
Next i

'calculate average
    Avg = Sum / lstTemperatures.ListCount

    MsgBox "Average temperature was: " & Avg & " degrees."

Now you should have a clear idea of the concept behind loops,  If clauses and variables; be sure you got it, because we are going to see the last important things about code: subs and functions.

Lesson 2

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

Lesson 4

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