You are on page 1of 74

Visual Basic: Lab #1

Using some of the basic objects

 Open Visual Basic and then open a new Standard EXE

 Before you go any further, save your work: File...Save as

You will be asked to save both the form and the project. Make sure you save them on your
server. Give them the same name: ct3200lab1

 In your Properties Window, change the caption of the form to “Lab One”

 Go to the bottom of your Properties Window and change the WindowState Property
from “0-Normal” to “2-Maximized”. This will make sure that your project runs, it will take
up the full screen

 Click on the Command Button in your toolbox. If you click it once, you will get a set of
crosshairs that tell you that you can draw a button the size you want. If you double-click
the command button in your toolbox, a button will appear on your form.

 After you have created your button, you will need to change the caption. Click on the
button so that a set of squares appears around it. This will tell you that it is selected.
Then, go to your Properties Window, find the Caption property and change it to “Click
Me”

 Now go back to the toolbox and create 2 textboxes in the same way you created the
command button. You will notice that inside each textbox will say “Text1” or “Text2”.
You will have to delete these words by clicking on each textbox, then going to the
Properties Window and finding the “Text” property. Erase “Text1” from the box, then
click on the second textbox and do the same thing.

 Next, you will add a label to your form. Find it in the toolbox and add it to the form. Make
sure it is selected, then go to the Properties Window and change the following
properties:

o Find the Caption property and erase “Label1”


o Find the BorderStyle property. It will say “0-None”. Click in the box and a drop-
down menu will appear. Change the property to “1-Fixed Single”. A border will
appear around the label
 Now add 2 more labels to your form. Change the caption of one to “First Name” and
change the other to “Last Name”. Now click each label and drag them next to each
textbox.

Your form should look something like this:

Writing the Code

 Double click on the command button. Your screen will change and this will appear:

Private Sub Command1_Click()

End Sub

You are now in the code view mode. Here is where you will start doing some programming.

You are going to make a sentence appear in the big label by entering some information in the
textboxes and clicking on the button.

 Start by typing this into the space between "Private Sub" and "End Sub":
Label1.Caption =

 This tells the program that when the button is clicked, something is going to appear in
the label.
 Now add this to the line

Label1.Caption = "My name is"

 Now we are going to make whatever we type in the textboxes appear in the label. Add
this to the line of code:

Label1.Caption = "My name is" + Text1.Text + " " + Text2.Text

 This is saying that the text in each textbox will be added to the contents of the label.
You need to add the plus signs so that everything will appear in order in the label.
 The set of empty quotation marks between Text1.Text and Text2.Text is there so there
will be a space between the first name and last name when the program runs.

So your completed code should look like this:

Private Sub Command1_Click()

Label1.Caption = "My name is" + Text1.Text + " " + Text2.Text

End Sub

 Now run your program. Click the triangular Play button on the top of your screen.
 Type your first name into the first textbox, then your last name into the second text box.
Then click the button.
 Your screen should look something like this:

Notice that there is no space between 'is' and your first name.
To stop the program, use the 'X' in the corner.

 Go back into your code and add a space between 'is' and the quotation mark. Then run
the program again. Type in the first and last name and click the button. The space
should be there now.

Adding Things On (Bonus Points)

 If you have time left, it would be nice to have a button on the screen to end the program
so we don't have to use the 'X'.
 Go back to your form and add a button. Change the caption to 'Exit', then double-click
on it to enter the code view.
 In the space between the existing code, add this line:

End

 Now run your program. When you're finished, click the Exit button.

 Finally, let's add a button to clear the textboxes and the label, in case we make a
mistake when we enter our inof into the textboxes.
 On your form, create a button. Change the caption to 'Clear', then double click on it to
enter the code view.
 In the space between the existing code, add these lines:

Text1 = ""
Text2 = ""
Label1.Caption = ""

 What the set of empty quotes says is that we want nothing to be in the textboxes or the
label.
 Now run the program again, enter the info in the textboxes, click the button to fill the
label, then click the Clear button.

Visual Basic Lab #2

Creating a Cash Register for the Canteen

Situation: The canteen has decided to go hi-tech and create a small cash register to add
up customer's totals.
To make this work in VB, you have to be able to take a number from a textbox and
perform a calculation on it. To do so, you need to add something to the textbox code
you created in Lab #1:

Val(Text1)- Val means value


Next, you need to know what a variable is. In math, you have seen
variables in algebra like 'x' or 'y'. These letters hold values
(numbers). In VB, a word can be a variable, such as:
price = Val(Text1)- This means that we are going to take whatever
number is typed into Text1 and hold it in a variable called 'price'
until we need to do something else with it.
We can also make a variable hold a calculated value, such as:
fee = Val(Text2) * 1.5- This means we are going to take whatever is
typed into Text2, multiply it by 1.5 and hold it in the variable 'fee'.
Next, we can take the values of 2 or more variables and perform
calculations on them, such as:
total = price + fee- This means we are taking the value stored in
'price' and adding it to the value stored in 'fee', then putting that
value in another variable called 'total'.
Finally, you can take a variable and display it in something like a
label, such as:
Label.caption = total

Here's Your Lab


Step 1: Open up Visual Basic and start a new project. Save the
form and the project in your server folder as 'ct3200lab2'.

Step 2: Create a form with the following objects:


 5 textboxes
 8 labels, called the following:
