Вы находитесь на странице: 1из 67

Object Oriented Programming 1: Using Microsoft Visual Basic 6.

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 eventdriven, 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.

Event?

Event processor

Basic Code

Basic Code

Basic Code

Event procedure

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


1
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Project (.VBP, .MAK)
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)

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

2
PLP College of Computer Studies
- rct- 6/06

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.
3
PLP College of Computer Studies
- rct- 6/06

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 Application There 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 Properties Visual 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

4
PLP College of Computer Studies
- rct- 6/06

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

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

Figure 4: Toolbox Form Controls

5
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Common Object/Controls and Their Naming Conventions: Object Type Form Picture Box Label Text Box Frame Command Button Check Box Option Button Combo Box List Box Horizontal Scroll Bar Vertical Scroll Bar Timer Prefix frm pic lbl txt fra cmd chk opt Example frmCalculatorProgra m picHappyFace lblEnterName txtEnterName frmPickOptions cmdEndProgram chkPickFeatures optPaymentChoice Description A window or dialog box that makes up part of an applications user interface A container that can display graphics Displays text that the user cannot directly modify at Run time. Displays text that the user can modify at Run Time A container that groups other controls such as radio buttons or check boxes. Responds to a user click to trigger an event 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. 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. 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. Displays a list of values from which the user can select 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 Same as a horizontal scroll bar, only it is displayed vertically. Triggers an event when a specified time period elapses. Provides a list of available disk drives and enables the user to select one. Provides a list drive paths and directories, enabling the user to select one Provides a list of files, enabling the user to select one. A two-dimensional tool for drawing shapes. A two-dimensional tool for drawing straight lines. Similar to the Picture Box, but easier to use, it can display graphic images. Support database compatibility with programs such as Microsoft Access. Provides a data link with an Object Linking and Embedding compliant application
- rct- 6/06

cbo lst hsb

cboColorChoice lstTravelDestination hsbVolumeControl

vsb tmr

vsbTrebleControl tmrDelay drvHardDiskContent dirTree filProgramFiles shpCircle linBorder imgClouds datEmployeeRecords oleSpreadsheet
6

Drive List drv Box Directory dir List Box File List Box fil Shape Line Image Data OLE shp lin img dat ole

PLP College of Computer Studies

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 2 Sum = Val(Text1.Text) + Val(Text2.Text) To display the answer on label 1 Label1.Caption = Sum End Sub

7
PLP College of Computer Studies
- rct- 6/06

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 () Statements End 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")
8
PLP College of Computer Studies
- rct- 6/06

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:
9
PLP College of Computer Studies
- rct- 6/06

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 = vbRed ElseIf Check1.Value = 1 Then Form1.BackColor = vbBlue End 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 = 0 End Sub Private Sub Option2_Click() Shape1.Shape = 1 End Sub Private Sub Option3_Click() Shape1.Shape = 2 End Sub Private Sub Option4_Click() Shape1.Shape = 3 End Sub Private Sub Option5_Click() Shape1.Shape = 4 End Sub

The Drive List Box


10
PLP College of Computer Studies
- rct- 6/06

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.

Object Box

The Properties Window is used to establish initial property values for objects. The drop-down List
11
PLP College of Computer Studies
- rct- 6/06

Properties

Figure 7: The Directory List Box

Setting Box

box at the top of the window lists all objects in the current Form. Two views are available;

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.
Properties Window Title Bar

Figure 8: Properties Window

The Form Layout Window

shows where (upon program execution) your Form will be displayed relative to your monitors 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.
View Object

View Code

Toggle Folders

Figure 10: Project Window

Building a Visual Basic Application


12
PLP College of Computer Studies
- rct- 6/06

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 Procedures

Writing Visual Basic Code


13
PLP College of Computer Studies
- rct- 6/06

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> OR Click 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. Click Save button Then, displayed Save Project As dialog box Type the project name (follow the PEPJT01RICHARDGWAPO

4.

5.
6.

project

Format

filename)

ex:

Note:

Before typing the project name makes sure that the Save Project As dialog box (as shown besides) is displayed in your screen. Click Save button

7.

Note: To RUN/EXECUTE the program/application Click on Run menu then, click Start - OR Press F5 function key OR Click Start button
14
PLP College of Computer Studies
- rct- 6/06

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

15
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Rating:

Practice Exercise #1: Adding several controls to Form Window


Project Name Form Name : PEPJT01<FirstNameLastName> : PE01FRM01<FirstNameLastName> Example: PEPJT01RichardGwapo Example: PE01FRM01RichardGwapo

