You are on page 1of 27

Visual Basic 6 Progamming task sheets

Contents
Information Sheet 1: The Visual Basic Interface .............................................................................................. 3 Information Sheet 2: The toolbar and Properties Window................................................................................ 4 Information Sheet 3: Making your program readable ....................................................................................... 4 Information Sheet 3: Making your program readable ....................................................................................... 5 Example Sheet 1: Scribble program.................................................................................................................. 6 Example Sheet 2: Local variables ..................................................................................................................... 8 Example Sheet 3: Data Types ........................................................................................................................... 9 Example Sheet 4: More Data Types................................................................................................................ 11 Example Sheet 5: Control structures............................................................................................................... 12 Example Sheet 6: Loops.................................................................................................................................. 12 Example Sheet 6: Loops.................................................................................................................................. 13 Example Sheet 7: Loop and Count.................................................................................................................. 15 Example Sheet 8: IF Then Else ....................................................................................................................... 17 Example Sheet 9: Do Loop Until ................................................................................................................ 19 Example Sheet 10: Input Validation ............................................................................................................... 20 Example Sheet 11: Functions.......................................................................................................................... 21 Example Sheet 12: Random Numbers ............................................................................................................ 23 Example Sheet 13: Conditional Statements inside a loop ............................................................................... 24 Example Sheet 14: Arrays............................................................................................................................... 25 Example Sheet 15: More Input Validation...................................................................................................... 26 Visual Basic Reference sheet: ......................................................................................................................... 27

Information Sheet 1: The Visual Basic Interface

This is where you find tools to add buttons, text boxes, picture boxes, labels etc. to your program

This is where you can see which files your program will use

This window lets you see how the program will look on your screen when it is running

This is window is where you can change the properties of the objects you place on the form

This window shows where your program will appear on your screen

Information Sheet 2: The toolbar and Properties Window

Change the properties of an object here If the toolbar disappears from your screen, look under the View menu and choose toolbox

Information Sheet 3: Making your program readable


Internal Documentation: You can use the keyword Rem or just a single quote before comments in your programs. You should always give details of the Author, Date and Purpose of a program in the General Declarations section

You should include comments to explain how parts of a program work

Comments will always show as green in the Visual Basic code window

Meaningful names: Variables, Command buttons, Text boxes and Labels should always be given meaningful names. Variables should always be given names which describe the information they are storing

Example Sheet 1: Scribble program


Problem: Write a program to 'scribble' a line on the screen. As the mouse is moved, a line is drawn to follow the pointer.

Objects and Events


Object Form Command Button Command Button Name Scribble cmdQuit cmdPrint Caption Scribble. Quit. Print Event Form_Load MouseMove Click Click Result set up form so that it can be printed causes a line to be drawn from previous point exits from the program prints the contents of the form on the printer

Interface Design: You should sketch out a rough design for the appearance of your form showing the objects and their control names.

Algorithm: 1. Repeat 2. Move the mouse (MouseMove event) 3. Draw a line from the previous point to the current position 4. If print button is pressed then print form 5. Until the Quit button is pressed 6. End the program Add the following line to the Form_MouseMove procedure: Line -(X,Y)

Add this line to the Form_Load procedure 6