"Welcome to the HNMA Canteen"
Chips: $1.00
Ice Cream: $0.75
Water: $1.00
Small Milk: $0.45
Large Milk: $0.80
"Enter the quantity here:"
"Your Total:"
- Leave the 8th one blank and change the border style to
"Fixed Single"

 3 buttons, called the following:


Calculate Total
Clear All
Exit
Your form should look something like this:

Step 3: Double click on the "Calculate Total" button to bring up the


code window. Most of your code will go under this button.
You need to create variables for the 5 items on the menu (look at the
prices on the labels on your form). Here's the first one, but you need to
come up with the rest of them yourself (HINT: You're going to take the
number typed into each textbox and multiply it by the price of the item).
Type them all under the code for the "Calculate Total" button.
chips = Val(Text1) * 1

Step 4: Now you need to add all your variables together to get the
total for the customer:
total = chips + ..... + ..... + ..... + .....
Step 5: Now you have to display your total to the screen. Make sure
you choose the right label.
Label8.Caption = ? (What goes in place of the ?)

Step 6: Run your program. Enter some numbers in the textboxes


and click the "Calculate Total" button. Did you get a total?

Step 7: Double-click the "Clear All" button. Write the code to clear all
the textboxes and the label for displaying the total. Think about how
you did it for Lab #1. Then run your program to see if it works.

Step 8: Double-click the "Exit" button and write the code to make it
work. Run your program to make sure it works.
Extras
 Disable the "Clear All" button when the program first starts and
enable it again when the "Calculate Total" button is clicked.

Visual Basic Lab #3


Learning to Use Functions By Calculating A
Class Average

WARNING!!!: This might be a long and confusing


lab. The good news: You can do it, just take your
time. Remember, you're finishing your first week
of programming. Everybody won't finish this lab
right away.

A function is like a mini-program within the bigger program that


you can call over and over when you need it. Instead of typing the
same code for several buttons, you can write a function, give it a
name, then use a simple line of code to put it to work when you
need it.
In this lab you will create some functions that will calculate
averages for 3 students, then calculate a class average.

Here's the Lab


STEP 1: Draw the form you see above. There are:
 5 textboxes for you to enter test marks into
 3 buttons for you to program to calculate the marks for each
student
 3 labels for you to display the averages in once they are
calculated
 A button to clear the textboxes so you can enter marks for
the next student (Next Student)
 A button to calculate the class average
 A label to display the class average
 A button to end the program
Save the form and the project as 'ct3200lab3'
STEP 2: Go to your code view. Type the following lines of code at
the top of the blank page:
Option Explicit

Dim student1 As Double


Dim student2 As Double
Dim student3 As Double
Dim classavg As Double

Why do you do this? Well, in order for your entire program to see
and use the variables you will use for this lab, you need
to declare them first. Think of it as being like putting a sign on the
bathroom door to tell visitors that it is there for everybody to use.
STEP 3: Go back out to your form and double-click on the 'Student
#1 Avg' button to bring up the code view. Type in this line of code:
Private Sub Command4_Click() NOTE: Your buttons and labels might have different
names
Call s1
Label9.Caption = student1
End Sub

'Call s1' means that you are going to call a function named 's1'
that will do a calculation for you.
STEP 4: Move down a couple of lines past this code and type in
the following:
Private Function s1()
student1 = NOTE: 'student1' is a variable that will hold the first student's average until you
display it or use it in another calculation
End Function

The equation after 'student1=' has been left out because I want
you to figure out how you would calculate an average. What do
you do? Add up all the marks and divide by the number of marks.
Remember the code you wrote for Lab #2? You need to think
about that in order to fill out the equation you need.
STEP 5: Set up your button for Student #2:
Private Sub Command4_Click() NOTE: Your buttons and labels might have different
names
Call s2
Label10.Caption = student2
End Sub

STEP 6: Set up your function for the second student average:


Private Function s2()
student2 = HINT: The equation for the average is going to be the same every
time-you just need to change the variable in front
End Function

STEP 7: Set up your button for Student #3:


Private Sub Command4_Click() NOTE: Your buttons and labels might have different
names
Call s3
Label10.Caption = student3
End Sub

STEP 8: Set up your function for the second student average:


Private Function s3()
student3 = HINT: The equation for the average is going to be the same every
time-you just need to change the variable in front
End Function

STEP 9: Now you need to set up the button to calculate the class
average:
Private Sub Command3_Click()
Call class
End Sub

STEP 10: Now you need the function that will calculate the class
average for you:
Private Function class()
classavg = (student1 + student2 + student3) / 3
End Function

STEP 11: Write the code for the 'Next Student' (Clear) button and
the Exit button.
Step 12: Run your program. Enter some numbers in the textboxes,
then click the first student average button. Click the Next Student
button and repeat the process for the second and third students.
Then click the Class Average button.
If everything doesn't work, don't worry about it. IT WILL WORK
EVENTUALLY!!

Extras
 Disable the 'Class Average' button until it is needed (until the
3 student averages have been found)
Visual Basic Lab #4

 Introduction to Some Built-in Functions


 Introduction
 In Visual Basic, there are a group of built-in functions that perform
different tasks for you that you may need from time to time.
 One of these is called "Len", which tells you how many letters are
in a particular word typed into a textbox
 In this fairly simple lab, you are going to use the Len function.
Also, you are going to use an INPUT BOX for the first time. When
called, this lets you enter information and send it to certain places.
 Here's Your Lab
 STEP #1: Create the following form. From now on, you are going