Steps: 1. Launch Visual Basic application/program; Displays New Project as shown (see figure 1) Be sure that Standard EXE is being selected 2. Click Open button Then, displays Form Window as shown below (see figure 2)

Figure 1: New Project Window

Figure 2: Form Window

3.

Add the following controls as shown (see figure 3) Labels Text Box Combo Box List Box Frame (Course & Subjects enrolled) Command Button Click Save button or File Save Project or File Save Project As Follow the project name and Form name Format Apply necessary enhancement: Font, Font Size, Font Color, Changing Caption etc.

4.

5.

Figure 3: Sample Form Interface

16
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Rating:

Practice Exercise #2: Inserting/Adding Form in the existing project & using MsgBox
Project Name Form Name Steps: 1. Exercise project 1) 2. 3. 4. Click <Project> menu then select <Add Form> New Form will be added in your existing project (see Figure 1) Add 2 controls/objects in your new Form as (see Figure 2) Change Properties: Form = Caption: Using MsgBox Label1 = Name: lblMsg Caption: Message goes here Command1 = Name: cmdTest Caption: Test (see Figure 3) Apply codes to youre application: Click <View> menu then <Code> OR select View Code button project explorer window OR double click the Test Button Then, displayed the Code Window (see Figure 4) : PEPJT01<FirstNameLastName> : PE02FRM02<FirstNameLastName> Example: PEPJT01RichardGwapo Example: PE02FRM02RichardGwapo

Retrieve/Open your PEPJT01 (Practice

shown
Figure 1: New Form in Project Explorer Window

5.

from
Figure 2: Form2 with Label1 & Command1 controls

Object

Procedure Figure 4: Code Window of Form2

6.

In the Event combo box (General) select cmdTest and in the Procedure Figure 3: combo box (Declarations) select click (see Figure 5) Note: The default event for a CommandButton Object is Click (see Figure 6)

Modified Form2

Figure 6: Code Window for cmdTest Object with Procedure click Figure 5: Object cmdTest

7.

Inside the procedure Type the source code as shown: (see Figure 7)

17
PLP College of Computer Studies
Figure 7: Sample procedure/code/command/message of cmdTest Object - rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises

18
PLP College of Computer Studies
- rct- 6/06

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 Try to run the program and see the output : (see Figure 9)

8.

Figure 9: Output of Form2

Figure 8: Project Properties Window

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)

Figure10: Code Window for Form object

10. 11.

Save and Run the program to test the output. To add Message Box command: Modify cmdTest procedure and add this line of command (see Figure 12)

19
PLP College of Computer Studies

Figure 11: Event for Form object - rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


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

20
PLP College of Computer Studies
- rct- 6/06

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 ^ * / Mod \ + or & Mathematical function Exponential Multiplication Division Modulus(return the remainder from an integer division) Integer Division(discards the decimal places) String concatenation Example 2^4=16 4*3=12 12/4=3 15 Mod 4=3 19\4=4 "Visual"&"Basic"="Visual Basic"

Program Listing 2: Example of Mathematical/Arithmetic Operators 1 Dim firstName As String Dim secondName As String Dim yourName As String Private Sub Command1_Click() firstName = Text1.Text secondName = Text2.Text yourName = secondName + " " + firstName Label1.Caption = yourName End Sub In this example Program Listing 3, three variables are declared as string. For variables firstName and secondName will receive their data from the users 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 string VAL( ) converts a string to number
21
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Examples: Let X = Hello! Y = How old are you Z = X + How are you Output of Z
Hello! How are you

A=5 B = 10 SUM = A + B Output of SUM


15

C = 20 AGE = 25

Z= Y + STR(AGE) Output of Z
How old are you 25

D = A + B + VAL(C) Output of D
35

Program Listing 3: Example of Mathematical/Arithmetic Operators 2 Dim number1, number2, number3 as Integer Dim total, average as variant Private sub Form_Click( ) number1=val(Text1.Text) number2=val(Text2.Text) number3= val(Text3.Text) Total=number1+number2+number3 Average=Total/5 Label1.Caption=Total Label2.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.

22
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Practice Exercise #3: Using VAL( ) and Mathematical Operators
Project Name Form Name Steps: 1. 2. 3. 4. 5. : PEPJT01<FirstNameLastName> : PE03FRM03<FirstNameLastName> Example: PEPJT01RichardGwapo Example: PE03FRM03RichardGwapo

