Visual Basic 6
Visual Basic 6
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
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
Change the properties of an object here If the toolbar disappears from your screen, look under the View menu and choose toolbox
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
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)
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
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.
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.
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
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
Use the four example programs to explore how the four control structures work
12
Double click on the Quit button and add this code: End
13
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
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
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
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
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
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:
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:
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
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
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
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
25
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:
26
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)
27