to put names on the different objects that tell anybody who looks
at your work what each object is used for.

 Form name: frmLength
 Command1 name: cmdDisplay
 Command2 name: cmdClear
 Picture Box name: picOutput

 STEP #2: Double click cmdDisplay. When the code window


opens, type this line of code:
 Call length
 This line calls a sub procedure called 'length' that is going to do
the work for you. A sub procedure is like the function you used in
the same lab.
 STEP #3: Click outside the code for the cmdDisplay button, move
down a few spaces and type in the red text as the code for the
sub procedure:
 Private Sub length()
Dim word As String (this means that the variable "word" is
going to be...a word)
Dim length As Integer (means that the length of the word will be
displayed as 1,2,3, etc.)
word = InputBox("Enter a word here", "Word") (this will cause an
input box named 'word' to pop up when you click the Display
button that will ask you to 'Enter a word here')
length = Len(word) (this means that the 'Len' function will look at
the word you type, figure out how many letters there are in it and
store that number in the variable 'length')
picOutput.Print "The number of letters in "; word; " is ";
length (this means that you are going to print your results in the
form of a sentence to a picture box)

End Sub
 STEP #4: Go out to your form, double click the Clear button and
type this line of code:
 Private Sub cmdClear_Click()
picOutput.Cls
End Sub
 Step #5: Run your code to see if it works. Save your project and
form as 'ct3200lab4'

Visual Basic Lab #5


Making Long Division Easy
Introduction
This lab will give you a chance to work with calculations in Visual Basic
and learn how to use one of Visual Basic's built in functions, "INT".
The "INT" function is used when you have a number with a decimal.
"INT" takes whatever appears before the decimal and displays it to your
screen.

Here's your lab


STEP #1: Create a form that looks something with the following
objects:
 Label: lblTitle: Holds the title of your project
 Label: lblDividend
 Label: lblDividend
 Textbox: txtDividend
 Textbox: txtDivisor
 Picture Box: picOutput
 Command button: cmdDivide
 Command button: cmdClear

STEP #2: Go into your code window and add this code on the blank
page:
Dim divisor As Single
Dim dividend As Single
Dim quotient As Single
Dim remainder As Single
If you declare a variable as 'Single', it means that the value it holds can
range from as low as 1.4 x 10-45 to as high as 3.4 x 1038
STEP #3: Now add this code under the cmdDivide button (go back to
your form and double click on the Divide button if you need to)
Private Sub cmdDivide_Click()

divisor = Val(txtDivisor) (takes the value of the textbox and


stores it in the variable 'divisor')
dividend = Val(txtDividend) (takes the value of the textbox and
stores it in the variable 'dividend')

quotient = Int(dividend / divisor)


(calculates the quotient, then stores everything to the left of the
decimal in the variable 'quotient')

remainder = dividend - quotient * divisor (this calculates the


remainder for the long division and stores it in the variable
'remainder)

picOutput.Print "The quotient is"; quotient (prints the quotient to


the screen)
picOutput.Print "The remainder is"; remainder (prints the
remainder to the screen)
End Sub
STEP #4: Write the code to for the Clear button. You will need to clear
out both textboxes and the picture box
 HINT: For the picture box, you will need to use this line of code:
"picOutput.Cls"
STEP #5: Run your code. Type some numbers into the textboxes and
see what happens
STEP #6: Save your form and project in your server folder as
'ct3200lab5'

Visual Basic Lab #6


Converting Imperial Measurements to Metric
Intro
In this lab you will be building a program for converting Imperial
measurements (miles, yards, feet inches) to kilometers, meters and
centimeters.
Your program will take information from textboxes, perform a
calculation and display the results to a picture box.
You will be using the FormatNumber function to round off some of the
numbers you will be calculating.

Here's Your Lab


STEP #1: Open Visual Basic and create the form below:

On this form there are:


 4 labels
 4 textboxes: One for Miles, Yards, Feet and Inches
 1 picture box: To display the answer to the calculation
 2 command buttons: One for performing the calculation and
another for clearing the picture box
Put these objects on your form and put the proper names on them that
tell what they do

STEP #2: Open your code window and enter the following code to
declare the variables you will be using:
STEP #3: Enter the code for the button that will perform the
calculation

NOTE: Here are some things for you to remember that will help the
TOTAL INCHES equation make more sense:
1 mile = 63360 inches
1 yard = 36 inches
1 foot = 12 inches
**Only type in the code below that is in red
** Your command button might not be called 'cmdDisplay', or your
picture box might not be called 'picResult'. CHANGE THE CODE
BELOW TO MAKE SURE YOUR NAMES MATCH.
NOTES:
 FormatNumber (kilometers, 1) takes the value in the variable
'kilometers' and rounds it to 1 decimal place.
 picResult.Print by itself inserts a blank line to help space your
text
STEP #4: Enter the code for the Clear button. You will need to clear
out the 4 textboxes and the picture box
 HINT: Think back to your last labs to figure out how to clear the
textboxes and picture box.

STEP #5: Run your program and put some numbers in the
textboxes to see what happens.

STEP #6: Save your project and form as 'ct3200lab6'


Visual Basic Lab #7
Introduction to Logic: If-Then Statements
"Converting Number Marks to Letter Grades"
Intro
In this lab you will begin to work with logical statements. Basically,
this means that part of your program will be asked to make a decision
about something, usually information that is received from the user. For
every possible situation, there are one or more possible actions that
can be taken.
For now, you will be working called an If-Then statement. In other
words, "If something happens, then something else will happen in
response".

Here's Your Lab


Since it's close to report card time, in this lab you will create a program
that will write a program that will convert your averages into letter
grades. When the program runs, you should be able to enter a number
into the textbox, click the correct button and have a letter grade appear
in the picture box:
F- Anything under 50
D- Anything from 50 to 55
C- Anything from 56 to 64
B- Anything from 65 to 79
A- Anything from 80 to 100
STEP #1: Create the following form in Visual Basic with these objects:
lblTitle: Displays the title for your form
lblDirection: Holds the instructions for the user
picOutput: Displays the result of your program.
cmdCheck: The button that the user will click to execute the main part
of your program.
cmdClear: This button will clear the picture box and text box.
cmdExit: Ends your program.
STEP #2: Now you will write the code for the 'Check Grade' button that
will do most of the work for this program. Double-click the 'Check
Grade' button and type in the following code (only type what you see
in red):
STEP #3: Go up to the drop-down menu that should say 'cmdCheck'
and select 'cmdClear'. Now write the code to clear the textbox and
picture box on your form.
STEP #4: Go back up again and select 'cmdExit' and write the code
to end the program.
STEP #5: Save you form and project as 'ct3200lab7'
STEP #6: Run your program to see if works. Try a few different
numbers to make sure the right letter grades appear in the picture box.
If you have any errors, go back and check them out before you finish.