Rating:

Retrieve/Open your PEPJT01 (Practice Exercise Project 1) Click <Project> menu then select <Add Form> Sample Form Layout/Interface: (see Figure 1) Add the following objects/controls as shown 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 Please type the given names as it is to avoid errors in program codes.

Figure 1: Sample Layout/Interface

Note: 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. 9. Save and run the program to test the output (see Figure 2) Apply necessary enhancement to your Form (optional)

Single Quotation ( )
23
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Single Quotation ( ) serves as a comment or remark

Figure 2: Sample Run

24
PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT01<FirstNameLastName> : MP01FRM01<FirstNameLastName> Example: MPPJT01RichardGwapo Example: MP01FRM01RichardGwapo

PROJECT #1q: FORM #1: SAMPLE FORM LAYOUT/INTERFACE:

SAMPLE OUTPUT:

1)

2)

3)

4)

5)

6)

Objects/Controls Properties: Form: Label:

Caption: Using Mathematical Operators] Argument 1 Argument 2 Sum (+) Difference () Product (*) Quotient (/) Text Box: 1. 2. 3. 4. 5. 6. Name: txtArg1 Name: txtArg2 Name: txtSum Name: txtDiff Name: txtProd Name: txtQuo Alignment: Right Alignment: Right Alignment: Right Alignment: Right Alignment: Right Alignment: Right

Enabled: False Enabled: False Enabled: False Enabled: False

Command Button:

Caption: Result Name: cmdResult

25
PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT01<FirstNameLastName> : MP02FRM02<FirstNameLastName> Example: MPPJT01RichardGwapo Example: MP02FRM02RichardGwapo

PROJECT #1: FORM #2: SAMPLE FORM LAYOUT Form:


1) 2) 3) 4)

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)

5) 6)

7) 8)

9)

Text Box: 1. Name: txtArg1 2. Name: txtArg2 3. Name: txtResult Enabled: False Caption &Clear &Add &Subtract &Multiply &Divide E&xit Description To clear all entries (text box) To add two numbers To subtract two numbers To multiply two numbers To divide two numbers To end/close the program

Command Buttons: #s 4 5 6 7 8 9 SAMPLE OUTPUT:

Name cmdClear cmdAdd cmdSubract cmdMultiply cmdDivide cmdExit

Note: You can also use the following keys Alt + C Clear Alt + A Add Alt + M Multiply Alt + S Subtract Alt + D Divide Alt + 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
- rct- 6/06

26
PLP College of Computer Studies

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


E&xit Exit

27
PLP College of Computer Studies
- rct- 6/06

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 Byte 1 byte Integer 2 bytes Long 4 bytes Single 4 bytes Double 8 bytes Range of Values 0 to 255 -32,768 to 32,767 -2,147,483,648 to 2,147,483,648 -3.402823E+38 to -1.401298E-45 for negative values 1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324 for negative values 4.94065645841247E-324 to 1.79769313486232e+308 for positive values.

Currency 8 bytes Decimal 12 bytes

-922,337,203,685,477.5808 to 922,337,203,685,477.5807 +/- 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 String(fixed length) String(variable length) Date Boolean Object Variant(numeric) Variant(text) Storage Length of string Length + 10 bytes 8 bytes 2 bytes 4 bytes 16 bytes Length+22 bytes Range 1 to 65,400 characters 0 to 2 billion characters January 1, 100 to December 31, 9999 True or False Any embedded object Any value as large as Double 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.
28
PLP College of Computer Studies
- rct- 6/06

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.
29
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises

Loc al Variables

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 My_Variable ThisDate Long_Name_Can_beUSE Invalid Name My.Variable 7Day Mine&Yours *& is not acceptable

30
PLP College of Computer Studies
- rct- 6/06

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 = 0XFF0000 frmExample.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.
31
PLP College of Computer Studies
- rct- 6/06

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 Returned Abs Absolute value of a number Asc ASCII or ANSI code of a character Chr Character corresponding to a given ASCII or ANSI code Cos Cosine of an angle Date Current date as a text string Format Date or number converted to a text string Left Selected left side of a text string Len Number of characters in a text string Mid Selected portion of a text string Now Current time and date Right Selected right end a text string Rnd Random number Sin Sine of an angle Sqr Square root of a number Str Number converted to a text string Time Current time as a text string Timer Number of seconds elapsed since midnight Val Numeric value of a given text string.
32
PLP College of Computer Studies
- rct- 6/06

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

33
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Rating:

Practice Exercise #4: Stopwatch Application (Using several Visual Basic Functions)
Project Name Form Name : PEPJT02<FirstNameLastName> : PE04FRM01<FirstNameLastName> Example: PEPJT02RichardGwapo Example: PE04FRM01RichardGwapo

Project 2 / Form 1
Steps: 1. 2. 3. Create a New Project Add the following controls as shown (see Figure 1) (place three command buttons and six labels on the form) Set Properties of the form, three buttons and six labels: Form1: BoarderStyle 1-Fixed Single Caption Stopwatch Application Name frmStopWatch Command1: Caption &Start Timing Name cmdStart Command2: Caption &Start Timing Name cmdEnd Command3: Caption E&xit Name cmdExit Label1: Caption Start Time Label2: Caption End Time Label3: Caption Elapsed Time Label4: BoarderStyle 1-Fixed Single Caption [Blank] Name lblStart Label5: BoarderStyle 1-Fixed Single Caption [Blank] Name lblEnd Label6: BoarderStyle 1-Fixed Single Caption [Blank] Name lblElapsed

Figure 1: Sample Form Layout

Figure 2: Modified Form properties

4. 5. 6.

(See Figure 2: Modified form properties) Stopwatch Application Attaching Code Double click anywhere on the form to open the code window. Or select View Code from the project window. Select specific object then type the following line of codes.

Figure 3: Sample Run (Output)

34
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


General Declaration Option Explicit This statement forces us to declare variables. Declaration of StartTime, EndTime & ElapsedTime as variables global within the form. Dim StartTime As Variant Dim EndTime As Variant Dim ElapsedTime As Variant cmdStart Event Private Sub cmdStart_Click() 'Establish and print starting time StartTime = Now lblStart.Caption = Format(StartTime, "hh:mm:ss") lblEnd.Caption = "" lblElapsed.Caption = "" End Sub cmdEnd Event Private Sub cmdEnd_Click() 'Find the ending time, compute the elapsed time 'Put both values in label boxes EndTime = Now ElapsedTime = EndTime - StartTime lblEnd.Caption = Format(EndTime, "hh:mm:ss") lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss") End Sub cmdExit Event Private Sub cmdExit_Click() Unload Me End Sub 7. Save and run the program to test the output (see Figure 3)

35
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Practice Exercise #5: My Calendar Application
Project Name Form Name : PEPJT02<FirstNameLastName> : PE05FRM02<FirstNameLastName> Example: PEPJT01RichardGwapo Example: PE05FRM02RichardGwapo

Rating:

Project 2 / Form 2
Steps: 1. 2. 3. Retrieve/Open your PEPJT02 (Practice Exercise Project 2) Add Form2 and add the following controls as shown (see Figure 1) (place 5 labels and 1 timer) Set Properties: Form2: Caption My Calendar BorderStyle 1-Fixed Single Timer: Name timDisplay Interval 1000 Figure 1: Sample Form Layout (Calendar) Label1: Name lblDay Caption Sunday FontName Times New Roman FontStyle Bold FontSize 24 Label2: Name lblTime Caption 00:00:00 PM FontName Times New Roman FontStyle Bold FontSize 24 Label3: Figure 2: Sample Run (Output) Name lblYear Alignment 2 Center Caption 2004 FontName Times New Roman FontStyle Bold FontSize 24 Label5: Label4: Name lblMonth Name lblNumber Alignment 2 Center Alignment 2 Center Caption July Caption 18 FontName Time New Roman FontName Arial FontStyle Bold FontStyle Bold FontSize 72 FontSize 24

36
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


4. Source Codes: General Declaration Option 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)

37
PLP College of Computer Studies
- rct- 6/06

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 And or Xor Not Meaning Both sides must be true One side or other must be true One side or other must be true but not both Negates truth

38
PLP College of Computer Studies
- rct- 6/06

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 Statement Private 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

39
PLP College of Computer Studies
- rct- 6/06

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.
40
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Program Listing 6: Example of Selective Structure 2 Dim 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

41
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Practice Exercise #6: Lucky Seven Program
Project Name Form Name : PEPJT02<FirstNameLastName> : PE06FRM03<FirstNameLastName> Example: PEPJT02RichardGwapo Example: PE04FRM03RichardGwapo

Rating:

Sample Form: Specs: 3 Labels: Name: lblNum1 Name: lblNum2 Name: lblNum3 FontSize: 20 1 CommandButton: Name: cmdSpin

Sample Output:

Message: You Win

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 If End Sub

