manual vb 6.0
TRANSCRIPT
1
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
A Brief Description of Visual Basic
VISUAL BASIC
Is a high level programming language evolved from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. It is a fairly easy programming language to learn. The codes look a bit like English Language. Different software companies produced different version of BASIC, such as Microsoft QBASIC, QUICKBASIC, GWBASIC, IBM BASICA and so on.
What is Visual Basic?
Visual Basic is a tool that allows you to develop Windows (Graphical User Interface – GUI) applications. The applications have a familiar appearance to the user. Visual Basic is event-driven, meaning code remains idle until called upon to respond to some event (button pressing, menu selection, …) Visual Basic is governed by an event processor. Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (event procedure) is executed. Program control is then returned to the event processor.
Some features of Visual Basic
• Full set of objects – you draw the application• Lots of icons and pictures for your use• Response to mouse and keyboard actions• Clipboard and printer access• Full array of mathematical, string handling and graphics functions.• Can handle fixed and dynamic variable and control arrays• Sequential and random access file support• Useful debugger and error-handling facilities• Powerful database access tools• ActiveX support• Package & Deployment Wizard makes distributing your applications simple
Structure of Visual Basic Application
PLP – College of Computer Studies - rct- 6/‘06
Event?
Basic Code Basic Code Basic Code
Event processor
Event procedure
2
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesProject (.VBP, .MAK)
Visual Basic Start-up Dialog Box
On start up, Visual Basic 6.0 will display the following dialog box as shown in figure 1.1. You can choose to:
Start a new project Open an existing project Select a list of recently opened programs.
Project A project is a collection of files that make up your application. There are various types of
applications we could create; however, we shall concentrate on creating Standard EXE programs (EXE means executable program).
Note: By clicking on the Standard EXE icon to go into the actual VB programming
environment.
Figure 1: The Visual Basic Start-up Dialog Box
PLP – College of Computer Studies - rct- 6/‘06
Form 1 (.FRM)
Control 1
Control 2
Control 3
Form 2 (.FRM)
Control 1
Control 2
Control 3
Form 3 (.FRM)
Control 1
Control 2
Control 3
Module 1 (.BAS)
3
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
The Visual Basic Environment
Figure 2: The Visual Basic Environment
The Visual Basic Environment consists of the:
• A Blank Form for you to design your application's interface. • The Project window which displays the files that are created in your application. • The Properties window which displays the properties of various controls and objects that are
created in your applications.
Application (Project) is making up of:
• Forms – Windows that you create for user interface.• Controls – Graphical features drawn on Forms to allows user interaction (text boxes, labels,
scroll bars, command button, etc.) (Forms and Controls are objects).• Properties – Every characteristics of a Form or control is specified by a property. Example
properties include names, captions, size, color, position and contents. Visual Basic applies default properties. You can change properties at design time or run time.
• Methods – Built-in procedure that can be invoked to impart some action to a particular object.• Event Procedures – Code related to some object. This is the code that is executed when a
certain events occurs.• General Procedure – Code not related to objects. This code must be invoked by the application.
PLP – College of Computer Studies - rct- 6/‘06
4
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
• Modules – Collection of general procedures, variable declarations and constant definitions used by application.
Steps in Developing ApplicationThere are three primary steps involved in building a Visual Basic application:• Draw the user interface• Assign properties to controls• Attach code to controls
Drawing the User interface and Setting PropertiesVisual Basic operates in three modes.• Design mode – used to build application• Run mode – used to run the application• Break mode – application halted and debugger is available.
Six windows appear when you start Visual Basic.
The Main Window consists of the title bar, menu bar, and toolbar. The Title bar indicates the project name, the current Visual Basic operating mode, and the current Form. The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menus options. The main window also shows the location of the current Form relative to the upper left corner of the screen (measured in twips) and the width and length of the current Form.
The Form Window is central to developing Visual Basic applications. It is where you draw your application. (see figure 3)
Figure 3: Visual Basic Form Window
Note:
The most prominent element of the Visual Basic program development environment is the blank Form that is displayed in the middle of the screen. A Visual Basic Form Window is a window in which you design the user interface for your application
PLP – College of Computer Studies - rct- 6/‘06
5
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Adding controls to a Form:There are two ways to place a control on a Form:• Double – clicking• Drawing
The Toolbox is the selection menu for controls used in your application
Figure 4: Toolbox Form Controls
PLP – College of Computer Studies - rct- 6/‘06
Pointer
Label
Frame
Check Box
Combo Box
Horizontal Scroll Bar
Timer
Directory List Box
Shapes
Image Box
Object Linking Embedding
Picture Box
Text Box
Command Button
Option Button
List Box
Vertical Scroll Bar
Drive List Box
File List Box
Lines
Data Control
6
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesCommon Object/Controls and Their Naming Conventions:
Object Type Prefix Example DescriptionForm frm frmCalculatorProgra
mA window or dialog box that makes up part of an applications user interface
Picture Box pic picHappyFace A container that can display graphicsLabel lbl lblEnterName Displays text that the user cannot directly
modify at Run time.Text Box txt txtEnterName Displays text that the user can modify at Run
TimeFrame fra frmPickOptions A container that groups other controls such as
radio buttons or check boxes.Command Button
cmd cmdEndProgram Responds to a user click to trigger an event
Check Box chk chkPickFeatures Displays a check mark or an x to indicate the current state of a True/False option and responds to a user click to toggle the choice.
Option Button
opt optPaymentChoice An option button can be turned off or on by clicking the option button with the mouse. This control is typically used to enable the user to select from mutually exclusive options.
Combo Box cbo cboColorChoice Combines the features of a text box and list box. The user can specify data by typing it or by selecting a value from a list.
List Box lst lstTravelDestination Displays a list of values from which the user can select
Horizontal Scroll Bar
hsb hsbVolumeControl Provides a visual mechanism for a user to easily navigate through large amount of inFormation. Can also provide an analog representation of a current position
Vertical Scroll Bar
vsb vsbTrebleControl Same as a horizontal scroll bar, only it is displayed vertically.
Timer tmr tmrDelay Triggers an event when a specified time period elapses.
Drive List Box
drv drvHardDiskContent Provides a list of available disk drives and enables the user to select one.
Directory List Box
dir dirTree Provides a list drive paths and directories, enabling the user to select one
File List Box fil filProgramFiles Provides a list of files, enabling the user to select one.
Shape shp shpCircle A two-dimensional tool for drawing shapes.Line lin linBorder A two-dimensional tool for drawing straight
lines.Image img imgClouds Similar to the Picture Box, but easier to use, it
can display graphic images.Data dat datEmployeeRecords Support database compatibility with programs
such as Microsoft Access.OLE ole oleSpreadsheet Provides a data link with an Object Linking and
Embedding compliant application
PLP – College of Computer Studies - rct- 6/‘06
7
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Handling some of the common controls
The Text Box
The text box is the standard control that is used to receive input from the user as well as to display the output.
Note: It can handle string (text) and numeric data but not images or pictures. String in a text box can be converted to a numeric data by using the function Val(text).
Example:
In this program, two text boxes are inserted into the form together with a few labels. The two text boxes are used to accept inputs from the user and one of the labels will be used to display the sum of two numbers that are entered into the two text boxes. Besides, a command button is also programmed to calculate the sum of the two numbers using the plus operator. The program use creates a variable sum to accept the summation of values from text box 1 and text box 2.The procedure to calculate and to display the output on the label is shown below.
Figure 5: Sample Form Layout/Interface
`Program Listing 1: Example of Text Box Controls
Private Sub Command1_Click()‘To add the values in text box 1 and text box 2Sum = Val(Text1.Text) + Val(Text2.Text)‘To display the answer on label 1Label1.Caption = Sum
End Sub
PLP – College of Computer Studies - rct- 6/‘06
8
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
The Label
The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label.Caption, it can display text and numeric data.
Note: You can change its caption in the properties window and also at runtime. Please refer to
Program Listing 1 and Figure 5 for the usage of label.
The Command Button
The command button is a very important control as it is used to execute commands. It displays an illusion that the button is pressed when the user click on it. The most common event associated with the command button is the Click event, and the syntax for the procedure is
Private Sub Command1_Click () StatementsEnd Sub
The Picture Box
The Picture Box is one of the controls that used to handle graphics. You can load a picture at design phase by clicking on the picture item in the properties window and select the picture from the selected folder. You can also load the picture at runtime using the LoadPicture method.
Example: the statement will load the picture grape.gif into the picture box.
Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
Note: The image in the picture box is not resizable.
The Image Box
The Image Box is another control that handles images and pictures. It functions almost identically to the picture box. However, there is one major difference, the image in an Image Box is stretchable, which means it can be resized. This feature is not available in the Picture Box. Similar to the Picture Box, it can also use the LoadPicture method to load the picture.
Example: the statement loads the picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
PLP – College of Computer Studies - rct- 6/‘06
9
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
The List Box
The function of the List Box is to present a list of items where the user can click and select the items from the list. In order to add items to the list, we can use the AddItem method. For example, if you wish to add a number of items to list box 1, you can key in the following statements
Example:Private Sub Form_Load ( )
List1.AddItem “Lesson1”List1.AddItem “Lesson2”List1.AddItem “Lesson3”List1.AddItem “Lesson4”
End Sub
Note: The items in the list box can be identified by the ListIndex property, the value of
the ListIndex for the first item is 0, the second item has a ListIndex 1, and the second item has a ListIndex 2 and so on
The Combo Box
The function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method. For example, if you wish to add a number of items to Combo box 1, you can key in the following statements
Example:Private Sub Form_Load ( )
Combo1.AddItem “Item1”Combo1.AddItem “Item2”Combo1.AddItem “Item3”Combo1.AddItem “Item4”
End Sub
The Check Box
The Check Box control lets the user to select or unselect an option. When the Check Box is checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can include the statements Check1.Value=1 to mark the Check Box and Check1.Value=0 unmark the Check Box, and use them to initiate certain actions. For example, the program will change the background color of the form to red when the check box is unchecked and it will change to blue when the check box is checked.
Note:
PLP – College of Computer Studies - rct- 6/‘06
10
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
You will learn about the conditional statement If….Then….Elesif in later lesson. VbRed and vbBlue are color constants and BackColor is the background color property of the form.
Example:
Private Sub Check1_Click ()If Check1.Value = 0 Then Form1.BackColor = vbRedElseIf Check1.Value = 1 Then Form1.BackColor = vbBlueEnd If
End Sub
The Option Box
The Option Box control also lets the user selects one of the choices. However, two or more Option Boxes must work together because as one of the Option Boxes is selected, the other Option Boxes will be unselected. In fact, only one Option Box can be selected at one time. When an option box is selected, its value is set to “True” and when it is unselected; its value is set to “False”. In the following example, the shape control is placed in the form together with six Option Boxes. When the user clicks on different option boxes, different shapes will appear. The values of the shape control are 0, 1, and 2,3,4 which will make it appear as a rectangle, a square, an oval shape, and a rounded square respectively.
Example:Private Sub Option1_Click ( ) Shape1.Shape = 0End Sub
Private Sub Option2_Click() Shape1.Shape = 1End Sub
Private Sub Option3_Click() Shape1.Shape = 2End Sub
Private Sub Option4_Click() Shape1.Shape = 3End Sub
Private Sub Option5_Click() Shape1.Shape = 4End Sub
The Drive List Box
PLP – College of Computer Studies - rct- 6/‘06
11
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
The Drive ListBox is used to display a list of drives available in your computer. When you place this control into the form and run the program, you will be able to select different drives from your computer as shown in Figure 6.
Figure 6: The Drive List Box
The Directory List Box
The Directory List Box is used to display the list of directories or folders in a selected drive. When you place this control into the form and run the program, you will be able to select different directories from a selected drive in your computer as shown in Figure 7.
Figure 7: The Directory List Box The Properties Window is used to establish initial property values for objects. The drop-down
box at the top of the window lists all objects in the current Form. Two views are available;
PLP – College of Computer Studies - rct- 6/‘06
Object Box
Properties List
Setting Box
12
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Alphabetic and Categorized. Under this box are the available properties for the currently selected object.
Figure 8: Properties Window
The Form Layout Window shows where (upon program execution) your Form will be displayed relative to your monitor’s screen.
Figure 9: Form Layout Window
The Project Window displays a list of all Forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window.
Figure 10: Project Window
Building a Visual Basic ApplicationPLP – College of Computer Studies - rct- 6/‘06
Properties Window Title Bar
View Object
View Code Toggle Folders
13
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Creating Your First Application
Figure 11: Source Code Window
Figure 12: List of Objects
Figure 13: List of ProceduresWriting Visual Basic Code
PLP – College of Computer Studies - rct- 6/‘06
14
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Code Window• Visual Basic Window that you open when you want to type VB code into your program or
view the program statements already in your program. It is also known as the Code Editor Window. It contains an:o Object box – performs the same function as the Object box in the Properties window;
both allow you to choose either the Form or one of the controls on the Form. You can also use the Object Box to verify the name of a control while you are writing instruction in the Code Window
o Procedure box – list the event procedures to which the selected object is capable of responding Input box
Saving Project and Form/s
To save the Project & Form:1. Click <File> <Save Project> OR
Click <File> <Save Project As> ORClick Save Button
2. Then, displayed Save File As dialog box
3. Type the Form name(follow the Form filename format )ex: PEFRM01RICHARDGWAPO
Note: Before typing the Form name
makes sure that the Save File As dialog box (as shown besides) is displayed in your screen.
4. Click Save button5. Then, displayed Save Project As dialog box6. Type the project name (follow the project Format filename) ex:
PEPJT01RICHARDGWAPO
Note: Before typing the project name
makes sure that the Save Project As dialog box (as shown besides) is displayed in your screen.
7. Click Save button
Note: To RUN/EXECUTE the program/application Click on Run menu then, click Start - OR - Press F5 function key -
OR - Click Start button
PLP – College of Computer Studies - rct- 6/‘06
15
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
To TERMINATE execution mode (to go back to Form Window) Click on End button
PLP – College of Computer Studies - rct- 6/‘06
16
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesName : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #1: Adding several controls to Form WindowProject Name : PEPJT01<FirstNameLastName> Example: PEPJT01RichardGwapoForm Name : PE01FRM01<FirstNameLastName> Example: PE01FRM01RichardGwapo
Steps:1. Launch Visual Basic application/program;
Displays New Project as shown (see figure 1)
Be sure that Standard EXE is being selected2. Click Open button
Then, displays Form Window as shown below (see figure 2)
3. Add the following controls as shown (see figure 3) Labels Text Box Combo Box List Box Frame (Course & Subjects
enrolled) Command Button
4. Click Save button or File Save Project or File Save Project As Follow the project name and
Form name Format
5. Apply necessary enhancement:Font, Font Size, Font Color,Changing Caption etc.
PLP – College of Computer Studies - rct- 6/‘06
Figure 1: New Project Window
Figure 2: Form Window
Figure 3: Sample Form Interface
17
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #2: Inserting/Adding Form in the existing project & using MsgBox Project Name : PEPJT01<FirstNameLastName> Example: PEPJT01RichardGwapoForm Name : PE02FRM02<FirstNameLastName> Example: PE02FRM02RichardGwapo
Steps:1. Retrieve/Open your PEPJT01 (Practice
Exercise project 1) 2. Click <Project> menu then select <Add
Form> New Form will be added in your existing project (see Figure 1)
3. Add 2 controls/objects in your new Form as shown (see Figure 2)
4. Change Properties:Form = Caption: Using MsgBox Label1 = Name: lblMsg
Caption: Message goes hereCommand1 = Name: cmdTest
Caption: Test (see Figure 3)
5. Apply codes to you’re application: Click <View> menu then <Code> OR select View Code button from
project explorer window OR double click the Test Button Then, displayed the Code Window (see Figure 4)
6. In the Event combo box (General) select cmdTest and in the Procedure combo box (Declarations) select click (see Figure 5) Note: The default event for a CommandButton Object is Click (see Figure 6)
7. Inside the procedure Type the source code as shown: (see Figure 7)
PLP – College of Computer Studies - rct- 6/‘06
Figure 1: New Form in Project Explorer Window
Figure 2: Form2 with Label1 & Command1 controls
Figure 3: Modified Form2
Figure 4: Code Window of Form2
Object Procedure
Figure 5: Object cmdTest
Figure 6: Code Window for cmdTest Object with Procedure click
Figure 7: Sample procedure/code/command/message of cmdTest Object
18
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
PLP – College of Computer Studies - rct- 6/‘06
19
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
lblMsg is the object where you want to place the message and Caption is its property that holds the text to be displayed.
Note: - In object programming, the access to method and properties is done by joining the name of the object and the property (or method) with a dot.
- The message is enclosed with double quotation marks (“ “) because the text is a string constant.
Note: Before running the program you need to change the project properties to run Form2 otherwise, Form1 will always be the Form to be executed.o Click <Project> menu then click <Project Properties> then, displays the Project Properties dialog
box/window (see Figure 8)o Select Form2 (or the Form that you
wants to run/execute) from the Startup objects. Then, click OK button
8. Try to run the program and see the output : (see Figure 9)
9. Creating event/procedure for the object Form. Click the View Code button or simply Double click the Form to work on with the code window (see
Figure 10)
Notice that the default event for Form is not Click but Load. Select Click and type the procedure/code as shown (see Figure 11)
10. Save and Run the program to test the output.
11. To add Message Box command: Modify cmdTest procedure
and add this line of command (see Figure 12)
PLP – College of Computer Studies - rct- 6/‘06
Figure 9: Output of Form2
Figure10: Code Window for Form object
Figure 11: Event for Form object
Figure 8: Project Properties Window
20
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesMsgBox – Text Message To be displayed.
12. Save and run the program/application to test the output
Try to enhance the Form by changing some object properties.
PLP – College of Computer Studies - rct- 6/‘06
21
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Operators in Visual Basic
In order to compute inputs from users and to generate results, we need to use various mathematical operators. In Visual Basic, except for + and -, the symbols for the operators are different from normal mathematical operators.
Arithmetic Operators:
Operator Mathematical function Example^ Exponential 2^4=16* Multiplication 4*3=12/ Division 12/4=3
Mod Modulus(return the remainder from an integer division)
15 Mod 4=3
\ Integer Division(discards the decimal places)
19\4=4
+ or & String concatenation "Visual"&"Basic"="Visual Basic"
Program Listing 2: Example of Mathematical/Arithmetic Operators 1Dim firstName As StringDim secondName As StringDim yourName As String Private Sub Command1_Click() firstName = Text1.Text
secondName = Text2.TextyourName = secondName + " " + firstName
Label1.Caption = yourNameEnd Sub
In this example Program Listing 3, three variables are declared as string. For variables firstName
and secondName will receive their data from the user’s input into textbox1 and textbox2, and the variable yourName will be assigned the data by combining the first two variables. Finally, yourName is displayed on Label1.
Type Conversions
Values are classified as either String or Numeric. Both values can be manipulated separately. For example, we can concatenate two strings or add two numbers but we cannot add or concatenate a string and a number.
In many occasions, we need to convert a string format to numeric format for computation and a numeric format to string format for manipulation. To do this, we can use the STR( ) and VAL( ) functions.
STR( ) – converts a number to stringVAL( ) – converts a string to number
PLP – College of Computer Studies - rct- 6/‘06
22
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesExamples:
Let X = “Hello! ” A = 5 C = “20”Y = “How old are you ” B = 10 AGE = 25
Z = X + “How are you” SUM = A + B
Output of Z Output of SUM
Z= Y + STR(AGE) D = A + B + VAL(C)
Output of Z Output of D
Program Listing 3: Example of Mathematical/Arithmetic Operators 2Dim number1, number2, number3 as IntegerDim total, average as variantPrivate sub Form_Click( )
number1=val(Text1.Text) number2=val(Text2.Text) number3= val(Text3.Text)
Total=number1+number2+number3Average=Total/5 Label1.Caption=TotalLabel2.Caption=Average
End Sub
In the Program Listing 4, three variables are declared as integer and two variables are declared as variant. Variant means the variable can hold any numeric data type. The program computes the total and average of the three numbers that are entered into three text boxes.
PLP – College of Computer Studies - rct- 6/‘06
Hello! How are you
How old are you 25
15
35
23
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #3: Using VAL( ) and Mathematical OperatorsProject Name : PEPJT01<FirstNameLastName> Example: PEPJT01RichardGwapoForm Name : PE03FRM03<FirstNameLastName> Example: PE03FRM03RichardGwapo
Steps:1. Retrieve/Open your PEPJT01 (Practice Exercise Project 1) 2. Click <Project> menu then select <Add Form>3. Sample Form Layout/Interface: (see Figure 1)4. Add the following objects/controls as shown5. Change properties:
Form = Caption: Mathematical Operations Text1 = Name: txtMyName Text2 = Name: txtYourName Text3 = Name: txtMyAge Text4 = Name: txtYourAge Label1 = Name: lblOurName Label2 = Name: lblSumAge Command1 = Name: cmdOurName Command2 = Name: cmdSumAge
Note: Please type the given names as it is to avoid errors in program codes.
6. Double Click NAME button then, type the following line of codes.
cmdOurName Event:
Private Sub cmdOurName_Click()' Displaying "Welcome MyName and YourName value"lblOurName.Caption = "Welcome! " + txtMyName.Text + " " + txtYourName.Text
End Sub
7. Double Click SUM button then, type the following line of codes.
cmdSumAge Event:
Private Sub cmdSumAge_Click()' Displaying MyAge and YourAge
lblSumAge.Caption = Val(txtMyAge.Text) + Val(txtYourAge.Text)
End Sub
8. Save and run the program to test the output (see Figure 2)9. Apply necessary enhancement to your Form (optional)
Single Quotation ( ‘ )
PLP – College of Computer Studies - rct- 6/‘06
Figure 1: Sample Layout/Interface
24
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Single Quotation ( ‘) serves as a comment or remark
PLP – College of Computer Studies - rct- 6/‘06
Figure 2: Sample Run
25
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #1: Project Name : MPPJT01<FirstNameLastName> Example: MPPJT01RichardGwapoForm Name : MP01FRM01<FirstNameLastName> Example: MP01FRM01RichardGwapo
PROJECT #1q:FORM #1: SAMPLE FORM LAYOUT/INTERFACE: SAMPLE OUTPUT:
Objects/Controls Properties:
Form: Caption: Using Mathematical Operators]
Label: Text Box: Argument 1 1. Name: txtArg1 Alignment: Right Argument 2 2. Name: txtArg2 Alignment: Right Sum (+) 3. Name: txtSum Alignment: Right Enabled: False Difference (–) 4. Name: txtDiff Alignment: Right Enabled: False Product (*) 5. Name: txtProd Alignment: Right Enabled: False Quotient (/) 6. Name: txtQuo Alignment: Right Enabled: False
Command Button: Caption: Result Name: cmdResult
PLP – College of Computer Studies - rct- 6/‘06
1) 2)
3) 4) 5) 6)
26
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #2: Project Name : MPPJT01<FirstNameLastName> Example: MPPJT01RichardGwapoForm Name : MP02FRM02<FirstNameLastName> Example: MP02FRM02RichardGwapo
PROJECT #1:FORM #2: SAMPLE FORM LAYOUT
Form: Caption: SIMPLE CALCULATOR ContolBox: False
Note: If ControlBox is set to False the contol menu box will be removed along with the minimize, maximize and close button (see the sample output below)
Text Box:1. Name: txtArg12. Name: txtArg23. Name: txtResult Enabled: False
Command Buttons:
#’s Name Caption Description4 cmdClear &Clear To clear all entries (text box)5 cmdAdd &Add To add two numbers6 cmdSubract &Subtract To subtract two numbers7 cmdMultiply &Multiply To multiply two numbers8 cmdDivide &Divide To divide two numbers9 cmdExit E&xit To end/close the program
SAMPLE OUTPUT:Note: You can also use the following keys
Alt + C – Clear Alt + A – AddAlt + M – MultiplyAlt + S – SubtractAlt + D – DivideAlt + X – Exit
***** The effect of & symbol is to have a short-cut key for the following command button objects stated above.
Example: You type Effect: &Clear
Clear
PLP – College of Computer Studies - rct- 6/‘06
1)
2)
3)
5)
6)
4)
9)7)
8)
27
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
E&xit Exit
PLP – College of Computer Studies - rct- 6/‘06
28
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Visual Basic Data Types
There are many types of data we come across in our daily life. For example, we need to handle data such as names, addresses, money, date, stock quotes, statistics and etc everyday. Similarly in Visual Basic, we are also going to deal with these kinds of data. However, to be more systematic,
VB divides data into different types.
Numeric Data Numeric data are data that consists of numbers, which can be computed mathematically
with various standard operators such as add, minus, multiply, divide and so on. In Visual Basic, the numeric data are divided into 7 types.
Numeric Data Types
Type Storage Range of ValuesByte 1 byte 0 to 255Integer 2 bytes -32,768 to 32,767Long 4 bytes -2,147,483,648 to 2,147,483,648Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values.Double 8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for negative values
4.94065645841247E-324 to 1.79769313486232e+308 for positive values.Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
+/- 7.9228162514264337593543950335 (28 decimal places).
Non-numeric Data Types
Data Type Storage RangeString(fixed length) Length of string 1 to 65,400 charactersString(variable length) Length + 10 bytes 0 to 2 billion charactersDate 8 bytes January 1, 100 to December 31, 9999Boolean 2 bytes True or FalseObject 4 bytes Any embedded objectVariant(numeric) 16 bytes Any value as large as DoubleVariant(text) Length+22 bytes Same as variable-length string
Suffixes for Literals
Literals are values that you assign to a data. In some cases, we need to add a suffix behind a literal so that VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double type data.
PLP – College of Computer Studies - rct- 6/‘06
29
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Suffix Data Type& Long! Single# Double@ Currency
In addition, we need to enclose string literals within two quotations and date and time literals within two # sign. Strings can contain any characters, including numbers.
Examples: memberName="Turban, John." TelNumber="1800-900-888-777" LastDay=#31-Dec-00# ExpTime=#12:00 am#
Declaring Variables and Constant
Variables are used by Visual Basic to hold information needed by your application. Variable is a temporary repository of information. Usually, these information are stored because they expect to be processed or be used as an element in a process.
Two classifications of variable name: Numeric String
Rules used in naming variables: Not more than 40 characters The first character must be a letter followed by either another letters, numbers and underscore
( _ ) They are not case sensitive which makes a lowercase variable the same as that written in its
uppercase Format. You cannot use a reserve word (word needed by Visual Basic)
Scoping of variables:
Variables can be Local to the procedure or Local to the whole Form. Local variables to a procedure are declared at the start of a procedure and can be used only in that procedure. Local variables to the whole Form, on the other hand, can be defined at the Declaration section of the General object found in the code window. See figure below.
Variables that are Local to the procedure are declared after DIM reserve word while variables that are Local to the Form are declared either by using DIM or PRIVATE reserve words. See figure 12.
PLP – College of Computer Studies - rct- 6/‘06
30
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Figure 12: Variable Declaration
Managing Variables
Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the mail boxes. In term of VB, variables are areas allocated by the computer memory to hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic, you have to follow a set of rules.
Constant
Refers to fixed values. Like variable, constants can be Local for a specific procedure, Local for the entire Form, Private for a Module, and Public for the whole project.
The reserve word Const is use to declare a constant see Figure 13.
Figure 13: Constant Variable Declarations
Examples: Valid and Invalid Variable Names
Valid Name Invalid NameMy_Variable My.VariableThisDate 7DayLong_Name_Can_beUSE Mine&Yours *& is not acceptable
PLP – College of Computer Studies - rct- 6/‘06
Loc al Variables
31
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Visual Basic Symbolic Constants
Many times Visual Basic, functions and objects require data arguments that affect their operation and return values you want to read and interpret. These arguments and values are constant numerical data and difficult to interpret based on just the numerical value. To make these constants more understandable, Visual Basic assigns names to the most widely used values – these are called symbolic constants.
Example: frmExample.BackColor = 0XFF0000frmExample.BackColor = vbBlue
Declaring Variables
In Visual Basic, one needs to declare the variables before using them by assigning names and data types. They are normally declared in the general section of the codes' windows using the Dim statement.
Format: Dim variableNmae as DataType
Example:Dim password As String Dim yourName As String Dim firstnum As Integer Dim secondnum As Integer Dim total As Integer Dim doDate As Date
Note:
You may also combine them in one line , separating each variable with a comma, as follows:
Example:Dim password As String, yourName As String, firstnum As Integer,.............
If data type is not specified, VB will automatically declare the variable as a Variant. For string declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as example 5.1 above. However, for the fixed-length string, you have to use the
Format: Dim VariableName as String * n,
(where n defines the number of characters the string can hold.)Example:
Dim yourName as String * 10 ‘yourName can holds no more than 10 Characters.
PLP – College of Computer Studies - rct- 6/‘06
32
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Working with Variables
Assigning Values to Variables
After declaring various variables using the Dim statements, we can assign values to those variables. The general format of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and etc.
Examples:firstNumber=100 secondNumber=firstNumber-99 userName="John Lyan" userpass.Text = password Label1.Visible = True Command1.Visible = false Label4.Caption = textbox1.Text ThirdNumber = Val(usernum1.Text) total = firstNumber + secondNumber+ThirdNumber
Visual Basic Functions
Visual Basic offers a rich assortment of built-in functions. The on-line help utility will give you information on any or all of these functions and their use:
Function Value ReturnedAbs Absolute value of a numberAsc ASCII or ANSI code of a characterChr Character corresponding to a given ASCII or ANSI codeCos Cosine of an angleDate Current date as a text stringFormat Date or number converted to a text stringLeft Selected left side of a text stringLen Number of characters in a text stringMid Selected portion of a text stringNow Current time and dateRight Selected right end a text stringRnd Random numberSin Sine of an angleSqr Square root of a numberStr Number converted to a text stringTime Current time as a text stringTimer Number of seconds elapsed since midnightVal Numeric value of a given text string.
PLP – College of Computer Studies - rct- 6/‘06
33
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Rnd Function
In writing games and learning software, we use the Rnd funtion to introduce randomess. This ensures different results each time you try a program. The Visual Basic function Rnd returns a single precision, random numbers between 0 and 1 (actually greater than or equal to 0 and less than 1). To produce random integers (I) between Imin and Imax, use the formula:
I = Int(Imax – Imin + 1) * Rnd) + Imin
The random number generator in Visual Basic must be seeded. A seed value initializes the generator. The Randomize statement is used to do this:
Randomize Seed If you use the same Seed each time your run your application, the same sequence of random
numbers will be generated. To ensure you get different numbers everytime you use your application (preferred for games), use the Timer funtion to seed the generator:
Randomize Timer
Note:Place Randomize Timer statement in the Form_Load event procedure
Examples:
1. To roll a six-sided die, the number of spots would be computed using:
Answer:NumberSpots = Int(6 * Rnd) + 1
2. To randomly choose a number between 100 and 200, use:
Answer:Number = Int(100 * Rnd) + 100
PLP – College of Computer Studies - rct- 6/‘06
34
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #4: Stopwatch Application (Using several Visual Basic Functions)Project Name : PEPJT02<FirstNameLastName> Example: PEPJT02RichardGwapoForm Name : PE04FRM01<FirstNameLastName> Example: PE04FRM01RichardGwapo
Project 2 / Form 1Steps:
1. Create a New Project2. Add the following controls as shown (see Figure 1) (place
three command buttons and six labels on the form) 3. Set Properties of the form, three buttons and six labels:
Form1:BoarderStyle 1-Fixed SingleCaption Stopwatch ApplicationName frmStopWatch
Command1:Caption &Start TimingName cmdStart
Command2:Caption &Start TimingName cmdEnd
Command3:Caption E&xitName cmdExit
Label1:Caption Start Time
Label2:Caption End Time
Label3:Caption Elapsed Time
Label4:BoarderStyle 1-Fixed SingleCaption [Blank]Name lblStart
Label5:BoarderStyle 1-Fixed SingleCaption [Blank]Name lblEnd
Label6:BoarderStyle 1-Fixed SingleCaption [Blank]Name lblElapsed
(See Figure 2: Modified form properties)4. Stopwatch Application – Attaching Code5. Double click anywhere on the form to open the code window. Or select View Code from the project
window.6. Select specific object then type the following line of codes.
PLP – College of Computer Studies - rct- 6/‘06
Figure 1: Sample Form Layout
Figure 2: Modified Form properties
Figure 3: Sample Run (Output)
35
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesGeneral Declaration
Option Explicit ‘This statement forces us to declare variables.‘Declaration of StartTime, EndTime & ElapsedTime as variables global within the form.Dim StartTime As VariantDim EndTime As VariantDim ElapsedTime As Variant
cmdStart EventPrivate Sub cmdStart_Click()
'Establish and print starting timeStartTime = NowlblStart.Caption = Format(StartTime, "hh:mm:ss")lblEnd.Caption = ""lblElapsed.Caption = ""
End Sub
cmdEnd EventPrivate Sub cmdEnd_Click()
'Find the ending time, compute the elapsed time'Put both values in label boxesEndTime = NowElapsedTime = EndTime - StartTimelblEnd.Caption = Format(EndTime, "hh:mm:ss")lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss")
End Sub
cmdExit EventPrivate Sub cmdExit_Click()
Unload MeEnd Sub
7. Save and run the program to test the output (see Figure 3)
PLP – College of Computer Studies - rct- 6/‘06
36
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #5: My Calendar Application Project Name : PEPJT02<FirstNameLastName> Example: PEPJT01RichardGwapoForm Name : PE05FRM02<FirstNameLastName> Example: PE05FRM02RichardGwapo
Project 2 / Form 2Steps:
1. Retrieve/Open your PEPJT02 (Practice Exercise Project 2)
2. Add Form2 and add the following controls as shown (see Figure 1) (place 5 labels and 1 timer)
3. Set Properties: Form2:
Caption My CalendarBorderStyle 1-Fixed Single
Timer:Name timDisplayInterval 1000
Label1:Name lblDayCaption SundayFontName Times New RomanFontStyle BoldFontSize 24
Label2:Name lblTimeCaption 00:00:00 PMFontName Times New RomanFontStyle BoldFontSize 24
Label3:Name lblYearAlignment 2 – Center Caption 2004FontName Times New RomanFontStyle BoldFontSize 24
Label4:Name lblNumberAlignment 2 – CenterCaption 18FontName ArialFontStyle BoldFontSize 72FontSize 24
PLP – College of Computer Studies - rct- 6/‘06
Figure 1: Sample Form Layout (Calendar)
Figure 2: Sample Run (Output)
Label5:Name lblMonthAlignment 2 – CenterCaption JulyFontName Time New RomanFontStyle Bold
37
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
4. Source Codes:
General DeclarationOption Explicit
timDisplay Event Private Sub timDisplay_Timer() Dim Today As Variant Today = Now lblDay.Caption = Format(Today, "dddd") lblMonth.Caption = Format(Today, "mmmm") lblYear.Caption = Format(Today, "yyyy") lblNumber.Caption = Format(Today, "d") lblTime.Caption = Format(Today, "h:mm:ss ampm")End Sub
5. Run the program to test the output (see Figure 2)
PLP – College of Computer Studies - rct- 6/‘06
38
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Controlling Program Flow
Six Comparison/Relational/Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically, they resemble mathematical operators. Conditional operators are very powerful tools, they let the VB program compare data values and then decide what action to take, whether to execute a program or terminate the program and etc.
Operator Meaning= Equal to> More than< Less Than
>= More than and equal<= Less than and equal<> Not Equal to
Note: You can also compare strings with the above operators. However, there are certain rules
to follows: Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D".......<"Z" and number are less than letters.
Logical Operators
In addition to conditional operators, there are a few logical operators which offer added power to the VB programs.
Operator MeaningAnd Both sides must be trueor One side or other must be true
Xor One side or other must be true but not bothNot Negates truth
PLP – College of Computer Studies - rct- 6/‘06
39
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Conditional Statement / Selective Structure
If...Then...Else Statements
To effectively control the VB program flow, we shall use If...Then...Else statement together with the conditional operators and logical operators.
Format: if...then...else statement is :
If conditions Then VB expressions Else VB expressions End If
Note: any If..Then..Else statement must end with End If. Sometime it is not necessary to use
Else.
Program Listing 4: Example of Conditional StatementPrivate Sub OK_Click()
firstnum = Val(usernum1.Text) secondnum = Val(usernum2.Text) total = Val(sum.Text)
If total = firstnum + secondnum And Val(sum.Text) <> 0 Then correct.Visible = True wrong.Visible = False Else correct.Visible = False wrong.Visible = True End If
End Sub
PLP – College of Computer Studies - rct- 6/‘06
40
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Select Case
If you have a lot of conditional statements, using If..Then..Else could be very messy. For multiple conditional statements, it is better to use Select Case
The format is :
Select Case expression Case value1 Block of one or more VB statements Case value2 Block of one or more VB Statements Case value3 Block of one or more VB statements Case value4 . . Case Else Block of one or more VB Statements
End Select
Note: The data type specified in expression must match that of Case values.
Program Listing 5: Example of Selective Structure 1'Examination Grades Dim grade As String Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade Case "A"
result.Caption="High Distinction" Case "A-" result.Caption="Distinction" Case "B" result.Caption="Credit" Case "C" result.Caption="Pass" Case Else result.Caption="Fail" End Select
End sub
Note: Please note that grade is a string, so all the case values such as "A" are of String data type.
PLP – College of Computer Studies - rct- 6/‘06
41
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Program Listing 6: Example of Selective Structure 2Dim mark As Single Private Sub Compute_Click() 'Examination Marks mark = mrk.Text
Select Case mark Case Is >= 85
comment.Caption = "Excellence" Case Is >= 70
comment.Caption = "Good" Case Is >= 60 comment.Caption = "Above Average" Case Is >= 50 comment.Caption = "Average" Case Else comment.Caption = "Need to work harder" End Select End Sub
Note we use the keyword Is here to impose the conditions. This is generally used for numeric data.
Program Listing 7: Example of Selective Structure 3
Dim mark As Single Private Sub Compute_Click() 'Examination Marks mark = mrk.Text Select Case mark Case 0 to 49 comment.Caption = "Need to work harder" Case 50 to 59 comment.Caption = "Average"
Case 60 to 69 comment.Caption = "Above Average"
Case 70 to 84 comment.Caption = "Good"
Case Else comment.Caption = "Excellence"
End Select End Sub
PLP – College of Computer Studies - rct- 6/‘06
42
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #6: Lucky Seven ProgramProject Name : PEPJT02<FirstNameLastName> Example: PEPJT02RichardGwapoForm Name : PE06FRM03<FirstNameLastName> Example: PE04FRM03RichardGwapo
Sample Form: Sample Output:
cmdSpic_Click Event:Private Sub cmdSpin_Click() Dim Num1 As Integer Dim Num2 As Integer Dim Num3 As Integer Num1 = Int(Rnd * 10) Num2 = Int(Rnd * 10) Num3 = Int(Rnd * 10) lblNum1.Caption = Format(Num1, "#0") lblNum2.Caption = Format(Num2, "#0") lblNum3.Caption = Format(Num3, "#0") If Num1 = 7 Or Num2 = 7 Or Num3 = 7 Then MsgBox "You win" Else MsgBox "Sorry " End IfEnd Sub
Form_Load Event Private Sub Form_Load() Randomize TimerEnd Sub
PLP – College of Computer Studies - rct- 6/‘06
Specs:3 Labels: Name: lblNum1 Name: lblNum2 Name: lblNum3 FontSize: 201 CommandButton: Name: cmdSpin
7 7 7
Message: “You Win”
43
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #3:Project Name : MPPJT02<FirstNameLastName> Example: MPPJT02RichardGwapoForm Name : MP03FRM01<FirstNameLastName> Example: MP03FRM01RichardGwapo
PROJECT 2: FORM #1: 3 Digits Lotto Program
Instructions: 1. Your bet should not be less than 10 pesos, otherwise it will prompt you with “Enter minimum amount of
Php 10.00”2. Enter single digits for each of the text box3. If the content of the text box are all equal to the winning numbers (in order) it will prompt you with “You
have won 1 MILLION PESOS JACKPOT” (see sample Message box below), otherwise it will prompt you with “Sorry better luck next time”
4. But, if the content of the text box are equal to the winning numbers (but not in order) it will prompt you with “You have won a consolation prize of ____”. The consolation prizes will depend to the BET amount (Example: Bet is 100, multiply your bet to 1,000.00 to get the consolation amount.)
PLP – College of Computer Studies - rct- 6/‘06
44
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #4: Project Name : MPPJT02<FirstNameLastName> Example: MPPJT02RichardGwapoForm Name : MP04FRM02<FirstNameLastName> Example: MP04FRM02RichardGwapo
PROJECT #2:FORM #2: SAMPLE FORM LAYOUT
Sample Output:
Formula: Semestral Grade = 25% of Prelim + 25% of Midterm + 50% of Final
Point Equivalent TableSem. Grade Equivalent Sem. Grade Equivalent98 – 100 1.00 83 – 85 2.2595 – 97 1.25 80 – 82 2.5092 – 94 1.50 77 – 79 2.7589 – 91 1.75 75 – 76 3.0086 – 88 2.00 74 & below 5.00 (FAILED)
Additional Logical Problems:
• For New Entry Button: Upon clicking displays this message box If “Yes” will clear all entries else nothing happen
• For Compute Button:Upon clicking displays this message boxIf “Yes” will display the results else nothing happen
• For Exit Button: Will close the program/application
PLP – College of Computer Studies - rct- 6/‘06
45
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
The Call Statement
To call another procedure, you can simply place the procedure name in code. You can also use the optional call statement.
Format: [Call] nmae [(argument list)] Example: Call cmdNext
Call An optional keyword used to signify the transfer of program control to another Procedure
Name The name of the procedure to pass control to.Argumentlist The variables or expression to pass to another procedure.
Introduction to VB Functions I
Functions are similar to normal procedures but the main purpose of the functions is to accept certain inputs and pass them on to the main program to finish the execution. They are two types of function, the built-in functions(or internal functions) and the functions created by the programmers.
The general format of a function is:functionName(arguments)
where arguments are values that are passed on to the functions. In this lesson, we are going to learn two very basic but useful internal functions, i.e. the
MsgBox( ) and InputBox ( ) functions.
The Message BoxMsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues.
This message box format is as follows: yourMsg=MsgBox(Prompt, Style Value, Title)
The first argument, Prompt - will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box. The Title argument will display the title of the message board.
PLP – College of Computer Studies - rct- 6/‘06
46
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Style Value Named Constant Buttons Displayed0 vbOkOnly Ok button1 vbOkCancel Ok and Cancel buttons2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.3 vbYesNoCancel Yes, No and Cancel buttons4 vbYesNo Yes and No buttons5 vbRetryCancel Retry and Cancel buttons
Note: We can use named constant in place of integers for the second argument to make the programs
more readable. In fact, VB6 will automatically shows up a list of names constant where you can select one of them.
Example: yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")
andyourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")
are the same.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section.
Return Values and Command ButtonsValue Named Constant Button Clicked
1 vbOk Ok button2 vbCancel Cancel button3 vbAbort Abort button4 vbRetry Retry button5 vbIgnore Ignore button6 vbYes Yes button7 vbNo No button
Example:
Figure 14: Sample Interface
PLP – College of Computer Studies - rct- 6/‘06
47
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesYou draw three command buttons and a label as shown in Figure 14.
Program Listing 8: The procedure for the test button: Private Sub Test_Click() Dim testmsg As Integer testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then Display.Caption = "Testing Successful" Else Display.Caption = "Testing fail" End If End Sub
Note: When a user click on the test button, the image like the one shown in Figure 15 will appear. As
the user click on the OK button, the message "Testing successful" will be displayed and when he/she clicks on the Cancel button, the message "Testing fail" will be displayed.
Figure 15: Test Message
o To make the message box looks more sophisticated, you can add an icon besides the message. There are four types of icons available in VB as shown in the table below:
Value Named Constant Icon16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
PLP – College of Computer Studies - rct- 6/‘06
48
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesIn this example, the following message box will be displayed:
Figure 16: Modified Test Message
Note: You could draw the same Interface as in example program listing 8, but modify the codes
as follows:
Program Listing 9: Example of MsgBox with Yes, No & Cancel buttonPrivate Sub test2_Click()
Dim testMsg2 As Integer testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg2 = 6 Then display2.Caption = "Testing successful" ElseIf testMsg2 = 7 Then display2.Caption = "Are you sure?" Else display2.Caption = "Testing fail" End If
End Sub
The InputBox( ) Function
An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text.
Format:
myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)
Where: myMessage - is a variant data type but typically it is declared as string, which accept the
message input by the users. The arguments are explained as follows:o Prompt - The message displayed normally as a question asked. o Title - The title of the Input Box. o default-text - The default text that appears in the input field where users can use
it as his intended input or he may change to the message he wish to key in. o x-position and y-position - the position or the coordinate of the input box.
PLP – College of Computer Studies - rct- 6/‘06
49
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Figure 17: Sample Interface for InputBox function
Program Listing 10: Example of an InputBox function‘The procedure for the OK button Private Sub OK_Click()
Dim userMsg As String userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your message
here", 500, 700)
If userMsg <> "" Then message.Caption = userMsg Else message.Caption = "No Message" End If
End Sub
Note: When a user click the OK button, the input box as shown in Figure 18 will appear. After user
entering the message and click OK, the message will be displayed on the caption, if he click Cancel, "No message" will be displayed.
Figure 18: InputBox for Message Entry Form
PLP – College of Computer Studies - rct- 6/‘06
50
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #7: Flash Card Addition Problems Project Name : PEPJT03<FirstNameLastName> Example: PEPJT03RichardGwapoForm Name : PE07FRM01<FirstNameLastName> Example: PE07FRM01RichardGwapo
Project 2 / Form 3Steps:
1. Retrieve/Open your PEPJT02 (Practice Exercise Project 2)2. Add Form3 and add the following controls as shown (see Figure 1) (place 5 labels
and 1 timer)
3. Set Properties: Form3
BorderStyle 1 – Fixed SingleCaption Flash Card Addition
Command1Name cmdNextCaption &Next ProblemEnabled False
Command2Name cmdExitCaption E&xit
Text1Name txtAnswerFontName ArialFontSize 48MaxLenght 2
Label1Name lblNum1Alignment 2 – CenterFontName ArialFontSize 48
PLP – College of Computer Studies - rct- 6/‘06
Label1
Label3
Label2
Label4
Label5
Label6
Text1
Label7
Command1
Command2
Figure 1: Sample Layout
Figure 2: Sample Run (Output)with correct answer
Note: After entering your answer press enter key to check if the answer is correct or not.
51
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Caption [blank] Label2:
Alignment 2 – CenterCaption +FontName ArialFontSize 48
Label3:Name lblNum2Alignment 2 – CenterCaption [blank]FontName ArialFontSize 48
Label4:Alignment 2 – CenterCaption ScoreFontName MS Sans SerifFontSize 18
Label5:Name lblScoreAlignment 2 – CenterBackColor &H0000FFFF& (Yellow)BorderStyle 1 – Fixed SingleCaption 0FontName Times New RomanFontStyle BoldFontSize 36
Label6:Alignment 2 – CenterCaption =FontName ArialFontSize 48
Label7:Name lblMessageAlignment 2 – CenterBackColor &H00FFFF00& (Cyan)BorderStyle 1 – Fixed SingleFontName MS Sans SerifFontStyle Bold & ItalicFontSize 24
4. Source Codes:
General DeclarationOption Explicit
Dim Sum As Integer Dim NumProb As Integer, NumRight As Integer
cmdExit Event:Private Sub cmdExit_Click() EndEnd Sub
cmdNext Event:Private Sub cmdNext_Click()
PLP – College of Computer Studies - rct- 6/‘06
Figure 3: Sample Run (Output)with incorrect answer
*** Click Next Problem button to flash another sets of numbers*** Click Exit button to end the application
52
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
'Generate next addition problem Dim Number1 As Integer Dim Number2 As Integer txtAnswer.Text = "" lblMessage.Caption = "" NumProb = NumProb + 1 'Generate random numbers for addends Number1 = Int(Rnd * 21) Number2 = Int(Rnd * 21) lblNum1.Caption = Format(Number1, "#0") lblNum2.Caption = Format(Number2, "#0") 'Find sum Sum = Number1 + Number2 cmdNext.Enabled = False txtAnswer.SetFocusEnd Sub
Form_Activate Event:Private Sub Form_Activate() Call cmdNext_ClickEnd Sub
Form_Load Event:Private Sub Form_Load() Randomize Timer NumProb = 0 NumRight = 0End Sub
txtAnswer Event:Private Sub txtAnswer_KeyPress(KeyAscii As Integer) Dim Ans As Integer 'Check for number only input and for return key If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyBack Then Exit Sub ElseIf KeyAscii = vbKeyReturn Then
'Check answer Ans = Val(txtAnswer.Text) If Ans = Sum Then NumRight = NumRight + 1 lblMessage.Caption = "That's correct!" Else lblMessage.Caption = "Answer is " + Format(Sum, "#0") End If lblScore.Caption = Format(100 * NumRight / NumProb, "##0") cmdNext.Enabled = True cmdNext.SetFocus Else KeyAscii = 0 End IfEnd Sub
PLP – College of Computer Studies - rct- 6/‘06
53
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
5. Save and run the program to test the output (see Figure 2 & 3)
PLP – College of Computer Studies - rct- 6/‘06
54
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #5: Project Name : MPPJT03<FirstNameLastName> Example: MPPJT03RichardGwapoForm Name : MP05FRM01<FirstNameLastName> Example: MP05FRM01RichardGwapo
PROJECT #3:FORM #1: SAMPLE FORM LAYOUT
PRICES:Size: Small – Php 100.00 Medium – 150.00 Large – 200.00
Crust Type: Thin Crust – same as size prices Thick Crust – Plus 50% of size prices
Drinks: Soft Drinks – Php 20.00 Fruit Juice – 15.00 Coffee/Chocolate 25.00
Extra Toppings: Plus Php 10.00 per extra toppings
Build Pizza Button: will display message box Your Pizza (see sample above)Clear Toppings Button: will uncheck all check boxes.Compute Button: will display all values under Amount frameClear All Button: will clear all entriesExit Button: will close the program.
PLP – College of Computer Studies - rct- 6/‘06
55
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #6: Project Name : MPPJT03<FirstNameLastName> Example: MPPJT03RichardGwapoForm Name : MP06FRM02<FirstNameLastName> Example: MP06FRM02RichardGwapo
PROJECT #3:FORM #2: SAMPLE FORM LAYOUT
Logical Problems & Formulas: Position Code Rate/Day Civil Status Rate Basic Pay SSS Rate A 500.00 Single 10% 10,000 & above 7%
B 400.00 Married 5% 5,000 – 9,999 5%C 300.00 Widowed 5% 1,000 – 4,999 3%
below 1,000 1%
Basic Pay = No. of Days Worked * Rate/DaySSS Contribution = Basic Pay * SSS Rate Withholding Tax = Basic Pay * Tax RateNet Pay = Basic Pay – (SSS Contribution + Withholding Tax)
• Upon choosing the desired Employee Number, it will automatically display the Employee Name.
• For Compute Button, will compute the Basic Pay, SSS Contribution, Withholding Tax and Net Pay
PLP – College of Computer Studies - rct- 6/‘06
EMPLOYEE PAYROLL COMPUTATION
56
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
• For Clear Button, will clear all entries• For Quit Button, will close the program/application.
PLP – College of Computer Studies - rct- 6/‘06
57
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #7: Project Name : MPPJT04<FirstNameLastName> Example: MPPJT04RichardGwapoForm Name : MP07FRM01<FirstNameLastName> Example: MP07FRM01RichardGwapo
PROJECT 4: FORM #1: Hotel Billing System
Sample Form and sample output:
Room Capacity
Room Type Rate/day Type of Payment
Additional Charge
Regular 100.00 Cash No add’l chargeSingle De Luxe 300.00 Check + 5%
Suite 500.00 Credit Card + 10%Regular 200.00
Double De Luxe 500.00Suite 800.00Regular 500.00
Family De Luxe 750.00Suite 1,000.00
PLP – College of Computer Studies - rct- 6/‘06
Problem:• Compute for Total Amount based on the date of
check-in and check-out.• Select room capacity, room type and payment
type before clicking Compute button otherwise, will prompt you with “No selected room capacity” or “No selected room type” or “No selected type of payment”
58
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Looping
Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called looping .
Do Loop
Format:a) Do While condition
Block of one or more VB statements Loop
b) Do Block of one or more VB statements Loop While condition
c) Do Until condition Block of one or more VB statements Loop
d) Do Block of one or more VB statements
Loop Until condition
Example:Do while counter <=1000
num.Text=counter counter =counter+1 Loop
Note: The above example will keep on adding until counter >1000. The above example can be rewritten as
Do num.Text=counter counter=counter+1 Loop until counter>1000
PLP – College of Computer Studies - rct- 6/‘06
59
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
For....Next Loop
Format: For counter=startNumber to endNumber (Step increment)
One or more VB statements Next
Example: (a) For counter = 1 to 10 display.Text =counter Next
(b) For counter=1 to 1000 step 10 counter = counter + 1 Next
(c) For counter = 1000 to 5 step -5 counter = counter - 10 Next
PLP – College of Computer Studies - rct- 6/‘06
60
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Introduction to VB Functions II
Creating Your Own Functions
Format: Public Function functionName (Arg As dataType,..........) As dataType or Function functionName (Arg As dataType,..........) As dataType
Note: Public indicates that the function is applicable to the whole program and Private indicates that the function is only applicable to a certain module or procedure.
Example: The following program will automatically compute examination grades based on the
marks that a student obtained.
Figure 11: Sample Interface
Program Listing 19: Example of Functions declaration‘Declaration of Function gradePublic Function grade(mark As Variant) As String
Select Case mark Case Is >= 80 grade = "A" Case Is >= 70 grade = "B" Case Is >= 60 grade = "C" Case Is >= 50
PLP – College of Computer Studies - rct- 6/‘06
61
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
grade = "D" Case Is >= 40 grade = "E" Case Else grade = "F" End Select
End Function
‘Procedure computePrivate Sub compute_Click() grading.Caption = grade(mark) End Sub
‘Procedure end – to close the applicationPrivate Sub End_Click() End End Sub
PLP – College of Computer Studies - rct- 6/‘06
62
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : ____________________________ Rating: Date Finished : _____________ Section: _________ Time: ________Instructor : ____________________________
Practice Exercise #8: Password EntryProject Name : PEPJT03<FirstNameLastName> Example: PEPJT03RichardGwapoForm Name : PE07FRM02<FirstNameLastName> Example: PE07FRM02RichardGwapo
Form 1: Password Entry
Specs:TextBox Name: txtPassword
CommandButton Name: cmdAccept
Display this message box if the password is incorrect:
Click Retry: to go back to Password Entry Form Click Cancel: to quits the application/program.
Display this message box if you failed to enter the password correctly (three (3) attempts only)
Click OK: to quits the application/program.
PLP – College of Computer Studies - rct- 6/‘06
Then, will display Form 1 after clicking on OK button (Sample Program above)
Display this Message Box if the password is correct
63
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesSource Codes:
cmdAccept Event: Private Sub cmdAccept_Click()
Dim Ans As IntegerStatic Trial As Integer
If txtPassword.Text = "gwapo" Then MsgBox "Password Accepted...", vbInformation, "Password Entry" Unload Me Form3.Show Else Ans = MsgBox("Invalid Password....Try Again...", vbQuestion + vbRetryCancel, "Password Entry") If Ans = vbRetry Then txtPassword.Text = "" txtPassword.SetFocus If Trial = 2 Then MsgBox "Intruder!....", vbCritical + vbOKOnly, "Password Entry" End Else Trial = Trial + 1 End If Else End End If End If
End Sub
Form_Activate Event:Private Sub Form_Activate()
txtPassword.SetFocus End Sub
PLP – College of Computer Studies - rct- 6/‘06
64
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Name : _______________________ Date Finished: ________ Rating: Course/Section: _________ Time: ________ Program Design (30%): _____Instructor : _______________________ Program Logic (70%): _____
100%
Machine Problem #8: Project Name : MPPJT05<FirstNameLastName> Example: MPPJT05RichardGwapoForm Name : MP08FRM01<FirstNameLastName> Example: MP08FRM01RichardGwapo
PROJECT #5:FORMS: SAMPLE FORM LAYOUT
Upon running the program displays the 1st form, which is the PASSWORD ENTRY
FORM 1:
Note: No limit for password, if incorrect password will prompt the user to RETRY & CANCEL and user name should have an entered value otherwise will prompt the user to enter value for user name.
If the password is correct will display the 2nd form (MENU)
FORM 2: (with File & Help Menu)Main Menu: File HelpSub Menus: Transaction About
Exit
<File> <Transaction>, will display the Transaction Form:
For TRANSACTION Form:Initially; BUTTONS: New, Clear, Close & Compute are all in disabled layout (as shown below)
<File> <Exit>, will close the program If Transaction is clicked, displays 3rd Form: (as shown below)
PLP – College of Computer Studies - rct- 6/‘06
Richard Gwapo
* * * * *
65
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesFORM 3:
Appliances/Items Unit Price Appliances/Items Unit PriceElectric Fan 500.00 Television 5,000.00Refrigerator 9,000.00 Air Conditioner 10,000.00Washing Machine 4,000.00 Rice Cooker 600.00Oven Toaster 550.00 Electric Stove 1,000.00Flat Iron 350.00 Electric Pot 800.00VCD Player 1,200.00 Karaoke 2,500.00Mini Component 3,500.00 Microwave Oven 3,000.00
Logical Problems: Double click Appliance item (List Box) then the selected item will be displayed to the Appliance Sold (List
Box) and UnitPrice (List Box) (see example below)Note: Be sure that you have enter value in the Quantity
If quantity is less than or equal to zero (0) it will prompt the user to input quantity. Amount Text Box will be based on the Appliance Unit Price * Quantity
Example: Appliance Sold: Electric Fan, Unit Price: 500, Quantity: 2 (see example below) Sub-total Text Box will be based on the total item sold.
Example: Appliance Sold: Air Conditioner 10,000.00 X 1 and Electric Fan 500.00 X 2(see example below);
Choose Type of Payment: Cash or Charge then, will enable Compute buttonIf Compute button is clicked; for CASH
Total Amount = Sub-total less 5% discount
PLP – College of Computer Studies - rct- 6/‘06
3rd Form: (Transaction Form)
User Name: Railee Darrel <Insert Date & Time here>
0
66
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory ExercisesOutput:For Cash Payment
Then, will enable buttons; New, Clear & Close
Enter value for Amount Tendered: Amount Tendered should be exact amount or should be greater than Total Amount otherwise, will prompt the user to enter valid amount.
Click Change button to display the amount change. For New button, will clear all entries For Clear button, will Quantity, Appliance Sold, Unit Price and Type of Payment only. If Compute button is clicked; for CHARGE
Total Amount = Sub-total + 5% additional charge For Close button, will close the transaction window only.
Output:For Charge Payment.
PLP – College of Computer Studies - rct- 6/‘06
User Name: Richard Gwapo <Insert Date & Time here>
User Name: Richard Gwapo <Insert Date & Time here>
2
2
67
Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises
Then, will hide all controls under Total Amount and displays 5% Additional to all Charge Payments (see example above)
FORM 4:
If Help then About is clicked, will display a Form “About the program”
If button OK is clicked will close the form window.
If button AUTHOR is clicked will display message group members/programmers.
PLP – College of Computer Studies - rct- 6/‘06