Visual Basic Lab #8


Introduction to Logic: If-Then Statements
"The Bank Machine"
Intro
In this lab you will continue to practice with If-Then statements, but you
will also use a calculation that your program will have to take and make
a decision on. Also, you will use a "nested" If-Then statement. This is
an If-Then statement within another If-Then statement- depending on
the result of one, the other one may or may not be executed.

Here's Your Lab


Lawn has its first bank machine-well, sort of. You are going to create a
program that takes the current account balance and the amount you
wish to withdraw and computes the transaction. If you don't have
enough money, or if your balance gets too low, the ATM will let you
know.
STEP #1: Create the following form in Visual Basic with these objects:
lblTitle: Displays the title for your form
picOutput: Displays the result of your program.
cmdCompute: The button that the user will click to execute the main
part of your program.
cmdClear: This button will clear the picture box.
cmdExit: Ends your program.

STEP #2: Now you will write the code for the 'Compute Transaction'
button that will do most of the work for this program. Double-click the
'Compute Transaction' button and type in the following code (only type
what you see in red):

STEP #3: Go up to the drop-down menu that should say 'cmdCompute'


and select 'cmdClear'. Now write the code to clear the picture box on
your form.
STEP #4: Go back up again and select 'cmdExit' and write the code
to end the program.
STEP #5: Save you form and project as 'ct3200lab8'
STEP #6: Run your program to see if works. Try a few different
numbers to make sure calculation works. Try to withdraw more money
than is in the account.

Visual Basic Lab #9


Introduction to Logic: If-Then Statements
"The HNMA CD Store"
Intro
OK, so you have completed a couple of labs finished dealing with If-
Then statements. Now you're going to do some of the thinking yourself.
You'll get the basic idea plus a little help, but you'll have to figure out
what the main coding will be yourself.

Here's Your Lab


The graduating class is selling blank CD's in bulk and they want a quick
way to add up a customer's order. If people buy less than 25 CD's,
they will cost $1.25 each. But if someone wants more than 25, the cost
will be 75 cents each.
Each order will need 15% tax added on. Then you will need to add the
cost of the order to the tax in order to get the customer's total cost.
STEP #1: Create the following form in Visual Basic with these objects:
cmdOrder: Brings up an input box for you to enter the number of CD's
in the order
cmdTax: Calculates the tax for the order
cmdTotal: Calculates the total cost for the CD's
picCost: Displays the price for the CD's ordered
picTax: Displays the amount of tax to be paid
picTotal: Displays the total cost for the CD's
cmdClear: Clears all the picture boxes
 Also, you need to add the other labels that tell you what each