Form_Load Event Private Sub Form_Load() Randomize Timer End Sub 42


PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT02<FirstNameLastName> : MP03FRM01<FirstNameLastName> Example: MPPJT02RichardGwapo 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 box 3. 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.)

43
PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT02<FirstNameLastName> : MP04FRM02<FirstNameLastName> Example: MPPJT02RichardGwapo 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 Table Sem. Grade Equivalent 98 100 1.00 95 97 1.25 92 94 1.50 89 91 1.75 86 88 2.00

Sem. Grade 83 85 80 82 77 79 75 76 74 & below

Equivalent 2.25 2.50 2.75 3.00 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 box If Yes will display the results else nothing happen For Exit Button: Will close the program/application
44
PLP College of Computer Studies
- rct- 6/06

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)] Call Example: Call cmdNext

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 Box


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

45
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Style Value 0 1 2 3 4 5 Named Constant vbOkOnly vbOkCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel Buttons Displayed Ok button Ok and Cancel buttons Abort, Retry and Ignore buttons. Yes, No and Cancel buttons Yes and No buttons 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") and yourMsg=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 Buttons Value Named Constant 1 vbOk 2 vbCancel 3 vbAbort 4 vbRetry 5 vbIgnore 6 vbYes 7 vbNo Example: Button Clicked Ok button Cancel button Abort button Retry button Ignore button Yes button No button

Figure 14: Sample Interface


46
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


You 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 16 32 48 64 Named Constant vbCritical vbQuestion vbExclamation vbInformation Icon

47
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


In 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 button Private 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.
48
- rct- 6/06

PLP College of Computer Studies

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


49
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Practice Exercise #7: Flash Card Addition Problems
Project Name Form Name : PEPJT03<FirstNameLastName> : PE07FRM01<FirstNameLastName> Example: PEPJT03RichardGwapo Example: PE07FRM01RichardGwapo

Rating:

Project 2 / Form 3
Steps: 1. 2. Retrieve/Open your PEPJT02 (Practice Exercise Project 2) Add Form3 and add the following controls as shown (see Figure 1) (place 5 labels

Label1 Label2 Label3 Label6 Text1

Label4

Label7

Label5

Command1 Command2 Figure 1: Sample Layout

and 1 timer) 3. BorderStyle Caption Name Caption Enabled Name Caption Name FontName FontSize MaxLenght Name Alignment FontName FontSize Set Properties: Form3 1 Fixed Single Flash Card Addition Command1 cmdNext &Next Problem False Command2 cmdExit E&xit Text1 txtAnswer Arial 48 2 Label1 lblNum1 2 Center Arial 48 50
PLP College of Computer Studies
- rct- 6/06

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.

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Caption Alignment Caption FontName FontSize Name Alignment Caption FontName FontSize Alignment Caption FontName FontSize Name Alignment BackColor BorderStyle Caption FontName FontStyle FontSize Alignment Caption FontName FontSize Name Alignment BackColor BorderStyle FontName FontStyle FontSize 4. [blank] Label2: 2 Center *** Click Next Problem button to flash another sets of + numbers Arial *** Click Exit button to end the application 48 Label3: lblNum2 2 Center [blank] Arial 48 Label4: 2 Center Score MS Sans Serif 18 Label5: lblScore 2 Center &H0000FFFF& (Yellow) Figure 3: Sample Run (Output) 1 Fixed Single with incorrect answer 0 Times New Roman Bold 36 Label6: 2 Center = Arial 48 Label7: lblMessage 2 Center &H00FFFF00& (Cyan) 1 Fixed Single MS Sans Serif Bold & Italic 24 Source Codes:

General Declaration Option Explicit Dim Sum As Integer Dim NumProb As Integer, NumRight As Integer cmdExit Event: Private Sub cmdExit_Click() End End Sub cmdNext Event: Private Sub cmdNext_Click() 51
PLP College of Computer Studies
- rct- 6/06

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.SetFocus End Sub Form_Activate Event: Private Sub Form_Activate() Call cmdNext_Click End Sub Form_Load Event: Private Sub Form_Load() Randomize Timer NumProb = 0 NumRight = 0 End 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 If End Sub 52
PLP College of Computer Studies
- rct- 6/06

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)

53
PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT03<FirstNameLastName> : MP05FRM01<FirstNameLastName> Example: MPPJT03RichardGwapo 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 frame Clear All Button: will clear all entries Exit Button: will close the program. 54
PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT03<FirstNameLastName> : MP06FRM02<FirstNameLastName> Example: MPPJT03RichardGwapo Example: MP06FRM02RichardGwapo

