visual Basic 6 Task Sheets - Kelso High School Basic 6... · Visual Basic 6 Progamming task ......

27
1 Visual Basic 6 Progamming task sheets

Transcript of visual Basic 6 Task Sheets - Kelso High School Basic 6... · Visual Basic 6 Progamming task ......

1

Visual Basic 6

Progamming task sheets

2

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

3

Information Sheet 1: The Visual Basic Interface

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

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

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

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

This window shows where your program will appear on your screen

4

Information Sheet 2: The toolbar and Properties Window

If the toolbar disappears from your screen, look under the View menu and choose toolbox

Change the properties of an object here

5

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

6

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 Name Caption Event Result Form Scribble Scribble. Form_Load set up form so that it can be printed MouseMove causes a line to be drawn from previous point Command Button

cmdQuit Quit. Click exits from the program

Command Button

cmdPrint Print Click 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

7

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 meant to do happen without error. Usually, you would produce a printout of the screen to prove that it is working correctly. Here is an example of the screen output from this 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 instead 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

8

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 Name Caption Event Result Button cmdenter Enter Data click Ask for a number Button cmddisplay Display Data Click Display message in label Label lbldisplay 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.

9

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 Name Caption Event Result Form Adder Add 2 Numbers Form_Load set up form so that it can be printed Command Button cmdAdd Add Click to add numbers Command Button cmdQuit Quit. Click exits from the program Command Button cmdPrint Print Click prints the contents of the form on the

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

10

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

11

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 Name Caption Event Result Command Button cmdreal Real Click Input and print a real value Command Button cmdInteger Integer Click Input and print an integer value Command Button cmdstring String Click 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

12

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

13

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 Name Caption Button cmdloop Loop Button cmdquit Quit Picture Box picdisplay 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

14

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?

15

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 Name Caption Button cmdgetnumber How many Button cmdaverage Average Button cmdquit Quit Label lblresult 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

16

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)

17

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 Name Caption Button cmdenter Enter password Text box txtpassword Button cmdquit Quit Label lblresult 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

18

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

19

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 (Do…Loop 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 Name Caption Event Result Command

Button cmdStart Start Click 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(“That’s 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 Do…Loop 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 Do…Loop Until. You do not use the

counter when using the conditional loop.

20

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 doesn’t 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 Name Caption Button cmdgetnumber Input Number Label lblresult Button cmdquit 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

21

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 Description of Function Syntax of Function VAL Converts text to a number Number = val(txtinput)

INT Returns a whole number (it

always rounds down) Number = INT(RND * 10) + 1

SQR Square root of a number Number = Sqr(Number)

MOD Returns the remainder of a calculation.

Number = 5 MOD 2 (this would return the value 1).

ROUND Round a number up or down depending.

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).

22

Set up a VB form with these objects Object Name Caption Button cmdfunction Test Function Button cmdclear Clear Button cmdquit Quit Label lblresult Text box txtinput 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.

23

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 Name Caption Button cmdrandom Random Number Picture Picture1 Button cmdquit 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

24

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 Name Caption Button cmdcoin Toss Coin Picture Picture1 Button cmdquit 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

25

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 Name Caption Button cmdenter Enter data Picture Box Picture1 Button cmdname Print Name Button cmdquit 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

26

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 doesn’t 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 Name Caption Button cmdgetnumber Input Number Label lblresult Button cmdquit 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

27

Visual Basic Reference sheet: Data Types: Data Type Definition Examples String Any set of characters from the keyboard TD5 7EG Fred %$£9* Integer A number with no decimal point 3 978 -45 Real A number with a decimal point 1.56 -34.6 0.03 Boolean A variable which can be either true or false True False Array A list of items all of the same type Names(10) Values(20) Arithmetic Operators;: Logical Operators: Operator Symbol Example Add + counter = counter + 1 Subtract - total = total -1 Divide / Average = total / 5 Multiply * Score = score * 3 Power ^ Kilobyte = 2^10 Functions:

Operator Example AND IF answer is >=1 AND answer <= 10 OR IF response = “Y” OR response = “N” NOT IF Found NOT true

Function Description of Function Syntax of Function VAL Converts text to a number Number = val(txtinput)

INT Returns a whole number (it

always rounds down) Number = INT(RND * 10) + 1

SQR Square root of a number Number = Sqr(Number)

MOD Returns the remainder of a calculation.

Number = 5 MOD 2 (this would return the value 1).

ROUND Round a number up or down depending.

Number = ROUND(4.5)