picture box is for
STEP #2: Declare these variables that you will use for this program by
writing them in the blank code page:
Dim num As Single ('num' will be the number of CD's ordered)
Dim cost As Single ('cost' will be the number of CD's multiplied
by the price)
Dim tax As Single ('tax' will be the tax charged for the CD's
ordered)
Dim total As Single ('total' will be the cost plus the tax)
STEP #3: For the cmdOrder button, you will need to write a line of
code to bring an input box that you will use to enter the number of CD's
that a customer orders:
num = (InputBox("Number of CDs:"))
STEP #4: Now YOU have to figure out the If-Then statements that go
under the cmdOrder button. There will be 2 choices:
 If the customer order less than 25 CD's, the cost will be the
number entered in the input box multiplied by $1.25. The cost will
then be displayed in picOrder
 Or, if the customer orders more than 25 CD's, the cost will be the
number entered in the input box multiplied by 75 cents. The cost
will then be displayed in picOrder
STEP #5: Now you need to program the cmdTax button to calculate
the tax on the number of CD's ordered
 The tax will equal the cost multiplied by 0.15
STEP #6: Now you need to program the cmdTotal button to calculate
the total for the CD's ordered
 The total will equal the cost plus the tax
STEP #7: Program the cmdClear button to clear the three picture
boxes, picCost, picTax and picTotal. If you need to, check back to
another lab if you can't remember what the line of code is.
STEP #8: Go out to your form. Make a button, re-name it cmdExit and
change the caption to 'Exit'. Then double click on it and write the line of
code to make it end the program.
STEP #9: Run your program to see if it works. If it doesn't, ask for help.
STEP #10: Before you finish, save your project and form as
'ct3200lab9'

Visual Basic Lab #10


If-Then Statements
"Creating an on-line quiz"
Intro
Now that you're getting more comfortable with using If-Then
statements, you can use them to work with a new Visual Basic object-
the option button.
The option button is used when you want a user to be able to pick
only one choice from a list, just like in a multiple choice test. The code
for an option button is generally:
option1.Value = true or false
In this lab, you are going to create a multiple choice quiz using option
buttons. As you answer questions, you will keep a running score of how
many answers the test taker gets right.

Here's Your Lab


You need to create a multiple choice quiz with at least 5 questions. The
quiz can be about anything you want (keep it clean). You only need to
have 3 possible answers for each question.
You will keep score using an equation that adds up the correct answer.
STEP #1: Create the following form in Visual Basic with these objects:

 optQ1_1: The option button for question 1, choice 1


 optQ1_2: The option button for question 1, choice 2
 optQ1_3: The option button for question 1, choice 3
 cmdQ1: The 'Submit Answer #1' button
 lblAnswer: Displays a message telling the user that the answer is
correct or not

 lblTotal: Displays the number of correct answers


NOTE: The rest of the labels on the form don't NEED to be named
because they will not be affected by the coding you will do- they just
display information.
STEP #2: Declare the variable that will count the number of write
answers for you. Type this into the blank code page:
Dim total as Integer
STEP #3: Now you need to set up the code for the first question in your
quiz. This code will be for the cmdQ1 button (type only the red text):
STEP #4: Make up 4 more questions with 3 possible answers each
(write them on scrap paper first, then transfer them to your VB form).
Then draw the objects on your form (the same ones you already have).
You should have 5 questions in all.
Use the same code as above, but change Q1 to Q2, then Q3, and so
on. For the correct answer to each question, include the code for
counting the correct answers (total = total + 1), as well as the code for
the label to display the total.
Change the option button with the right answer to the first or second
option button so that all your answers aren't the last option.
STEP #5: Add an Exit button to end your program
STEP #6: After you create 2 questions, run your code to see if it works.
GET SOMEBODY ELSE TO TAKE YOUR QUIZ TO SEE HOW THEY
DO!!
EXTRAS
 Add a "Clear All" button that will clear all the labels and enable the
buttons again so somebody else can take the quiz without ending
the program
 After the last question is answered, display a message box that
shows the user's score.

Visual Basic Lab #11


If-Then Statements: Using the Check Box
"Creating a Student Registration Program"
Intro
You've had some practice with the option button by finishing the last
lab. Now you are going to work with a new object called the check
box. The check box works something like an option button except you
can use it to pick as many options as you want. For example:
check1.Value = 0 (not checked) or 1 (checked)
In this lab, you are going to create program for registering new
students. The check boxes will be used to select courses for each
student.

Here's Your Lab


You need to create a program that is used to:
 enter information about a student and pick a grade from a list of
option buttons
 select courses from a list (no more than 6 courses can be
selected or a message box will appear)
 display the student and course information in separate picture
boxes
 clear either the student information or the course information with
separate buttons
You will keep count of the number of courses using an equation like the
one from the last lab that you used to keep score of the quiz questions
STEP #1: Create the following form in Visual Basic with these
objects:

You will need to make 7 textboxes to enter student information into


your program:
 txtFirst: For the first name
 txtLast: For the last name
 txtAge: Student's age
 txtAddress: For a P.O. Box or street address
 txtTown: Student's hometown
 txtPost: For the postal code
 txtPhone: For the phone number
You will need a set of 3 option buttons to select the grade for the new
student:
 optG10: Will select 'grade 10'
 optG11: Will select 'grade 11'
 optG12: Will select 'grade 12'
You will need 2 picture boxes to display the information you enter:
 picInfo: Displays the student information from the text boxes
 picCourses: Displays the information about the courses you select
using the checkboxes.
You will need 9 check boxes to select the courses for the new student:
 chkMath
 chkChem
 chkBiology
 chkEnglish
 chkComp
 chkFrench
 chkPhysics
 chkGym
 chkHealth
You will need 5 command buttons:
 cmdReg: Adds registration info to picInfo
 cmdCourses: Adds course info to picCourses
 cmdClearReg: Clears picInfo, all the textboxes and the option
buttons
 cmdClearCourses: Clears picCourses and all the check boxes
 cmdExit: Ends the program
In your empty code window, declare the variable that you will use to
count the number of courses a student registers for:
Dim course_total As Integer
STEP #2: Now, enter the code for cmdReg. Only enter the code
shown in red:
STEP #3: Under the cmdCourses button, enter the
following red code:
 This is the code for ONE check box. There are 9 altogether, so
you need to repeat this code for all the other ones. Start right
under the 'End If' above. All you need to do is copy the code, but
make sure you change the name of each one to the proper
subject (Ex: change chkMath to chkChem and so on) and
change what is displayed out ot the picture box (Ex: change
"Math" to "Chemistry"). You will have 9 separate If-Then
statements.
STEP #4: Enter this code to get the cmdClearCourses button
working. Use only the red text:
Private Sub cmdClearCourses_Click()

picCourses.Cls (Clears picCourses)


chkMath.Value = 0 (Clears chkMath)
 From here you need to clear out the rest of the check boxes. Use
the same code that you see above for chkMath.
End Sub
STEP #5: Enter this code to get the cmdClearInfo button working.
Use only the red text:
Private Sub cmdClearReg_Click()
txtFirst = "" (Clears txtFirst)
optG10.Value = False (Clears optG10)
 Now you need to enter the code to clear the other 6 textboxes
and the other 2 option buttons
End Sub
STEP #6: Write the code for your cmdExit button (You should know
what this code is by now)

