VB Tutorial
VB Tutorial
This tutorial contains a beginner’s guide to Visual Basic 6.0, introducing the
programming
environment, defining key terms and introducing exercises to demonstrate the five
control structures (sequence, selection: binary and multiway, iteration: pre and post
test).
Syllabus outcome
H5.3 A student selects and applies appropriate software to facilitate the design and
Naming conventions
Sequence
Binary Selection
Multiway selection
Activity 6: Multiway selection
Iterations
The first step is to create a project template within VB, to organise and store your
work.
This will consist of a menu structure with headings that will let you access the many
Activity 1
• Use the file menu to open a new project with a blank form.
– BackColor to White.
– WindowState to Maximised.
• Find the Menu icon and click on it to select it. Enter the following menu headings:
Quit
Introduction with indented subheadings of
Example1
Example2
• Click on Quit menu heading and enter the following code. This procedure is used
to
exit from running the project display and return to the design screens.
Unload me
End
End Sub
• Use the <F5> function key to run the application to verify that the Menu
structure is
• Use the File menu to save your work as Main.frm and (your intitials)Project1.vbp
• Use the file menu to open a new blank form (or the properties window)
caption to Example1
BackColor to White
WindowState to Maximised
• Click on the Example 1 main menu heading and enter the following code:
Private Sub Example1_Click()
Welcome.Show
End Sub
• Save your work and run <F5> to ensure that it is free of errors.
• Add two labels, an image and a command button to create a welcome screen. To
do
this
Select label icon from the toolbox. Click towards the centre-top of your form and
Set the font (Arial, underline, alignment centred, size 24 point, forecolour blue)
Use the image icon on your toolbox to add the image to your form. Use the
Use the command Button icon to add the button. Change its caption to RETURN.
Then double-click the button and add the following line of code after the
Command1_Click() procedure.
– Unload Welcome
• Use the file menu to save your work and use <F5> to run the application.
• DON’T FORGET TO SAVE (AND BACK UP TO FLOPPY) ALL YOUR WORK.
• An object is a thing — anything that appears on the screen. An object has a set
of
Label is an object
• Events are things that happen on the screen. Event handlers transfer data to
procedures that complete the task. The results of these procedures are returned
End Sub
As each new example and exercise solution is to be added to your project you will
need
to:
• click on the main menu icon with the main form displayed to show the menu
designer
FormXX.Show
Activity 2
1. Open a new form and change its name to ColourChanger. Place the following
objects
on this form.
3 horizontal scroll bars (Set the max value property of all three to 255)
another small label5 under the button with its visible property set to false.
2. Double click each scroll bar and add the following code to its _onChange() event.
Use
HScroll3.Value)
HScroll3.Value)
Label5.Visible = True
Label5.Caption = “WOW!”
Label2.BackColor = RGB(HScroll1.Value, 0, 0)
3. Double click the return button and add the following code to its _onClick() event
Unload Me
4. Use the Project Explorer window to return to your main form and double click
5. Use <F5> function key to test your project. Save and backup.
Naming conventions
Up till now, we have often accepted default names, Text1, Label1, etc. In a big
project,
this is not good practice as it makes the code harder to read or maintain. Naming
conventions use a prefix of three lowerCase letters to identify the type of control,
Data types in VB
A variable is a named location that holds data. A variable can only hold one
datatype.
A program can have as many variables as you need but before you can use a
variable it
must be declared.
You use a DIM statement to declare variables (where DIM stands for dimension).
Here is
Boolean One of two values only. e.g. True or False e.g. blnIsOverTime bln
bytAge
byt
-$922,337,203,685,477.5808 to +-
cur
Date Date and time values from Jan 1, 100 to Dec 31, 9999 e.g.
dteFirstLesson
dte
e.g. dblMicroMeasurement
dbl
int
Long Integer values beyond the range of Integer datatype from lng
obj
Single Numeric values that range from –3,402823E+38 to
sngYearSalesFigures
sng
strFirstName
str
Variant Data of any datatype used for control and other values for
vnt or
var
A function is a segment of code that accepts zero, one or more arguments and
returns a
single result. Visual Basic includes many built-in functions (intrinsic functions).
Some
An argument is a value you pass to a function so the function has data to work with.
Function names have parentheses at the end to hold the function arguments. Even
if a
Message and input boxes are intrinsic functions in Visual Basic 6.0 which allow the
end
Follow the instructions Add new form to menu at the end of Activity 1 to create a
new
form with a menu heading on the main form. Call this “Message and Input Boxes”
• Put a label on the top of the form “Computer Conversation”. Underneath have a
command button with the caption “Talk to me!” Name the command button
cmdTalk.
• Double click the command button to add the following code sequence.
End Sub
• Add a return button, called cmdBack as you did in the ColourChanger, using the
code
Form1.Show
End Sub
• Run your program using <F5>. Don’t forget to save your work.
Here are some handy literals (values that don’t change). You don’t have to learn
them
as the help prompt supplies a drop down list as you start to type.
vbSystemModal 4096 Displays a System Modal dialog box. The user must
Remarks are added in code to explain the purpose of a section of code or to add
information for code maintenance. If Rem or ‘ is placed in front of the remark, that
line
Create a calculator that can add, subtract, multiply and divide two numbers given
by the
user.
[A possible solution might use two input boxes (txtOne and txtTwo) and a label to
display
Declare variables:
dblNo1 As Double
dblNo2 As Double
dblAnswer As Double
intError As Integer
Use Val function to change string from input box to a number, then an assignment
Use a Format function to ensure answer is rounded off to two decimal places.
If you are very clever, this might be an option for the user.
Ensure that it is not possible to divide by zero, either by entering nothing or by
entering
zero. Use the MsgBox() function to indicate the problem to the user.
Else …
End If
Add a clear command button with the following code to allow the user to do another
calculation.
txtOne.Text = “”
txtTwo.Text = “”
lblAnswer.Caption = “”
txtOne.SetFocus
The SetFocus method returns the cursor to the first input box.
Check that it works. Use integers, very big numbers, very small numbers, negative
numbers, zeros, etc. Is your label big enough for all values? If you set the label’s
Add a remark (put ‘ at the beginning of the line) at the top of your code which
includes
constructs. Each line of code followed another with only one possible pathway for
each
event. So, for each sub procedure, the algorithm would consist of input, output and
a
txtOne.Text = “”
txtTwo.Text = “”
lblAnswer.Caption = “”
txtOne.SetFocus
Binary selection
The next group of programs you will write uses the second algorithm construct —
selection. Selection allows multiple pathways for any event and allows for choices
to be
made. Selection constructs can be Binary (two way) or Multiway (multiple choices)
Binary selection uses the If – End If or the If – Else – End If statements. Here
End If
OR
Else
End If
(You have used binary selection in your calculator to prevent a user dividing by
zero.)
Activity 5
• Add a new menu heading Selections with two subheadings, Binary Selection and
Multiway Selection.
selected. Option buttons are mutually exclusive, i.e. only one can be selected at a
time.
• Use your calculator to verify the results. Try it out with some test data including
very large numbers, very small numbers, zero, negative numbers, 0.000000987654.
Multiway selection
than two alternatives, you can use nested If statements but this becomes
complicated
and leads to hard-to-read code. It is better to use Case statements. Here is the
syntax
Case value
Case value
Case value
[One or more VB statements]
Case Else
End Select
For example:
1 Convert it!
Case Is < 6
lblTitle.Caption = “Preschool”
Case 6 To 11
Case 12 To 18
lblTitle.Caption = “Secondary School”
Case Else
lblTitle.Caption = “Adult”
End Select
Activity 6
1. The post office has the following charges for parcels based upon different
weights.
0 – 50 $1.40
51 – 100 $2.70
Parcels which are heavier than 500 gms are calculated by weight*0.02
Design a project that allows a user to enter the weight in a text box and calculate
the
postage. Use Case statements in your code. Link this as CaseWeights under the
2. Use a set of check boxes to allow a user to choose the noise level by the
comments,
then output the probable decibel level based on information in the following table.
90 – 139 Deafening
60 – 89 Disturbing
30 – 59 Distracting
0 – 29 Relaxing
Again use Case statements and link this to the main form menu under the name
Activity 7
A control array is a set of multiple controls of the same type with the same name
(often
created by using the Copy and Paste command). You may have encountered this
already
in adding radio buttons or check boxes to your form. Individual controls within the
array
are distinguished by having different Index property values. So, if you created a
control
array of option buttons called optChoice, the Click event procedure might look like
this:
End Select
End Sub
The code above would change the label caption as each different option button was
selected. Try this out, then add code to change the label background colour (to
something appropriate) for each different day. Link to the menu Multiway Selection
heading in the main form menu under the heading Colour My Days.
Before we continue with the last structures — iterations — check that the menu
headings on Main are all correct and linked (by code) to the correct forms. Check
the list
Menu
Quit
Introduction (Sequences)
from Activity 1
from Activity 2
Selection
from Activity 4
from Activity 5
from Activity 6
from Activity 6
from Activity 7
Iteration
Iterations
carried out repeatedly while some condition remains true (or for a counted number
of
times). Each iteration MUST contain a way of stopping the looping. There are 2
• Pre-test iterations: in these loops, the condition to be met occurs at the beginning
of the loop and the code will not run at all if the condition
is never met.
• Post-test iterations: in these loops, the condition to be met is at the end of the
loop
Activity 8
Create a new form and link to iteration — pre-test (- Count the beeps) on the Main
menu.
Add a text box and a command button. Put a label above the text box asking the
user to
input a number between 1 and 10. When the user clicks the command button,
check the
textbox for a valid number and issue an error message if the number isn’t inside the
expected range. If the number is valid, use Do While …… Loop to issue that
intNumber = Val(Text1.Text)
‘Declare variables
‘Validate number
Beep
frmBeeper.Refresh
Next pause
Loop
Else
Text1.Text = ""
Text1.SetFocus
End If
End Sub
Activity 9
In this tutorial, we look at writing code containing the 5 basic control structures.
• sequence
• binary selection
• multiway selection
• pre-test iteration
• post-test iteration
The IPO chart and pseudocode algorithm for finding the average of some numbers
entered from the keyboard, using a post-test loop, might look like this:
I number, counter
add 1 to counter
average = sum/counter
O average
BEGIN Main Program
counter = 0
sum = 0
REPEAT
get number
counter = counter + 1
UNTIL counter = 10
display average
END MAINPROGRAM
Open a new form and create a link to the program from the menu form (Main) under
10 numbers entered by the user using a post-test loop with the syntax Do …..Loop
Until to ask for each number. Remember to use the Val () function to convert
strings
to numbers. Each number might be asked for with an input box using the syntax:
intNumber = Val(strNumber)
intCounter = 0
Can you be sure that the counter will never cause division by zero and crash your
Activity 10
new form to generate a random number between 1 and 6 to simulate the rolling of
a
dice. Your form will need a large picture box with the Autosize property set to true
and a
Dim x As Integer
x=0
Picture1 Print
Randomize
Do
x = Int(Rnd * 6 + 1)
Picture1 Print x;
End Sub
Run your program clicking the command button several times (until the picture box
is
full). Create a link to the program from the menu form (Main) under Iterations …
Post
test Loops … Roll the dice.
To produce a random integer x where 0 <= x < N, use the following syntax
x = Int(Rnd * N)
The following statement produces random integers in the range from 51 to 150.
The Randomize statement ensures that the start of each sequence of random
numbers is
also random.
You will notice that Visual Basic has two different syntax statements for post-test
iterations:
Both are post-test loops where the comparison test appears at the bottom of the
loop
meaning that the code in the loop must execute at least once. These are both
equivalent
Write the algorithm for this application in pseudocode that explains what every line
in the
program does.
Activity 11
Create a program to generate the first 20 Fibonacci numbers. This time use a
counter to
control the number of iterations. Add a Picture Box to print your results to. Make
sure
different from the ForeColor. Use the following code to help you.
‘Initialise
FibNumber = 0
FibNext = 1
‘trailing semicolon stops the Print method going to the next line.
Counter = Counter + 2
If Counter = 10 Then
Picture1 Print
End If
Loop
Write a program that uses nested For loops to fill a 2 dimensional array and then to
print
out the times tables from 1 – 12 into a picture control using the syntax:
with a new line for each new times table on the display.
You will definitely need to plot this one out on paper first, writing your algorithms
and
Bibliography
Further Resources
http://www.searchvb.com/
Free-Ed Net Course Catalog: http://www.free-ed.net/catalog.htm
Beverley Sampford