Scribble.AutoRedraw = True Add the following to the cmdQuit_Click procedure: End End is the keyword which causes a program to terminate. There can only be one use of the End keyword in a project. Add the following to the cmdPrint_Click procedure: PrintForm PrintForm is the keyword that will print everything displayed on a form. The title bar and border are not printed. Testing: When you test a program, you should make sure that all the things that it was to do happen without error. Usually, you would produce a printout of the screen prove that it is working correctly. Here is an example of the screen output from project: ` Challenge Change the program to draw a line when the mouse is clicked instead of moved. Hint: put the Line -(X,Y) code on the mouseup or mousedown procedure of the mouse_move one Can you add buttons to change the colour of the line to make a simple painting program? This code will change the foreground colour of a form to blue: Scribble.forecolor = VBblue Add a clear button as well the code to clear the form is cls meant to this

instead

Example Sheet 2: Local variables


Create a form with two buttons and a label. The buttons should be named cmdenter and cmddisplay The label should have no caption. Object Button Button Label Name cmdenter cmddisplay lbldisplay Caption Enter Data Display Data Event click Click Result Ask for a number Display message in label

Add the following code to the first button, cmdenter usernumber = Inputbox(please give me a number) Add the following code to the second button, cmddisplay Lbldisplay.caption =(the number you entered was + usernumber) Run the program. You will be asked to enter a number, but the result will not be as you might expect:

The problem is that the variable usernumber is not recognized by the cmddisplay button. It does not have scope throughout the project, so the cmdisplay button is unable to give it a value when it displays it in the label Add the following code to the general declarations section and then try the program again. Dim usernumber Now both buttons are able to see the usernumber variable and the program should work as expected.

Example Sheet 3: Data Types Problem:


Write a program to input two numbers, add them together and display the result.

Inputs:
Text boxes name txtNumber1 - text property initially a blank. name txtNumber2 - text property initially a blank.

Output:
Label name lblResult - caption property initially blank.

Object Form Command Button Command Button Command Button

Name Adder cmdAdd cmdQuit cmdPrint

Caption Add 2 Numbers Add Quit. Print

Event Form_Load Click Click Click

Result set up form so that it can be printed to add numbers exits from the program prints the contents of the form on the printer

Command Buttons:
Name CmdQuit cmdPrint Cmdadd Code end printform lblResult = txtNumber1 + txtNumber2

Problem 1 Test your program out. The result may not be what you expect. The two text boxes store the numbers entered as strings so when they are added together they are just joined the way two words would be To change them to numbers, we can use the Visual Basic function Val. Change the Cmdadd code to lblResult = Val(txtNumber1) + Val(txtNumber2) The numbers are now added together instead of jus joined. Problem 2 If you change either Number1 or Number2 in the form while the program is running, then the result displayed is no longer correct. The program should clear the value shown in the result as soon as any changes are made to the input text boxes. One of the events available for a text box is the Change event. Select the txtNumber1_change procedure and add the line: lblResult = "" Do the same for txtNumber2_Change. When either of these text boxes have a value that is changed, the value in LblResult is reset to show a blank line.

Challenge
Can you add additional buttons such as Subtract, Multiply etc. to your program to build a simple calculator

10

Example Sheet 4: More Data Types


Visual Basic uses a number of different data types. The variable name can be used to tell Visual Basic what type of information is to be stored in that variable # tells VB that the variable is a real number % tells VB that the variable is an integer $ tells VB that the variable is a string Create a form with three command buttons on it Object Command Button Command Button Command Button Name cmdreal cmdInteger cmdstring Caption Real Integer String Event Click Click Click Result Input and print a real value Input and print an integer value Input and print a string

Private Sub cmdreal_Click() Number# = Val(InputBox("Please give me a real number")) Print Number# End Sub Private Sub Cmdinteger_Click() Number% = Val(InputBox("Please give me an integer")) Print Number% End Sub Private Sub cmdstring_Click() letters$ = InputBox("Please give me a string") Print letters$ End Sub

11

Example Sheet 5: Control structures


Open the Programming Structures program from Core Programs, Computing, Programming. This program has examples of: A For-Next unconditional loop An If Then Else conditional statement A While Wend conditional loop A Dice Counter program using the first three structures to count how many times a 6 is thrown

Use the four example programs to explore how the four control structures work

12

Example Sheet 6: Loops


A loop in Visual Basic is a piece of code which makes something happen a set number of times Set up a VB form with two command buttons and a picture box. Give the objects the names and captions below.

Object Button Button Picture Box

Name cmdloop cmdquit picdisplay

Caption Loop Quit

Double click on the Quit button and add this code: End

Double click on the Loop button and add this code:


Dim counter

For counter = 1 to 10 Picdisplay.print Hello World


Next counter Test your program. Now try: Dim counter

For counter = 1 to 10 Picdisplay.print counter


Next counter

13

Change the code on the loop button to this Dim counter

For counter = 1 to 10 Picdisplay.print counter ; times 2 equals counter * 2


Next counter

You should see this when you run the program: Now change this program to display the 5 times table. Change the first line of the code to read: For counter = 1 to 10 step 2 Try the program now

Challenge 1 Change your program so that it prints your name 8 times in font sizes 5 to 40

Hints: You will need to use step to loop from 5 to 40 Change the properties of the form so that it uses the Ariel font You will need to change the fontsize property of the form inside the loop

Challenge 2 Can you set up a text box which you enter the text you want repeated in your loop?

14

Example Sheet 7: Loop and Count


A loop in Visual Basic is a piece of code which makes something happen a set number of times. We can use a loop to count up a set of values. In this case we are going to add up a set of numbers and calculate the average. Set up a VB form with three command buttons and a label Give the objects the names and captions below.

Object Button Button Button Label

Name cmdgetnumber cmdaverage cmdquit lblresult

Caption How many Average Quit

Double click on the Quit button and add this code: End

Double click on the cmdgetnumber button and add this code: Numbertoaverage = val ( inputbox (How many numbers do you want to find the average of?) )
NB Because this variable is needed by the other button in the program you will have to declare it in the General declarations section:

Dim numbertoaverage

15

Double click on the Average button and add this code: Dim total Total = 0 For counter = 1 to numbertoaverage Usernumber = inputbox (Please enter a number) Total = total + Usernumber Next counter Dim average Average = total / numbertoaverage Lblresult.caption = (The average of these numbers is+ str$(average))

Challenge: Alter this program to deal properly with letters type in instead of numbers. (Hint look at the code for numbertoaverage)

16

Example Sheet 8: IF Then Else


If Then Else statements can be used to test for a condition, with different outcomes depending on the result of the condition

Set up a VB form with two command buttons a text box and a label Give the objects the names and captions below. Object Button Text box Button Label Name cmdenter txtpassword cmdquit lblresult Caption Enter password Quit

Enter the following code on the cmdEnter button:

Dim password Password = computing If txtPassword.Text = Password Then LblResult = Valid password has been entered Else LblResult = Invalid password has been entered End if

17

Challenge: Add a clear button to your program Change the properties of the txtpassword text box so that it shows the password as stars instead of letters Often you are only allowed a certain number of tries before a password program locks you our Challenge: Using the same program, only allow the user to have three attempts at entering the password. If the user enters a password incorrectly three times, display an appropriate message in a message box and end the program. Hints: Declare a counter variable in General Declarations (Dim counter). This sets up Counter and gives it a value of zero You will need to add one to the counter every time an incorrect password is entered. You will also need to add another if statement that checks when the counter is equal to three. You will need to add the code for the message box inside this if statement.. The code for a message box is: MsgBox ( your message here The End command should also be inside this if statement ).

18

Example Sheet 9: Do Loop Until


When using a FOR-NEXT loop, the programmer specifies the number of times a particular section of code is to be repeated. However, if the programmer does not know the number of repetitions then a condition has to be set for the repetition to end. As an example, the password checker program, instead of using an IF-THEN-ELSE statement, we could use a conditional loop (DoLoop Until). The program would loop until the correct password is entered. This program will ask the user a question and will then prompt the user for an answer via an input box. The user will be required to supply an answer until they answer the question correctly. Object Command Button Name cmdStart Caption Start Event Click Result Question will be displayed.

1. Copy the form and REMEMBER to name the objects as shown. 2. Use the following code to get started: Dim correct_answer Dim user_answer correct_answer = 7 Do user_answer = InputBox(How many Harry Potter books are there?) Loop Until user_answer = correct_answer MsgBox(Thats correct!!) 3. Try and add more questions, a maximum of five. Hints: Below this code you will have to set the correct answer for the next question, create another DoLoop Until and display a message if the user guesses the correct answer. Challenge 1. Try and change your password checker program., instead of using an if-then-else statement, use a DoLoop Until. You do not use the counter when using the conditional loop. 19

Example Sheet 10: Input Validation


Input validation is where you only allow the user to type in certain numbers you may wish to limit the range of numbers they can type in so that their input doesnt cause the program to crash later on. If you are using Input Validation, you should always give a user friendly message when an error occurs. Set up a VB form with two command buttons Give the objects the names and captions below. Object Button Label Button Name cmdgetnumber lblresult cmdquit Caption Input Number Quit

Double click on the Quit button and add this code:

End Double click on the cmdgetnumber button and add this code: Do Value = Val (InputBox ("Please enter a number between 1 and 10") ) If (Value < 1) Or (Value > 10 ) Then MsgBox ("Sorry invalid input") Loop Until (Value >= 1) And (Value <= 10) Lblresult.Caption = "Your number was " & Value
This example uses a new type of loop a Do Loop Until loop. This is called a Conditional loop Challenge:

Alter this program to accept numbers between 1 and 100


Adapt your program to take in 10 numbers between 1 and 100 and print out the average 20

Example Sheet 11: Functions

A function is a piece of code built into Visual Basic, which carries out a specific operation. The function is called from within your procedure and returns a result to the procedure. A table of some number functions can be seen below:

Function VAL INT SQR MOD ROUND

Description of Function Converts text to a number Returns a whole number (it always rounds down) Square root of a number Returns the remainder of a calculation. Round a number up or down depending.

Syntax of Function Number = val(txtinput) Number = INT(RND * 10) + 1 Number = Sqr(Number) Number = 5 MOD 2 (this would return the value 1). Number = ROUND(4.5)

Note: When using the ROUND function, if the number is even with point five then the number will be rounded down. However, if the number is odd with point five then the number will be rounded up (VERY CONFUSING).

21

Set up a VB form with these objects

Object Button Button Button Label Text box

Name cmdfunction cmdclear cmdquit lblresult txtinput

Caption Test Function Clear Quit

Add this code to the cmdfunction button

Number = Val(txtinput) Lblresult = Int(Number)


Test your program then change the code to see what the other functions do

Challenge Create a form similar to the form opposite. When the user enters a number a message should be displayed, stating whether it is an even number or an odd number. Hints: 1. Use the MOD function. 2. You will also need to use an IF THEN ELSE statement. 3. If the result after using the MOD function is zero then it is an even number. 22

Example Sheet 12: Random Numbers


Random Numbers are difficult to produce using a computer because computers are not random devices. In Visual Basic random numbers are generated by the RND function which produces numbers between 0 and 1. The following code generates a random number between 1 and 10

Randomise Randomnumber = Int(RND * 10) +1 Print Randomnumber


Set up a VB form with two command buttons and a picture box Give the objects the names and captions below. Object Button Picture Button Name cmdrandom Picture1 cmdquit Caption Random Number Quit

Double click on the Quit button and add this code:

End Double click on the cmdrandom button and add this code:
Randomize For Counter = 1 To 10 randomnumber = Int(Rnd * 10) + 1 Picture1.Print randomnumber Next Challenge: Adapt this program to simulate the throwing of a dice ten times. Your program should add up how many sixes have been thrown and print this total at the bottom of the picture box 23

Example Sheet 13: Conditional Statements inside a loop


A conditional statement is one where the computer has to make a decision. You are going to write a program which simulates the tossing of a coin. With the computer using a random number generator to decide whether the throw is a head or a tail. In this example a 1 will signify a head and a 2 will signify a tail. This code will print a random number between 1 and 2

Randomise Randomnumber = Int(RND * 2) +1 Print Randomnumber A conditional statement use IF and THEN to make a decision. IF number = 1 then print Head
Set up a VB form with two command buttons and a picture box Give the objects the names and captions below. Object Button Picture Button Name cmdcoin Picture1 cmdquit Caption Toss Coin Quit

Double click on the cmdcoin button and add this code: Randomize For Counter = 1 To 10 randomnumber = Int(Rnd * 2) + 1 If randomnumber = 1 then picture1.print Head If randomnumber = 2 then picture1.print Tail Next counter
Challenge: Adapt this program to add up how many heads and tails have been thrown and print this total at the bottom of the picture box 24

Example Sheet 14: Arrays


Arrays are ways of storing a large amount of information of the same type Set up a VB form with two command buttons and a text box Give the objects the names and captions below. Object Button Picture Box Button Button Name cmdenter Picture1 cmdname cmdquit Caption Enter data Print Name Quit

In the general declarations section add this code:


Dim names(10)

Double click on the cmdenter button and add this code:


For counter = 1 to 10 Inputname= inputbox(Please enter a name) Names(counter) = inputname Next counter

Double click on the cmdname button and add this code:


Inputnumber= inputbox(Please enter a number between 1 and 10) Picture1.print Name number ; inputnumber ; is ; names(inputnumber) Challenge: Adapt this program to check that only numbers between 1 and 10 can be entered (remember how you did this on validation sheet 8

25

Example Sheet 15: More Input Validation


Input validation is where you only allow the user to type in certain numbers you may wish to limit the range of numbers they can type in so that their input doesnt cause the program to crash later on. You may also wish to limit the type of number they type in. If you are using Input Validation, you should always give a user friendly message when an error occurs. Set up a VB form with two command buttons Give the objects the names and captions below. Object Button Label Button Name cmdgetnumber lblresult cmdquit Caption Input Number Quit

Double click on the cmdgetnumber button and add this code: Do Value = Val (InputBox ("Please enter a whole number between 1 and 10") ) If (Value < 1) Or (Value > 10 ) Or ( int (value) <> value) Then MsgBox ("Sorry invalid input") Loop Until (Value >= 1) And (Value <= 10) And ( int (value) = value) Lblresult.Caption = "Your number was " & Value
Challenge:

Alter this program to only accept the letters Y or y or N or n

26

Visual Basic Reference sheet:


Data Types: Data Type String Integer Real Boolean Array Definition Any set of characters from the keyboard A number with no decimal point A number with a decimal point A variable which can be either true or false A list of items all of the same type Examples TD5 7EG Fred %$9* 3 978 -45 1.56 -34.6 0.03 True False Names(10) Values(20) Logical Operators: Example counter = counter + 1 total = total -1 Average = total / 5 Score = score * 3 Kilobyte = 2^10 Operator AND OR NOT Example IF answer is >=1 AND answer <= 10 IF response = Y OR response = N IF Found NOT true

Arithmetic Operators;: Operator Add Subtract Divide Multiply Power Functions: Function VAL INT SQR MOD ROUND Description of Function Converts text to a number Returns a whole number (it always rounds down) Square root of a number Symbol + / * ^

Syntax of Function Number = val(txtinput) Number = INT(RND * 10) + 1 Number = Sqr(Number) Number = 5 MOD 2 (this would return the value 1). Number = ROUND(4.5)

Returns the remainder of a calculation. Round a number up or down depending.

27

You might also like