Visual Basic Lab #12


The Timer Control
"Creating a Stopwatch"
Intro
The timer control is used when you want parts of your program to be
time activated. This will become more important later when we look at
creating VB programs that run motors and other electronic
components. But for now you can get some idea of what the timer
control can do by completing this lab.
 The timer control is located in your toolbox with the other objects
like the textbox, label, etc.
 It has an Enabled property that can be set to True or False
 It has an Interval property (measured in milliseconds-thousandths
of a second) that can be set according to how fast you want your
timer to count
In this lab, you are going to create a simple stopwatch.

Here's Your Lab


You need to create a stopwatch that can be started and stopped, then
reset to '0'.
STEP #1: Create the following form in Visual Basic with these
objects:

cmdStart: Starts the stopwatch


cmdStop: Stops the stopwatch
cmdReset: Resets the stopwatch
cmdExit: Ends the program
lblTime: Displays the time
tmrWatch: The timer that will be needed for this program

STEP #2: Make sure you have the timer selected on your form. In the
properties window on the right, set the Enabled property to False and
the Intervalproperty to 100.
STEP #3: Enter this code for the cmdStart button (only the code in red):
STEP #4: Enter this code for the cmdStop button (only the code in red):

STEP #5: Enter this code for the cmdReset button (only the code
in red):

STEP #6: Enter this code for tmrWatch timer (only the code in red):
STEP #7: Enter the code for the cmdExit button (you should know this
code by now):
Private Sub cmdExit_Click()
WHAT GOES HERE?
End Sub
STEP #8: Run your program to see if it works
Extras
 In the Properties window, change the Interval to 10. Then in your
code, change the code for the timer from 0.1 to 0.01. What
happens?

Visual Basic Lab #13


Working With Nested If-Then Statements
"Creating A Rental Bill"
Intro
You used a nested If-Then statement in an earlier lab, which is one If-
Then statement inside another one. If the main one is true, the program
jumps into the nested one and checks the condition to see if it's true or
false.
In this lab, you are going to use nested If-Then statements to
create a bill for an equipment rental store. You will have to type in
the number of the item you wish to rent and the amount of time
you want it for- a half-day or full-day.
You are also going to use the Tab function. This allows you to line
text up in a picture box to make it look like a table. For instance,
Tab(10) would make text line up on the 10th space on a line.

Here's Your Lab


STEP #1: Create the following form in Visual Basic with these
objects:

 cmdRates: Displays the company's rental rates to picRates


 cmdBill: Displays the rental bill to picBill
 cmdClear: Clears the picture boxes and textboxes
 cmdExit: Ends the program
 picRates: Displays the prices for the rental items
 picBill: Displays the customer's bill
 txtItem: The user types the item number here
 txtTime: The user types the rental length-half day or full
day
 3 other labels for displaying directions and information:
these don't need special names
STEP #2: In the blank code window, declare the following
variables. You can copy and paste this line:
Dim deposit As Integer, item As String, time As String, price As String, totalbill
As Single, bill As Single

STEP #3: Double click on the cmdRates button and enter the
following code to make this button work (type only the code in
red):

STEP #4: Double click on the cmdBill button and enter the
following code to make this button work (type only the code in
red):
STEP #5: Enter this code for the sub procedure that will calculate
the total bill and display it to picBill: (type only the code in red):
STEP #6: Enter the code to get the Clear button working. You need
to clear both picture boxes and both textboxes.
STEP #7: Enter the code to get the Exit button working.
STEP #8: Run your program and try different combinations of
items and time.
STEP #9: Save your program as ct3200lab14

Visual Basic Lab #14


The Select Case Block
Introduction
Intro
A Select Case block is an efficient way to make decisions in VB that
simplifies between different options without having to use too many If-
Then statements.
In this lab, you are going to use a Select Case block to make a
simple set of conditions that will make a decision based on
whatever is typed into a textbox.

Here's Your Lab


You are going to determine which medal is going to be presented to the
top finishers in a cross country race:
STEP #1: Create the following form in Visual Basic with these
objects:

 txtNumber: Used to type in a number to determine the


output (the message that will appear)
 picOutput: Will display a message, depending on the
number typed into the textbox
 cmdMedal: When clicked, a message will appear in the
picture box
 cmdClear: This will clear the textbox and the picture box
 cmdExit: This will end the program
There are 2 other labels on the form which will display
information, but they don't need special names.
STEP #2: Double click on the cmdMedal button and in the code
window enter the following code to get it working (type only what
you see in red):
STEP #3: Enter the code to make the Clear button work.
Remember, you need to clear the textbox and picture box. Fill in
the question marks with the proper code.
txtNumber = ?
picOutput.?
STEP #4: Enter the code to make the Exit button work. Remember,
you only need one word.
STEP #5: Run your program. Try entering all the numbers between
1 and 5. Then try a higher number
STEP #6: Save your program as ct3200lab13

Visual Basic Lab #15