PROJECT #3: FORM #2: SAMPLE FORM LAYOUT EMPLOYEE PAYROLL COMPUTATION

Logical Problems & Formulas: Position Code Rate/Day A 500.00 B 400.00 C 300.00

Civil Status Single Married Widowed

Rate 10% 5% 5%

Basic Pay SSS Rate 10,000 & above 7% 5,000 9,999 5% 1,000 4,999 3% below 1,000 1%

Basic Pay = No. of Days Worked * Rate/Day SSS Contribution = Basic Pay * SSS Rate Withholding Tax = Basic Pay * Tax Rate Net 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 55
PLP College of Computer Studies
- rct- 6/06

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.

56
PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT04<FirstNameLastName> : MP07FRM01<FirstNameLastName> Example: MPPJT04RichardGwapo Example: MP07FRM01RichardGwapo

PROJECT 4: FORM #1: Hotel Billing System Sample Form and sample output:

Room Capacity Single

Room Type

Rate/day

Regular 100.00 De Luxe 300.00 Suite 500.00 Regular 200.00 Problem: Double De Luxe 500.00 Compute for Total Amount based on the date of Suite 800.00 check-in and check-out. Regular 500.00 Family SelectLuxe capacity, 750.00 and payment room type De room type before clicking Compute button otherwise, will Suite 1,000.00 prompt you with No selected room capacity or No selected room type or No selected type of payment 57
PLP College of Computer Studies

Type of Payment Cash Check Credit Card

Additional Charge No addl charge + 5% + 10%

- rct- 6/06

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

d)

58
PLP College of Computer Studies
- rct- 6/06

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 For counter=1 to 1000 step 10 counter = counter + 1 Next For counter = 1000 to 5 step -5 counter = counter - 10 Next

(b)

(c)

59
PLP College of Computer Studies
- rct- 6/06

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 grade Public 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
60
PLP College of Computer Studies
- rct- 6/06

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 compute Private Sub compute_Click() grading.Caption = grade(mark) End Sub Procedure end to close the application Private Sub End_Click() End End Sub

61
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Name : ____________________________ Date Finished : _____________ Section: _________ Time: ________ Instructor : ____________________________ Practice Exercise #8: Password Entry
Project Name Form Name : PEPJT03<FirstNameLastName> : PE07FRM02<FirstNameLastName> Example: PEPJT03RichardGwapo Example: PE07FRM02RichardGwapo

Rating:

Form 1: Password Entry


Specs: TextBox Name: txtPassword CommandButton Name: cmdAccept Then, will display Form 1 after clicking on OK button (Sample Program above) 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 the password is correct

Display this message box if you failed to enter the password correctly (three (3) attempts only) Click OK: to quits the application/program.

62
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Source Codes: cmdAccept Event: Private Sub cmdAccept_Click() Dim Ans As Integer Static 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

63
PLP College of Computer Studies
- rct- 6/06

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 Form Name : MPPJT05<FirstNameLastName> : MP08FRM01<FirstNameLastName> Example: MPPJT05RichardGwapo Example: MP08FRM01RichardGwapo

PROJECT #5: FORMS: SAMPLE FORM LAYOUT Upon running the program displays the 1st form, which is the PASSWORD ENTRY FORM 1:

Richard Gwapo *****

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 Help Sub 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)

64
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


FORM 3:

3rd Form: (Transaction Form)

User Name:

Railee Darrel

<Insert Date & Time here>

Appliances/Items Unit Price Electric Fan 500.00 Refrigerator 9,000.00 Washing Machine 4,000.00 Oven Toaster 550.00 Flat Iron 350.00 VCD Player 1,200.00 Mini Component 3,500.00

Appliances/Items Unit Price Television 5,000.00 Air Conditioner 10,000.00 Rice Cooker 600.00 Electric Stove 1,000.00 Electric Pot 800.00 Karaoke 2,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 button If Compute button is clicked; for CASH Total Amount = Sub-total less 5% discount

65
PLP College of Computer Studies
- rct- 6/06

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0

Lecture and Laboratory Exercises


Output: For Cash Payment
User Name: Richard Gwapo <Insert Date & Time here>

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.

User Name:

Richard Gwapo

<Insert Date & Time here>

66
PLP College of Computer Studies
- rct- 6/06

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.

67
PLP College of Computer Studies
- rct- 6/06

Вам также может понравиться