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 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. and the current Form. variable declarations and constant definitions used by application. 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 toolbar has buttons that provide shortcuts to some of the menus options. It is where you draw your application.6/‘06 . and toolbar. 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. The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. menu bar.  The Main Window consists of the title bar.0 Lecture and Laboratory Exercises Modules – Collection of general procedures. • Six windows appear when you start Visual Basic.  The Form Window is central to developing Visual Basic applications. the current Visual Basic operating mode. • Design mode – used to build application • Run mode – used to run the application • Break mode – application halted and debugger is available. (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. The Title bar indicates the project name. 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.

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 .

The user can specify data by typing it or by selecting a value from a list.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 .rct. Can also provide an analog representation of a current position Same as a horizontal scroll bar. only it is displayed vertically. Provides a list drive paths and directories.Object Oriented Programming 1: Using Microsoft Visual Basic 6. Triggers an event when a specified time period elapses. Similar to the Picture Box. but easier to use. 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. Provides a data link with an Object Linking and Embedding compliant application . enabling the user to select one. This control is typically used to enable the user to select from mutually exclusive options.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. it can display graphic images. Support database compatibility with programs such as Microsoft Access. A two-dimensional tool for drawing straight lines. enabling the user to select one Provides a list of files. A two-dimensional tool for drawing shapes. Provides a list of available disk drives and enables the user to select one. Combines the features of a text box and list box. Displays text that the user can modify at Run Time A container that groups other controls such as radio buttons or check boxes. An option button can be turned off or on by clicking the option button with the mouse. 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.

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

the shape control is placed in the form together with six Option Boxes. its value is set to “True” and when it is unselected. its value is set to “False”.rct.6/‘06 . an oval shape.Shape = 2 End Sub Private Sub Option4_Click() Shape1. However. Example: Private Sub Option1_Click ( ) Shape1. different shapes will appear. 1. In the following example.Shape = 0 End Sub Private Sub Option2_Click() Shape1. two or more Option Boxes must work together because as one of the Option Boxes is selected.Then…. a square.Value = 0 Then Form1.Shape = 1 End Sub Private Sub Option3_Click() Shape1. When the user clicks on different option boxes.Value = 1 Then Form1. and 2. the other Option Boxes will be unselected.Object Oriented Programming 1: Using Microsoft Visual Basic 6.BackColor = vbBlue End If End Sub The Option Box  The Option Box control also lets the user selects one of the choices.4 which will make it appear as a rectangle. and a rounded square respectively.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. The values of the shape control are 0.BackColor = vbRed ElseIf Check1. In fact. When an option box is selected.Shape = 3 End Sub Private Sub Option5_Click() Shape1.0 Lecture and Laboratory Exercises  You will learn about the conditional statement If….3.Shape = 4 End Sub The Drive List Box 10 PLP – College of Computer Studies . only one Option Box can be selected at one time.

Two views are available. you will be able to select different drives from your computer as shown in Figure 6. 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.rct.0 Lecture and Laboratory Exercises  The Drive ListBox is used to display a list of drives available in your computer. . The drop-down List 11 PLP – College of Computer Studies . When you place this control into the form and run the program. 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.Object Oriented Programming 1: Using Microsoft Visual Basic 6.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. When you place this control into the form and run the program.

0 Lecture and Laboratory Exercises Alphabetic and Categorized.Object Oriented Programming 1: Using Microsoft Visual Basic 6. 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 monitor’s screen. 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 .6/‘06 . Under this box are the available properties for the currently selected object.rct. Figure 9: Form Layout Window  The Project Window displays a list of all Forms and modules making up your application.

6/‘06 .rct.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 .Object Oriented Programming 1: Using Microsoft Visual Basic 6.

Note: To RUN/EXECUTE the program/application  Click on Run menu then. It is also known as the Code Editor Window.Object Oriented Programming 1: Using Microsoft Visual Basic 6. Click Save button Then. displayed Save Project As dialog box Type the project name (follow the PEPJT01RICHARDGWAPO 4. 5. 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. displayed Save File As dialog box 3.rct. Click Save button 7. 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. Then. both allow you to choose either the Form or one of the controls on the Form. It contains an: o Object box – performs the same function as the Object box in the Properties window. 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.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.6/‘06 .OR  Press F5 function key OR  Click Start button 14 PLP – College of Computer Studies . click Start .

rct.6/‘06 .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 .Object Oriented Programming 1: Using Microsoft Visual Basic 6.

4. Font Size. Figure 3: Sample Form Interface 16 PLP – College of Computer Studies . displays Form Window as shown below (see figure 2) Figure 1: New Project Window Figure 2: Form Window 3. 5. Changing Caption etc. 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. Click Open button  Then. Font Color.Object Oriented Programming 1: Using Microsoft Visual Basic 6.rct.6/‘06 . Launch Visual Basic application/program.  Displays New Project as shown (see figure 1)  Be sure that Standard EXE is being selected 2.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.

4.rct. Exercise project 1) 2. 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 you’re application:  Click <View> menu then <Code> OR select View Code button project explorer window OR double click the Test Button  Then.Object Oriented Programming 1: Using Microsoft Visual Basic 6. 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.6/‘06 . 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 . from Figure 2: Form2 with Label1 & Command1 controls Object Procedure Figure 4: Code Window of Form2 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. 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. 3.

rct.6/‘06 .0 Lecture and Laboratory Exercises 18 PLP – College of Computer Studies .Object Oriented Programming 1: Using Microsoft Visual Basic 6.

Note: . click OK button Try to run the program and see the output : (see Figure 9) 8. 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. Save and Run the program to test the output.In object programming.Object Oriented Programming 1: Using Microsoft Visual Basic 6. Figure 9: Output of Form2 Figure 8: Project Properties Window 9.The message is enclosed with double quotation marks (“ “) because the text is a string constant. 11. 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. o Click <Project> menu then click <Project Properties> then. Then. Select Click and type the procedure/code as shown (see Figure 11) Figure10: Code Window for Form object 10.rct. .  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 . the access to method and properties is done by joining the name of the object and the property (or method) with a dot.6/‘06 . Form1 will always be the Form to be executed.  Note: Before running the program you need to change the project properties to run Form2 otherwise.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.

6/‘06 .Object Oriented Programming 1: Using Microsoft Visual Basic 6.rct.  Save and run the program/application to test the output Try to enhance the Form by changing some object properties.0 Lecture and Laboratory Exercises MsgBox – Text Message To be displayed. 12. 20 PLP – College of Computer Studies .

6/‘06 .Object Oriented Programming 1: Using Microsoft Visual Basic 6. we can use the STR( ) and VAL( ) functions. Finally. For example. we can concatenate two strings or add two numbers but we cannot add or concatenate a string and a number.Caption = yourName End Sub In this example Program Listing 3. except for + and -. we need to use various mathematical operators. three variables are declared as string. Both values can be manipulated separately. yourName is displayed on Label1. 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. the symbols for the operators are different from normal mathematical operators.  In many occasions. Type Conversions  Values are classified as either String or Numeric. we need to convert a string format to numeric format for computation and a numeric format to string format for manipulation. To do this. 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. STR( ) – converts a number to string VAL( ) – converts a string to number 21 PLP – College of Computer Studies . In Visual Basic.0 Lecture and Laboratory Exercises Operators in Visual Basic In order to compute inputs from users and to generate results.rct.Text secondName = Text2.Text yourName = secondName + " " + firstName Label1.

6/‘06 .Text) Total=number1+number2+number3 Average=Total/5 Label1.rct. three variables are declared as integer and two variables are declared as variant. number3 as Integer Dim total.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.Text) number2=val(Text2. The program computes the total and average of the three numbers that are entered into three text boxes.Text) number3= val(Text3. average as variant Private sub Form_Click( ) number1=val(Text1.Caption=Average End Sub In the Program Listing 4. number2.Caption=Total Label2. 22 PLP – College of Computer Studies . Variant means the variable can hold any numeric data type.

Caption = "Welcome! " + txtMyName.Text + " " + txtYourName. 5. 9.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.Caption = Val(txtMyAge. type the following line of codes. 2.rct.          : 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.Text End Sub 7.Object Oriented Programming 1: Using Microsoft Visual Basic 6. cmdOurName Event: Private Sub cmdOurName_Click() ' Displaying "Welcome MyName and YourName value" lblOurName. Double Click NAME button then. 4.Text) + Val(txtYourAge. 3. 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 . type the following line of codes. Figure 1: Sample Layout/Interface Note:  6.6/‘06 .Text) End Sub 8. cmdSumAge Event: Private Sub cmdSumAge_Click() ' Displaying MyAge and YourAge lblSumAge. Double Click SUM button then.

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.

4. 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 . 3. 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.rct.6/‘06 .Object Oriented Programming 1: Using Microsoft Visual Basic 6. 2. 5.

6/‘06 26 PLP – College of Computer Studies . Name: txtArg2 3.Object Oriented Programming 1: Using Microsoft Visual Basic 6.rct. Name: txtArg1 2. 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.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. Example: You type Effect: &Clear Clear .

0 Lecture and Laboratory Exercises E&xit Exit 27 PLP – College of Computer Studies .6/‘06 .Object Oriented Programming 1: Using Microsoft Visual Basic 6.rct.

402823E+38 to -1.264. In Visual Basic.6/‘06 .9228162514264337593543950335 (28 decimal places). For example. Currency 8 bytes Decimal 12 bytes -922. addresses.593.483.401298E-45 to 3.162.203. stock quotes.94065645841247E-324 to 1.337. we are also going to deal with these kinds of data. we need to handle data such as names. we need to add a suffix behind a literal so that VB can handle the calculation more accurately.rct.0 Lecture and Laboratory Exercises Visual Basic Data Types There are many types of data we come across in our daily life.400 characters 0 to 2 billion characters January 1.337.5808 to 922.Object Oriented Programming 1: Using Microsoft Visual Basic 6. For example.401298E-45 for negative values 1.79.79769313486232e+308 to -4. money. VB divides data into different types.477.94065645841247E-324 for negative values 4. the numeric data are divided into 7 types.685. -1.337.147.685. 28 PLP – College of Computer Studies . minus.3089# for a Double type data.335 if no decimal is use +/.5807 +/.768 to 32.950. 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.767 -2.  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. statistics and etc everyday. However. Similarly in Visual Basic.7.543.  Numeric Data Numeric data are data that consists of numbers. date.228. 100 to December 31.203. to be more systematic. which can be computed mathematically with various standard operators such as add.79769313486232e+308 for positive values. we can use num=1. In some cases. divide and so on.514.648 -3. 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.648 to 2.477.147. multiply.483.402823E+38 for positive values.

these information are stored because they expect to be processed or be used as an element in a process. See figure 12.6/‘06 . See figure below. 29 PLP – College of Computer Studies . including numbers. Strings can contain any characters.rct. Examples: memberName="Turban.  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.Object Oriented Programming 1: Using Microsoft Visual Basic 6." 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. 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. Variable is a temporary repository of information. Local variables to a procedure are declared at the start of a procedure and can be used only in that procedure. Usually. can be defined at the Declaration section of the General object found in the code window.0 Lecture and Laboratory Exercises Suffix & ! # @ Data Type Long Single Double Currency In addition. on the other hand. 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. John. Local variables to the whole Form. we need to enclose string literals within two quotations and date and time literals within two # sign.

0 Lecture and Laboratory Exercises Loc al Variables Figure 12: Variable Declaration Managing Variables  Variables are like mail boxes in the post office. each variable must be given a name. Private for a Module. The contents of the variables changes every now and then. Local for the entire Form. just like the mail boxes. The reserve word Const is use to declare a constant see Figure 13. you have to follow a set of rules.6/‘06 . and Public for the whole project. In term of VB. Figure 13: Constant Variable Declarations Examples: Valid and Invalid Variable Names Valid Name My_Variable ThisDate Long_Name_Can_beUSE Invalid Name My.rct. Like the mail boxes. constants can be Local for a specific procedure.Object Oriented Programming 1: Using Microsoft Visual Basic 6. To name a variable in Visual Basic. Constant Refers to fixed values.Variable 7Day Mine&Yours *& is not acceptable 30 PLP – College of Computer Studies . Like variable. variables are areas allocated by the computer memory to hold data.

These arguments and values are constant numerical data and difficult to interpret based on just the numerical value...rct.) Example: Dim yourName as String * 10 ‘yourName can holds no more than 10 Characters. you have to use the Format: Dim VariableName as String * n... 31 PLP – College of Computer Studies ..BackColor = 0XFF0000 frmExample.6/‘06 .1 above.Object Oriented Programming 1: Using Microsoft Visual Basic 6. as follows: Example: Dim password As String. Example: frmExample. one needs to declare the variables before using them by assigning names and data types.. For the variable-length string. firstnum As Integer. for the fixed-length string. functions and objects require data arguments that affect their operation and return values you want to read and interpret. For string declaration. just use the same format as example 5.0 Lecture and Laboratory Exercises Visual Basic Symbolic Constants  Many times Visual Basic. separating each variable with a comma..  If data type is not specified. However.. one for the variable-length string and another for the fixed-length string... Visual Basic assigns names to the most widely used values – these are called symbolic constants.BackColor = vbBlue Declaring Variables  In Visual Basic.. there are two possible formats. 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 .. VB will automatically declare the variable as a Variant. yourName As String. They are normally declared in the general section of the codes' windows using the Dim statement. To make these constants more understandable.. (where n defines the number of characters the string can hold.

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.Text ThirdNumber = Val(usernum1. we can assign values to those variables.Text = password Label1.Visible = True Command1.Object Oriented Programming 1: Using Microsoft Visual Basic 6. The expression could be a mathematical expression.0 Lecture and Laboratory Exercises Working with Variables Assigning Values to Variables  After declaring various variables using the Dim statements. 32 PLP – College of Computer Studies .6/‘06 . Examples: firstNumber=100 secondNumber=firstNumber-99 userName="John Lyan" userpass.Caption = textbox1. a Boolean value (true or false) and etc. a string.Text) total = firstNumber + secondNumber+ThirdNumber Visual Basic Functions Visual Basic offers a rich assortment of built-in functions.rct.Visible = false Label4. a number. The general format of an assignment is Variable=Expression  The variable can be a declared variable or a control property value.

To roll a six-sided die. the number of spots would be computed using: Answer: NumberSpots = Int(6 * Rnd) + 1 2. The Randomize statement is used to do this: Randomize Seed  If you use the same Seed each time your run your application.Object Oriented Programming 1: Using Microsoft Visual Basic 6. random numbers between 0 and 1 (actually greater than or equal to 0 and less than 1). we use the Rnd funtion to introduce randomess.6/‘06 . use: Answer: Number = Int(100 * Rnd) + 100 33 PLP – College of Computer Studies . To produce random integers (I) between Imin and Imax. 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. This ensures different results each time you try a program.0 Lecture and Laboratory Exercises Rnd Function  In writing games and learning software.rct. The Visual Basic function Rnd returns a single precision. the same sequence of random numbers will be generated. use the formula: I = Int(Imax – Imin + 1) * Rnd) + Imin  The random number generator in Visual Basic must be seeded. To randomly choose a number between 100 and 200. A seed value initializes the generator.

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. 2. 3. 6. Or select View Code from the project window.Object Oriented Programming 1: Using Microsoft Visual Basic 6.6/‘06 . (See Figure 2: Modified form properties) Stopwatch Application – Attaching Code Double click anywhere on the form to open the code window. Select specific object then type the following line of codes.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. Figure 3: Sample Run (Output) 34 PLP – College of Computer Studies .rct. 5.

"hh:mm:ss") lblEnd. EndTime & ElapsedTime as variables global within the form. compute the elapsed time 'Put both values in label boxes EndTime = Now ElapsedTime = EndTime . ‘Declaration of StartTime. "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 .Caption = Format(EndTime.Object Oriented Programming 1: Using Microsoft Visual Basic 6. "hh:mm:ss") lblElapsed.StartTime lblEnd.6/‘06 .Caption = "" lblElapsed.rct. 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 = "" End Sub cmdEnd Event Private Sub cmdEnd_Click() 'Find the ending time.Caption = Format(ElapsedTime.Caption = Format(StartTime.0 Lecture and Laboratory Exercises General Declaration Option Explicit ‘This statement forces us to declare variables.

3.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.6/‘06 . 2. 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.

Object Oriented Programming 1: Using Microsoft Visual Basic 6.0 Lecture and Laboratory Exercises 4.Caption = Format(Today. "d") lblTime. "yyyy") lblNumber. "mmmm") lblYear.Caption = Format(Today. "dddd") lblMonth.rct.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 . Source Codes: General Declaration Option Explicit timDisplay Event Private Sub timDisplay_Timer() Dim Today As Variant Today = Now lblDay.6/‘06 .Caption = Format(Today.Caption = Format(Today.

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. there are certain rules to follows: Upper case letters are less than lowercase letters.<"Z" and number are less than letters. we can use various conditional operators. whether to execute a program or terminate the program and etc..Object Oriented Programming 1: Using Microsoft Visual Basic 6. "A"<"B"<"C"<"D"..rct.6/‘06 . they let the VB program compare data values and then decide what action to take... However. they resemble mathematical operators.. Logical Operators  In addition to conditional operators. Basically.. Conditional operators are very powerful tools. 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 . there are a few logical operators which offer added power to the VB programs.0 Lecture and Laboratory Exercises Controlling Program Flow Six Comparison/Relational/Conditional Operators  To control the VB program flow.

..Text) <> 0 Then correct.Else statement must end with End If.Visible = True wrong.Text) total = Val(sum.. we shall use If..Else statement together with the conditional operators and logical operators.. Format: if.6/‘06 .Object Oriented Programming 1: Using Microsoft Visual Basic 6.Text) If total = firstnum + secondnum And Val(sum.Visible = True End If End Sub 39 PLP – College of Computer Studies .0 Lecture and Laboratory Exercises Conditional Statement / Selective Structure If.Else Statements  To effectively control the VB program flow.else statement is : If conditions Then VB expressions Else VB expressions End If Note:  any If..Text) secondnum = Val(usernum2.Then..Visible = False Else correct.Then... Sometime it is not necessary to use Else...rct.Then.Visible = False wrong..then... Program Listing 4: Example of Conditional Statement Private Sub OK_Click() firstnum = Val(usernum1.

. 40 PLP – College of Computer Studies .6/‘06 . For multiple conditional statements. using If.rct.Then.Text Select Case grade Case "A" result. 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 .Caption="High Distinction" Case "A-" result. Case Else Block of one or more VB Statements End Select Note:  The data type specified in expression must match that of Case values.Caption="Distinction" Case "B" result.Caption="Fail" End Select End sub Note:  Please note that grade is a string.Else could be very messy. . Program Listing 5: Example of Selective Structure 1 'Examination Grades Dim grade As String Private Sub Compute_Click( ) grade=txtgrade.0 Lecture and Laboratory Exercises Select Case  If you have a lot of conditional statements. so all the case values such as "A" are of String data type.Caption="Credit" Case "C" result.Caption="Pass" Case Else result..Object Oriented Programming 1: Using Microsoft Visual Basic 6.

Caption = "Good" Case Is >= 60 comment.Caption = "Above Average" Case Is >= 50 comment. 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.Object Oriented Programming 1: Using Microsoft Visual Basic 6.rct.Text Select Case mark Case 0 to 49 comment.Caption = "Excellence" End Select End Sub 41 PLP – College of Computer Studies .Caption = "Above Average" Case 70 to 84 comment.Caption = "Need to work harder" End Select End Sub Note  we use the keyword Is here to impose the conditions.Caption = "Average" Case 60 to 69 comment.Caption = "Good" Case Else comment.Caption = "Need to work harder" Case 50 to 59 comment.Text Select Case mark Case Is >= 85 comment.Caption = "Excellence" Case Is >= 70 comment.6/‘06 .Caption = "Average" Case Else comment.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.

6/‘06 .Caption = Format(Num2. "#0") lblNum3. "#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 .Caption = Format(Num3.Object Oriented Programming 1: Using Microsoft Visual Basic 6.Caption = Format(Num1.rct. "#0") lblNum2.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: 7 7 7 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.

The consolation prizes will depend to the BET amount (Example: Bet is 100. 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 ____”.00” 2. Enter single digits for each of the text box 3. otherwise it will prompt you with “Sorry better luck next time” 4.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.6/‘06 . otherwise it will prompt you with “Enter minimum amount of Php 10.000. But.Object Oriented Programming 1: Using Microsoft Visual Basic 6.00 to get the consolation amount. Your bet should not be less than 10 pesos.) 43 PLP – College of Computer Studies . 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).rct. multiply your bet to 1.

25 2.75 86 – 88 2.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.Object Oriented Programming 1: Using Microsoft Visual Basic 6.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 .00 5.75 3. Grade 83 – 85 80 – 82 77 – 79 75 – 76 74 & below Equivalent 2.6/‘06 • • .50 89 – 91 1.00 Sem. Grade Equivalent 98 – 100 1.50 2.00 95 – 97 1.25 92 – 94 1.rct.

Argumentlist The variables or expression to pass to another procedure. Prompt . 45 PLP – College of Computer Studies . They are two types of function.e. i. Style Value. The general format of a function is: functionName(arguments)   where arguments are values that are passed on to the functions. 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. 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. 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.Object Oriented Programming 1: Using Microsoft Visual Basic 6. This message box format is as follows: yourMsg=MsgBox(Prompt.6/‘06 . Title)    The first argument. The Style Value will determine what type of command buttons appear on the message box. You can also use the optional call statement. you can simply place the procedure name in code.rct.0 Lecture and Laboratory Exercises The Call Statement  To call another procedure. In this lesson. we are going to learn two very basic but useful internal functions. The Title argument will display the title of the message board.will display the message in the message box. the built-in functions(or internal functions) and the functions created by the programmers.

Object Oriented Programming 1: Using Microsoft Visual Basic 6. Retry and Ignore buttons. It has to be declared as Integer data type in the procedure or in the general declaration section. 1. 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."Startup Menu") are the same. In fact.6/‘06 . "Startup Menu") and yourMsg=Msg("Click OK to Proceed".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. The values are determined by the type of buttons being clicked by the users. vbOkCancel.rct.  yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. Yes. VB6 will automatically shows up a list of names constant where you can select one of them. 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 . Example: yourMsg=MsgBox( "Click OK to Proceed".

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. 1. Program Listing 8: The procedure for the test button: Private Sub Test_Click() Dim testmsg As Integer testmsg = MsgBox("Click to test".rct.6/‘06 . Figure 15: Test Message o To make the message box looks more sophisticated.Caption = "Testing fail" End If End Sub Note:  When a user click on the test button. "Test message") If testmsg = 1 Then Display. the message "Testing fail" will be displayed. you can add an icon besides the message.Caption = "Testing Successful" Else Display. As the user click on the OK button. 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 . the message "Testing successful" will be displayed and when he/ she clicks on the Cancel button. the image like the one shown in Figure 15 will appear.

vbYesNoCancel + vbExclamation.Caption = "Testing successful" ElseIf testMsg2 = 7 Then display2.rct. Format: myMessage=InputBox(Prompt. default_text.6/‘06 PLP – College of Computer Studies . "Test Message") If testMsg2 = 6 Then display2. o default-text . y-position) Where:  myMessage .Caption = "Are you sure?" Else display2. x-position.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.0 Lecture and Laboratory Exercises In this example. 48 . 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.The title of the Input Box. No & Cancel button Private Sub test2_Click() Dim testMsg2 As Integer testMsg2 = MsgBox("Click to Test". Title.The message displayed normally as a question asked.Object Oriented Programming 1: Using Microsoft Visual Basic 6. but modify the codes as follows: Program Listing 9: Example of MsgBox with Yes. which accept the message input by the users. o Title . The arguments are explained as follows: o Prompt .the position or the coordinate of the input box.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.is a variant data type but typically it is declared as string. o x-position and y-position .

6/‘06 . 700) If userMsg <> "" Then message.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?".Caption = userMsg Else message. "No message" will be displayed.Object Oriented Programming 1: Using Microsoft Visual Basic 6. the message will be displayed on the caption. Figure 18: InputBox for Message Entry Form 49 PLP – College of Computer Studies .rct. if he click Cancel. "Enter your message here".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. "Message Entry Form". After user entering the message and click OK. 500.

.Object Oriented Programming 1: Using Microsoft Visual Basic 6.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. 2.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. 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 .

Object Oriented Programming 1: Using Microsoft Visual Basic 6.rct. [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 .6/‘06 .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.

"#0") 'Find sum Sum = Number1 + Number2 cmdNext.Caption = Format(Number2.rct.SetFocus Else KeyAscii = 0 End If End Sub 52 PLP – College of Computer Studies .Text = "" lblMessage.Caption = "That's correct!" Else lblMessage.Caption = Format(100 * NumRight / NumProb.6/‘06 . "##0") cmdNext. "#0") End If lblScore.0 Lecture and Laboratory Exercises 'Generate next addition problem Dim Number1 As Integer Dim Number2 As Integer txtAnswer. "#0") lblNum2.Enabled = False txtAnswer.Object Oriented Programming 1: Using Microsoft Visual Basic 6.Caption = "Answer is " + Format(Sum.Caption = "" NumProb = NumProb + 1 'Generate random numbers for addends Number1 = Int(Rnd * 21) Number2 = Int(Rnd * 21) lblNum1.Enabled = True cmdNext.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 = Format(Number1.

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 .

54 PLP – College of Computer Studies .00 Extra Toppings: Plus Php 10.00 Crust Type: Thin Crust – same as size prices Thick Crust – Plus 50% of size prices Drinks: Soft Drinks – Php 20.00 per extra toppings Build Pizza Button: will display message box Your Pizza (see sample above) Clear Toppings Button: will uncheck all check boxes.00 Fruit Juice – 15.00 Large – 200.00 Medium – 150.Object Oriented Programming 1: Using Microsoft Visual Basic 6.6/‘06 .rct.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. Compute Button: will display all values under Amount frame Clear All Button: will clear all entries Exit Button: will close the program.00 Coffee/Chocolate 25.

999 3% below 1.00 B 400.00 Civil Status Single Married Widowed Rate 10% 5% 5% Basic Pay SSS Rate 10. SSS Contribution.000 – 4. For Compute Button.000 1% Basic Pay = No.rct. 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.999 5% 1. Withholding Tax and Net Pay 55 PLP – College of Computer Studies . will compute the Basic Pay.Object Oriented Programming 1: Using Microsoft Visual Basic 6.000 & above 7% 5.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. it will automatically display the Employee Name.6/‘06 .000 – 9.00 C 300.

56 PLP – College of Computer Studies .Object Oriented Programming 1: Using Microsoft Visual Basic 6. will clear all entries For Quit Button. will close the program/application.rct.0 Lecture and Laboratory Exercises • • For Clear Button.6/‘06 .

00 Problem: Double De Luxe 500.00 and payment room type De room type before clicking Compute button otherwise.000. will Suite 1.6/‘06 .00 Regular 200.rct. Regular 500.00 check-in and check-out.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 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 add’l charge + 5% + 10% .00 Suite 500. 750.00 •Family SelectLuxe capacity.00 De Luxe 300.Object Oriented Programming 1: Using Microsoft Visual Basic 6.00 • Compute for Total Amount based on the date of Suite 800.

Object Oriented Programming 1: Using Microsoft Visual Basic 6.  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 . This is generally called looping .rct. 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.6/‘06 .0 Lecture and Laboratory Exercises Looping Visual Basic allows a procedure to be repeated as many times as long as the processor could support.Text=counter counter =counter+1 Loop Note:  The above example will keep on adding until counter >1000.

.6/‘06 .rct..10 Next (b) (c) 59 PLP – College of Computer Studies .Next Loop Format: For counter=startNumber to endNumber (Step increment) One or more VB statements Next Example: (a) For counter = 1 to 10 display..0 Lecture and Laboratory Exercises For.Object Oriented Programming 1: Using Microsoft Visual Basic 6.Text =counter Next For counter=1 to 1000 step 10 counter = counter + 1 Next For counter = 1000 to 5 step -5 counter = counter .

... Example: The following program will automatically compute examination grades based on the marks that a student obtained......) As dataType or Function functionName (Arg As dataType.6/‘06 ..Object Oriented Programming 1: Using Microsoft Visual Basic 6..rct. 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 .) 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...0 Lecture and Laboratory Exercises Introduction to VB Functions II Creating Your Own Functions Format: Public Function functionName (Arg As dataType.........

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 grade = "D" Case Is >= 40 grade = "E" Case Else grade = "F" End Select End Function ‘Procedure compute Private Sub compute_Click() grading.

6/‘06 .Object Oriented Programming 1: Using Microsoft Visual Basic 6. 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 . 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.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.rct.

. vbCritical + vbOKOnly.. vbQuestion + vbRetryCancel.6/‘06 . "Password Entry" Unload Me Form3..Object Oriented Programming 1: Using Microsoft Visual Basic 6.Try Again.".SetFocus End Sub 63 PLP – College of Computer Studies .. "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 If Trial = 2 Then MsgBox "Intruder!. "Password Entry") If Ans = vbRetry Then txtPassword....Text = "" txtPassword.Show Else Ans = MsgBox("Invalid Password...0 Lecture and Laboratory Exercises Source Codes: cmdAccept Event: Private Sub cmdAccept_Click() Dim Ans As Integer Static Trial As Integer If txtPassword.". vbInformation..".Text = "gwapo" Then MsgBox "Password Accepted.rct.

Close & Compute are all in disabled layout (as shown below) <File> <Exit>. BUTTONS: New.Object Oriented Programming 1: Using Microsoft Visual Basic 6.6/‘06 .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.rct. 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>. displays 3rd Form: (as shown below) 64 PLP – College of Computer Studies . 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. will close the program If Transaction is clicked. which is the PASSWORD ENTRY FORM 1: Richard Gwapo ***** Note: No limit for password. Clear. will display the Transaction Form: For TRANSACTION Form: Initially.

Unit Price: 500.500.00 VCD Player 1.00 Microwave Oven 3.  Amount Text Box will be based on the Appliance Unit Price * Quantity Example: Appliance Sold: Electric Fan.200.6/‘06 .000.Object Oriented Programming 1: Using Microsoft Visual Basic 6.00 Appliances/Items Unit Price Television 5.00 Washing Machine 4.00 Electric Pot 800.00 Oven Toaster 550.0 Lecture and Laboratory Exercises FORM 3: 3rd Form: (Transaction Form) User Name: Railee Darrel <Insert Date & Time here> 0 Appliances/Items Unit Price Electric Fan 500. Example: Appliance Sold: Air Conditioner 10.00 Refrigerator 9.00 Air Conditioner 10.500. for CASH Total Amount = Sub-total less 5% discount 65 PLP – College of Computer Studies .00 Electric Stove 1.000.00 Flat Iron 350.00 X 2 (see example below).000.  Choose Type of Payment: Cash or Charge then.00 Mini Component 3.rct. Quantity: 2 (see example below)  Sub-total Text Box will be based on the total item sold. will enable Compute button If Compute button is clicked.000.000.00 X 1 and Electric Fan 500.00 Karaoke 2.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.00 Rice Cooker 600.000.

Object Oriented Programming 1: Using Microsoft Visual Basic 6. New. Clear & Close Enter value for Amount Tendered: Amount Tendered should be exact amount or should be greater than Total Amount otherwise. For New button. for CHARGE Total Amount = Sub-total + 5% additional charge For Close button. will clear all entries For Clear button. will prompt the user to enter valid amount. If Compute button is clicked. Click Change button to display the amount change. User Name: Richard Gwapo <Insert Date & Time here> 2 66 PLP – College of Computer Studies . will enable buttons.6/‘06 .rct. Unit Price and Type of Payment only. Appliance Sold. Output: For Charge Payment. will close the transaction window only.0 Lecture and Laboratory Exercises Output: For Cash Payment User Name: Richard Gwapo <Insert Date & Time here> 2        Then. will Quantity.

rct. 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.Object Oriented Programming 1: Using Microsoft Visual Basic 6.6/‘06 . If button AUTHOR is clicked will display message group members/programmers. will display a Form “About the program” If button OK is clicked will close the form window. 67 PLP – College of Computer Studies .0 Lecture and Laboratory Exercises  Then.

Sign up to vote on this title
UsefulNot useful