Introduction to Repetition
"Do While Loops"
Intro
Introduction
Repetition is used widely in complex programming. A loop is used to
repeat a sequence of code a number of times. At each repetition,
or pass, the statements act upon variables whose values are
changing.
The number of time the code is repeated can be pre-set so that it ends
when you want it to (if you don't set an end point, your program will run
in an infinite loop, causing an error).
The first type of loop you will work with is the Do While Loop. The Do
While Loop repeats the code inside it as long as a certain condition is
true. For example:
Do While number < 50
number = number + 1
Loop
The equation "number = number + 1" will repeat itself as long as the
value of "number" is less than 50. Then, once 50 is reached, the loop
will end and the rest of the program will be executed.
In this lab, you are going to use a Do While Loop to run code that
will tell you how long it will take for the world's population to
reach 10 billion people.

Here's Your Lab


Right now, the world's population is about 6 billion people and
increases by 1.4% every year. So how long would it take to reach 10
billion, and in what year would this occur?
STEP #1: Create the following form in Visual Basic with these
objects:
 cmdYears: Executes the main code for the program
 picOutput: Displays the results of the calculations that
cmdYears executes
 cmdClear: Clears picOutput
 cmdExit: Ends the program
STEP #2: Double-click on the cmdYears button and enter the
following code. Only enter the red code:
STEP #3: Now enter the code for the Clear and Exit buttons that
you have used time and time again in previous labs.
STEP #4: Save your work as 'ct3200lab15'
STEP #5: Run your program. Click the "Years to 10 Billion" button.
You should get an answer of 37 years to reach 10 billion, and the
population should reach 10 billion by the year 2042.
THINK ABOUT THIS: In the time it took for you to click the button,
the code inside the Do While Loop ran 37 times (current_pop was
calculated 37 times until it reached 10 billion).

Visual Basic Lab #16


Introduction to Repetition
"For...Next Loops"
Intro
Introduction
In the last lab, you used a Do While Loop that kept repeating itself until
a certain point was reached. The problem was that you didn't know how
long it would take. In the case of that lab, the code ran 37 times before
reaching its end value.
For the next couple of labs you will be using something called
a For...Next Loop. This kind of loop lets you set the number of times
the loop repeats before stopping. For example:
For year = 1 To 5
picOutput.Print i * 10
Next year
This For...Next Loop will run 5 times. Each time it will take the value of
the variable year (which will be 1,2,3,4, or 5), multiply it by 10 and
display it to picOutput. "Next year" will change from 1 to 2, 2 to 3, and
so on until it reaches 5. Then the loop ends and the program moves on.
The variable "year" is called the control variable that changes after
every repetition of the loop. "1" is the initial value and "5" is
the terminating value.
Most of the time, the letters "i", "j", or "k" are used to name the control
variable instead of giving them descriptive names- just a part of
programming protocol.
In this lab, you are going to use a simple For...Next loop to
perform a mathematical calculation and display the results to a
picture box.

Here's Your Lab


Let's say that the population of Marystown has been increasing by 3%
per year since 2000, and you want to write a program that will tell you
what the population will be up until 2010.
STEP #1: Create the following form in Visual Basic with these
objects:
 cmdPop: Executes the main code for the program and
displays it in picOutput
 picOutput: Displays the results of the calculations to the
screen
 cmdClear: Clears picOutput
 cmdExit: Ends the program
STEP #2: Double-click on the "Show Populations"
(cmdPop) button and enter the following code. Only enter the red
code:
STEP #3: Enter the code for the Clear and Exit buttons
STEP #4: Save your work as 'ct3200lab16'
STEP #5: Run your program. Click the "Show Populations" button.
You should have a list of years from 2000 to 2010 in one column
and a list of populations for each year in another. The largest
value should be around 7392.
Visual Basic Lab #17
Introduction to Repetition
"Using Nested For...Next Loops"
Introduction
In the last lab, you used a For...Next Loop to calculate and display
populations over a 10-year period.
Now it's time to take the next step. A nested For...Next Loop works in
the same way as the nested If-Then statements you used earlier. Once
the outside loop starts, the inside loop also begins to run and execute
its instructions. Both loops are providing pieces of information at the
same time. For example:
For i = 1 To 5
For j = 1 To 5
picOutput.Print i; "+" j; "="; i + j,
Next j
Next i
Each one of these For...Next Loops will run 5 times. Each time the "i"
loop runs, it triggers the inside nested loop to also run. Each loop will
send a value to the calculation "i + j" which will produce an answer and
display it to the screen.
Remember, the inside nested loop must end before the outside one
In this lab, you are going to use a nested For...Next loop structure
to produce a multiplication facts table.

Here's Your Lab


You need to create a multiplication table for younger students using a
set of For...Next loops that will produce the numbers that will be
multiplied together.
STEP #1: Create the following form in Visual Basic with these
objects:

 cmdFacts: Executes the main code for the program and


displays it to picOutput
 picOutput: Displays the results of the calculations
 cmdClear: Clears the contents of picOutput
 cmdExit: Ends the program
STEP #2: Double-click on the cmdFacts button and enter the code
you see in red:

NOTE: The first time this loop executes, it will send a 1 to f1.
Then, it moves to the inside loop and f2 runs through all the
values of f2from 1 to 10. So when you run the program and
look at the screen, your top row of the table will show the "1
times" facts. After that, it runs through the loop again,
changes f1 from 1 to 2, and so on. On the click of the
button, 50 calculations are made.
STEP #3: Enter the code to get the Clear and Exit buttons working
STEP #4: Save your work as 'ct3200lab17'
STEP #5: Run your program. Click the "Display Multiplication
Table" button. If you entered your code correctly, you should
display a chart with all the multiplication facts up to 10 x 10.

Visual Basic Lab #18


Introduction to Repetition
"Using Do Until Loops"
Introduction
In Lab #15, you used a Do While Loop which repeats itself while a
certain condition is true, then stops when the condition becomes false.
A Do Until Loop works in a similar way, but with one major difference.
This loop will repeat itself until the condition you set becomes true.
For example:
Do Until points > 100
points = goals + assists
Loop
For this loop, the calculation "points = goals + assists" will continue until
the number of points reaches the level you set- in this case, 100.
There is also another way to program this loop:
Do
points = goals + assists
Loop Until points > 100
You can put the "Until..." part of the code next to "Loop" if you
want. The program will work either way.
In this lab, you are going to use a Do Until Loop to find out how
long it would take you to become a millionaire.

Here's Your Lab


You would like to know how long it would take to become a millionaire if
you deposited a certain amount of money into a bank account that paid
7% interest.
STEP #1: Create the following form in Visual Basic with these
objects:
 txtDeposit: You will use this textbox to enter the amount
of money you will deposit into the account
 cmdYears: This is the button that will contain the main
code for your program and send the results to picOutput.
 picOutput: This is the picture box that will display the
results of the calculations
 cmdClear: Clears out both the textbox and picture box
 cmdExit: Ends the program
STEP #2: Double-click the cmdYears button and enter the
following code to get it working. Only enter the red code:
STEP #3: Enter the code to make
the cmdExit and cmdClear buttons work. (REMEMBER: your Clear
button has to clear both the picture box AND textbox at once.
STEP #4: Save your work as 'ct3200lab18'
STEP #5: Run your program. Try different amounts for your
deposit. For example, if you enter $100, you should reach $1
million in only 137 years.
Visual Basic Lab #19
Using Sequential Files
"Saving Information to a File"
Introduction
You can use Visual Basic to create a program that accepts information
and sends it to an outside file that will save it for you to use later.
What you need to do is first create a file (for example, a ".txt" file in
Notepad), write the code for VB open it, set up what information will be
sent to the file, then run the program, enter the info and send it to the
file using a button.
In this lab, you will do just that. You will be entering statistics for
different school basketball players and saving them in a Notepad file.

Here's Your Lab


The basketball team would like to have a way to easily keep track of
their statistics.
STEP #1: Create the following form in Visual Basic with these
objects:
 5 labels with the captions you see above: "Basketball
stats", Player's Name:", etc.
 txtPlayer
 txtPoints
 txtAssists
 txtRebounds
 cmdAdd: You will click this button AFTER you enter the
info in the textboxes
 cmdClear: Click this to clear the textboxes so you can
enter more info.
 cmdExit: Ends the program
STEP #2: Save your project and form RIGHT NOW as
'ct3200lab19'. It is very important you save this RIGHT NOW or the
rest of your lab won't work probably.
STEP #3: Open Notepad by going to your Start menu, then
Programs...Accessories...Notepad. Save the blank file as
"stats". IMPORTANT: MAKE SURE YOU SAVE THE FILE IN THE
SAME PLACE YOU SAVE YOUR VB LABS!!!!!
STEP #4: In the blank code window, enter the following variable
declarations you will need for this program
Dim player As String, points As String, assists As String,
rebounds As String
STEP #5: Now you need to enter the code in red to get the main
part of the program running. This code will be executed when
the cmdAddbutton is clicked, so enter it under that one:
STEP #6: Enter the code for cmdClear (clears the 4 textboxes)
and cmdExit (ends the program)
STEP #7: Run your program. Add information for 3 different
players. make up your own names and numbers.
STEP #8: Now, go out to where you saved your "stats.txt" file.
Open the file- is there anything in it? If not, there may be
something wrong with your code...go have a look.
STEP #9: Make sure you have all your work saved.

Visual Basic Lab #20


Using Multiple Forms
on One Project
Introduction
Many large programs have many forms that the user has to move
between, just like moving around a Website. Some programs also have
what is called a splash screen, which is an introductory screen that
opens first when you open the program.
You will be asked to have a splash screen when you complete your
major project, so here's a simple lab to get you introduced to the idea.

Here's Your Lab


STEP #1: Open a new project and put a command button on the
form
STEP #2: Go up to the Project menu on the top of the screen.
Open it and click Add Form. You will now have two forms over in
the project window on the right side of your screen, Form1 and
Form2.
STEP #3: Double-click on Form2 in the project window. Put on a
command button on that form too. Now you should have two
forms with a button on each one.
STEP #4: Double-click on the button on Form2 and enter these
two simple lines of code (in red):
Private Sub Command1_Click()
Form1.Show
Form2.Hide
End Sub
 This code tells Form1 to appear and at the same time
tells Form2 to disappear.
STEP #5: Now double-click on Form1 over in the project window
on the right of the screen. When the form opens, double-click on
the command button you should have created in Step #1 and enter
this code (in red):
Private Sub Command1_Click()
Form2.Show
Form1.Hide
End Sub
 This code tells Form2 to appear and at the same time
tells Form1 to disappear.
STEP #6: Run your program. Form1 should open first. Click on the
command button. Form2 should appear. Then click the command
button on Form2. Form1 should re-appear.

You might also like