You are on page 1of 14

VB Notes summary

INTRODUCTION
Visual Language
Visual Language aims at providing the user with an interface that is easy to use. In developing
such an interface the programmer employs user-friendly feature such as windows, menus, buttons
etc.
A Visual Language environment provides all features that are required to develop a graphical user
interlace as ready to use components. The programmer does not have to write code to create a
display commonly required user-friendly features such as buttons, menus. Typically, the mouse is
used to select and place the necessary components on the form, thus, the visual programming
environment is also called a point and check environment.
The visual programming also provides a means of associating code with each component.
Advantages of Visual Language
• Visual developments are of graphical user interfaces, which arc easy to use and easy to
learn.
• A programmer need not to write code to display the required component,
• The components can be moved resized and even deleted if so required.
• A list of available components is displayed where a programmer picks up the required
components from this list.
Disadvantages of Visual Programming
• Visual development environment is highly graphical in nature and therefore requires more
memory.
• For visual program to run, it requires computer of higher configuration.
Examples Visual Language
I. Visual basic
2. Small talk
3. Delphi
4. Visual Cobol
S. Developer 2000

• What is Visual Basic?


Visual Basic is a tool that allows you to develop Windows (Graphic User interface - GUI)
applications. The applications have a familiar appearance to the user.
In visual basic codes are not written in designing an interface such as command buttons or
listbox, therefore this type of development gives ability to quickly design an interface.
VB provides programmers with a complete set of tools to simplify rapid Application Development.
Visual — it refers to the method used to create a graphical user interlace (GUI).
Basic — it refers to the basic language, a language used by more programmers than any other
language in the history of programming
B — Beginners
A — All-purpose
S — Symbolic
I — Instruction
C — Code

Visual Basic is event driven meaning code remains idle until called 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

Event
Basic Basic Basic
Procedures
Code Code Code

Integrated Development Environment (IDE)


Visual basic is an integrated system in which designing an interface, editing codes, compiling,
Linking, executing and debugging are performed by a single software package called the
integrated Development environment (IDE)
1 Prepared by Isaq
VB Notes summary

Structure of a Visual Basic Application


Application (Project) is made up of:
Forms: Windows that you create (or User interface
Controls: Graphical features drawn on forms to allow user interaction (text boxes, labels, scroll
bars, command buttons etc) (Forms and Controls are objects)
Properties: Every characteristic 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 runtime.
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
event occurs.
General procedures: Code not related to objects. This code must be invoked by the application.
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
1 Draw the user interface
2. Assign properties to controls (Setting Properties)
3. Attach code to controls

Creating an interface
Creating user interface is the most important part of an application; the usability of an
application depends on the interface. To users the interface is the application as they are not
aware of the code behind the success of an executable application.
Visual basic makes it easy to create a user interface by either double clicking the control or
dragging the control on to a form.
Visual Basic operation modes
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
Setting Properties
Properties of object can be set either at;
(i) Design Time or (ii) Run Time

Setting Properties of Objects at Design Time


Each form and control has properties assigned to it by default when you start up a new project.
There are two ways to display the properties of an object. The first way is to click on the object
(Form or control) in the form window. Then, click on the Properties Window or the Properties
Window button in the tool bar. The second way is to first click on the Properties Window. Then,
Select the object front the Object box in the Properties Window
The drop-down box at the top of the Properties Window is the Object box. It displays the name of
each object in the application as well as its type. The Properties list is directly below this box. In
this list, one can scroll through the list of properties for the selected object. Also may select a
property by clicking on it. Properties can be changed by typing a new value or choosing front a
list of predefined settings (available as a drop down list). Properties can be viewed in two ways:
alphabetic and Categorized.
A very important property for each object is its Name. The name is used by Visual Basic to refer
to a particular object in code.

Setting Properties at Run Time


Programmers can also set or modify properties while the application is running. To do this, you
must write some code. The code format is: -
ObjectName.Property=New Value
Such a format is referred to as dot notation. For example, to change the BackColor properly of a
form name frmStart, we’d type:
frmStart.BackColor=BLUE
2 Prepared by Isaq
VB Notes summary

Attach code to the event/write code


Once you have designed forms and set properties, you are ready to add code to your application.
You enter program statements (codes) in the Code window, a special text-editing window
designed specifically for Visual Basic program code. You can display the Code window:
* By clicking View Code in the Project window.
* By clicking the View menu Code command.
* By double clicking the object (form or control)

Event
An action recognized by an object, such as clicking the mouse or pressing a key, and for which
you can write code to respond. Events can occur as a result of a user action or program code, or
they can be triggered by the system.
Event-driven Applications
Event-driven programming is a style of programming, in which the program responds to events
generated by the user, such as key pressing or mouse clicks.
In an event-driven application, execution does not follow a predetermined path. Instead, it runs
different code sections in response to events. Events can be triggered by the user’s actions, by
messages from the system or other applications, or from the application. The sequence of events
determines the sequence in which the code runs. Therefore, the path through the application’s
code differs each time the program runs.
An essential part of event-driven programming is to Write code that responds to the possible
events that may occur in an application. Visual Basic makes it easy to implement an event- driven
programming model.
Event Driven Vs Procedural Programming
In Procedural application, the application itself controls which portion of the code to execute and
what sequence to take. Execution starts with the first line of code and follows procedure and
requirement.
While in an event driven application the code doesn’t follow a predefine path. Different cede
section is executed in response to events. Events can he triggered by the user’s action Event
driven programming is commonly referred to Object Oriented Programming (O.O Programming
making use of controls)

Variables
Variables are used to temporarily store values during the execution of an application. The process
of telling the compiler the variable that will be required is known as declaring variables. So
simply is a name of memory cell used in a program to store input data and computational results.
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.
Rules used when naming the variables in Visual Basic
• The first character must be a letter
• No spacing is allowed in between
• Period ( . )is not permitted
• May include letters, numbers, and underscore ( _ )
• Reserved words can not be used as Variables i.e. caption etc
• It must not begin with a number

Variable Declaration
Their three ways of declaring a variable
1. Explicit
2. Implicit
3. Variant
If variables are not implicitly or explicitly typed, they are assigned the variant type by default,
The Variant data type is a special type used by Visual Basic that can contain numeric, string, or
date data.

3 Prepared by Isaq
VB Notes summary

Explicit declaration, Dim variableName (as type)


In Visual Basic, one of the ways to create a variable is to declare it explicitly. Typically, you
declare a variable explicitly before you use the variable (usually at the beginning of an event
procedure). You declare the variable by typing a Dim (dimension) statement and the variable
name. For example, the following statement creates space for a program variable named
LastName:
Dim LastName as string
Typing the statement reserves room for the variable in memory when the program runs and lets
Visual Basic know what type of data it should expect to see later.
The Dim statement is the short form of dimension, the optional (as type) clause in the Dim
statement allows us to define the data type of the variable we are declaring All variable have
data types that determine what kind of data they can store for example a variable to store salary
is best represented as numeric data types and a variable storing names is best represented as
alphabetic.
Implicit declaration, Name = “Omar”
You can also declare a variable without the Dim statement; this process is called implicit
declaration. To declare a variable implicitly, you simply use the variable on its own and skip the
Dim statement altogether. Here’s an example:
LastName = “Charles V”

Advantages and Disadvantages


Implicit declaration has the advantage of speed because you don’t spend time typing the Dim
statement; however “the management” often discourages it for several reasons. First, implicit
declaration doesn’t force you to organize and list your variables in advance. Also, creating
variables in this way prevents Visual Basic from displaying an error message if you mistype the
variable name later.
When declaring variable explicitly primarily, we insure all computations are properly done;
mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency
in upper and lower case letters used in variable names. Because of these advantages, and
because it is good programming practice, we will explicitly type all variables
Variant
A variable declared as variant is capable of holding any type of data, if you did not declare a data
type of a variable name holding numerical value. VB treats the variable as of data type integer
likewise if a variable is not declared and in holding character value it’s treated as String.
Note:
When declaring variables you may also combine them in one line, separating each variable with a
comma, as follows:
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
shown above. However, for the fixed-length string, you have to use the format as shown below:
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.
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.
The following are some examples:
• firstNumber=100 • Command2.Visible = false
• secondNumber=firstNumber-99 • Label4.Caption = textbox2.Text
• userName= “john Lyan” • ThirdNumber = Val(usernum1.Text)
• userpass.Text = password
4 Prepared by Isaq
VB Notes summary
• Label3.Visible= True • total = firstNumber + secondNumber+ThirdNumber

Data types
Data type defines the type of in information the variable store. The Data type of a variable
determines how the bits representing those values are stored in the computers memory. When a
variable is declared we assign data type for it that specify the kind of data they hold.
By default if we don’t assign a data type the variable is given the variant data type. The following
is the list of data type supported by visual basic
1. Numeric data type
2. Character data type
3. Boolean data type
4. User defined type
5. Variant data type
The following are some of the common data type used in Visual Basic including storage sizes and
ranges.
i. Integer—This is used to store quantities, data, finite and are represented by whole
numbers, integer variables and are stored as two bytes numbers ranging in value form
—32,756 to + 32,757
ii. Long — This are stored as signed 4 byte numbers ranging form —2147,483,648 to +
2,147,483,647. They are also use to store finite number (no decimal places)
iii. Single — This data type stores floating point variable and occupies a memory space of 4 bytes.
The range is — 340283=38 to + 1.401298=45
iv. Double — This is similar to single and is also used to store floating point numbers. It has a
memory allocation of 8 bytes
v. Currency — The currency variables are 8 bytes numbers taken to four decimal places and used
to represent monitory values.
vi. Date —The date variables are stored as 8 bytes floating points that represent dates ranging
from 1° January year 1000 to 31e December 9999
Note
Arrays of any data type require 20 bytes of memory plus 4 bytes for each array dimension plus the
number of bytes occupied by the data itself. The memory occupied by the data can be calculated
by multiplying the number of data elements by the size of each element. For example, the data
in a single-dimension array consisting of 4 Integer data elements of 2 bytes each occupies 8 bytes.
The 8 bytes required for the data plus the 24 bytes of overhead brings the total memory
requirement for the array to 32 bytes.
A Variant containing an array requires 12 bytes more than the array alone.
Numeric data types
Numeric data type can be expressed as type:-
Integer used to store numbers with no decimals e.g. Dim Age as Integer t.
Long integer Used to store numbers with no decimals but with more storage size e.g. Dim Total
as long.
Double (Real) Used to store numbers with decimals but with more storage size e.g. Dim
Average as double.
Single (Real) Used to store numbers with decimals e.g. Dim Sales as single
Date/time Used to store data containing date / time e.g. Dim today as date
Currency Used to store value of fixed point.
Calculation e.g. money.
E.g. Dim salary as currency
Characters of data types
Character data can be expressed as type:-
String Used to store alphabetic or alphanumeric text.
e.g. Dim Name as string

Boolean data type


Uses two bytes per variable and that return a value of true or false, yes or no,1 or 0

5 Prepared by Isaq
VB Notes summary
User defined data type
Visual Basic allows users to create their own data type. This feature is useful when working with
several data types in a single application.

Visual basic Operators


Operators are symbols used in building an expression.
Visual Basic Operator includes:
1. Arithmetic Operators
These are symbols used to perform arithmetic functions.
Operator Operation
* Multiplication
/ Division
MOD Reminder Division (modulus)
+ Addition
- Subtraction
& String concatenation (combination)
^ Exponential (Raising a number to a power)
2. Conditional Operators
These are symbols used to compare two or more variable
Operator Operation
< Less than
<= Less than or equal to
= Equal to
<> Not equal to
>= Greater than or equal to
> Greater than
3. Assignment Operator
An operator used to assign a value to a variable e.g.
= Equal sign
Dim labe2 as integer
Label2 = text3.text
4. Logical/ Boolean Operators
An operator designed to work with true or false values, they include.
Operator Operation Meaning
NOT Logical Not (Negation) Negates truth
AND Logical AND (AND) Both sides must be true
OR Logical OR (OR) One side or other must be true
XOR Logical XOR (XOR) One side or other must be true but not both

Order of Priority/Precedence
This is the order in which visual basic executes operation in an expression.
Operator Cateorv Precedence/Priority level
() Parenthesis 1
NOT Negation 2
*, /, AND 3
+, - , OR 4
=, <>,<=, >, >= Relational Operation 5
NB
Parenthesis around an expression can change the precedence forcing the expression inside the
parenthesis to be executed first.

CONTROLLING PROGRAM FLOW


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.

6 Prepared by Isaq
VB Notes summary
You can also compare strings with the conditional 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. In addition to conditional operators, there are a few logical operators which
offer added power to the VB programs.

Control structures
Control structures allow you to control the flow of your program's execution. If left unchecked by
control-flow statements, a program's logic will flow through statements from left to right, and
top to bottom (sequence control). While some very simple programs can be written with only this
unidirectional flow, and while some flow can be controlled by using operators to regulate
precedence of operations, most of the power and utility of any programming language comes
from its ability to change statement order with structures and loops.
There existing the following control structures:
Sequence:
Here a program's logic will flow through statements from left to right, and top to bottom
Selection (Decision structures)
Is used to select one choice out of two or more choices. The decision structures that Visual Basic
supports include:
• If...Then
• If...Then...Else
• Select Case
Repetition (loop structures)
Here a group of statement is repeated until a condition is satisfied. it allows you to execute one
or more lines of code repetitively. The loop structures that Visual Basic supports include:
• Do...Loop
• For...Next
• For Each...Next
SELECTION CONTROL STRUCTURE
If statement with one choice or alternatives.
Format:
If <condition> then
Statement
End if
If statement with two choices or alternatives
Format:
If <condition> then
Statement 1
Else
Statement 2
End if

If statement with multiple/compound choices/alternatives.


Format:
If <condition> then
Statement 1
Else If <condition> then
Statement 2
Else If <condition> then
Statement 3
Else If <condition> then
Statement 4
Else If <condition> then
Statement n
Else
Statement last
End if
Example:
Private Sub chkBold_Click ()

7 Prepared by Isaq
VB Notes summary
If ChkBold.Value = vbChecked Then ' If checked.
txtDisplay.Font.Bold = True
Else ' If not checked.
txtDisplay.Font.Bold = False
End If
End Sub
The conditions in a multiple alternative decisions are evaluated in sequence until a true condition
is reached. If a condition is true, the statement after is executed and the rest of decisions
skipped. If all conditions are false then the last statement is executed.
Select Case statement
Here one statement is selected out of several statements.
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.
Format is:
Select Case <condition>
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
* The data type specified in condition(expression) must match that of Case values
Example 1
Private Sub ComputeGrade_Click( )
' Examination Grades
Dim grade As String
grade=txtgrade.Text
Select Case grade
Case "A"
lblresult.Caption="High Distinction"
Case "A-"
lblresult.Caption="Distinction"
Case "B"
lblresult.Caption="Credit"
Case "C"
lblresult.Caption="Pass"
Case Else
lblresult.Caption="Fail"
End Select
End Sub
*Please note that grade is a string, so all the case values such as "A" are of String data type.
Example 2
Private Sub Compute_Click()
'Examination Marks
Dim mark As Single
mark = txtmark.Text
Select Case mark
Case Is >= 85
lblcomment.Caption = "Excellence"
Case Is >= 70
lblcomment.Caption = "Good"
Case Is >= 60
lblcomment.Caption = "Above Average"
8 Prepared by Isaq
VB Notes summary
Case Is >= 50
lblcomment.Caption = "Average"
Case Else
lblcomment.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.
Example 3
Example 2 could be rewritten as follows:
Private Sub Compute_Click()
'Examination Marks
Dim mark As Single
mark = txtmrk.Text
Select Case mark
Case 0 to 49
lblcomment.Caption = "Need to work harder"
Case 50 to 59
lblcomment.Caption = "Average"
Case 60 to 69
lblcomment.Caption = "Above Average"
Case 70 to 84
lblcomment.Caption = "Good"
Case Else
lblcomment.Caption = "Excellence"
End Select
End Sub

REPETITION CONTROL STRUCTURE


Here a group of statement is executed until a certain condition is satisfied. Visual Basic allows a
procedure to be repeated as many times as long as the processor could support. This is generally
called looping.

1. Do loop
The formats are
a) Do While <condition>
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While <condition>
c) Do Until <condition>
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until <condition>

Example 1
Private Sub CmdComputeCounter_Click()
Dim counter As Integer
Dim num As Integer
Counter = 0
num = Val(txtnum.Text)
PicDisplay.Cls
PicDisplay.Print "Counter", "Num"
Do While counter <= num
counter = counter + 1
9 Prepared by Isaq
VB Notes summary
PicDisplay.Print counter, num
Loop
End Sub

* The above example will keep on adding (increasing counter value) until counter>num.
The above example can be rewritten as;
Private Sub CmdComputeCounter_Click()
Dim counter As Integer
Dim num As Integer
counter = 0
num = Val(txtnum.Text)
PicDisplay.Cls
PicDisplay.Print "Counter", "Num"
Do
counter = counter + 1
PicDisplay.Print counter, num
Loop Until counter > num
End Sub
2. For....Next Loop
The format is:

For counter=startNumber to endNumber (Step increment)


One or more VB statements
Next
Example:
(a) Private Sub CmdComputeCounter_Click()
Dim counter As Integer
Dim num As Integer
num = Val(txtnum.Text)
PicDisplay.Cls
PicDisplay.Print "Counter", "Number"
For counter = 1 To num
PicDisplay.Print counter, num
Next
End Sub
(b) Private Sub CmdComputeCounter_Click()
Dim counter As Integer
Dim num As Integer
num = Val(txtnum.Text)
PicDisplay.Cls
PicDisplay.Print "Counter", "Number"
For counter = 0 To num Step 5
PicDisplay.Print counter, num
Next
End Sub
(c) Private Sub CmdComputeCounter_Click()
Dim counter As Integer
PicDisplay.Cls
PicDisplay.Print "Counter"
For counter = 40 To 5 Step -5
PicDisplay.Print counter
Next
End Sub
General Procedures
A general procedure tells the application how to perform a specific task. Once a general
procedure is defined, it must be specifically invoked by the application. By contrast, an event
10 Prepared by Isaq
VB Notes summary
procedure remains idle until called upon to respond to events caused by the user or triggered by
the system.
Why create general procedures? One reason is that several different event procedures might need
the same actions performed. A good programming strategy is to put common statements in a
separate procedure (a general procedure) and have your event procedures call it. This eliminates
the need to duplicate code and also makes the application easier to maintain.
Event Procedures
When an object in Visual Basic recognizes that an event has occurred, it automatically invokes
the event procedure using the name corresponding to the event. Because the name establishes an
association between the object and the code, event procedures are said to be attached to forms
and controls.
An event procedure for a control combines the control's actual name (specified in the Name
property), an underscore (_), and the event name. For instance, if you want a command button
named cmdPlay to invoke an event procedure when it is clicked, use the procedure
cmdPlay_Click.
An event procedure for a form combines the word "Form," an underscore, and the event name. If
you want a form to invoke an event procedure when it is clicked, use the procedure Form_Click.
(Like controls, forms do have unique names, but they are not used in the names of event
procedures.) If you are using the MDI form, the event procedure combines the word "MDIForm," an
underscore, and the event name, as in MDIForm_Load.
All event procedures use the same general syntax.
Syntax for a control event Syntax for a form event
Private Sub controlname_eventname (arguments ) Private Sub Form_eventname (arguments)
statements statements
End Sub End Sub

Although you can write event procedures from scratch, it's easier to use the code procedures
provided by Visual Basic, which automatically include the correct procedure names. You can
select a template in the Code Editor window by selecting an object from the Object box and then
selecting a procedure from the Procedure box.
It's also a good idea to set the Name property of your controls before you start writing event
procedures for them. If you change the name of a control after attaching a procedure to it, you
must also change the name of the procedure to match the new name of the control. Otherwise,
Visual Basic won't be able to match the control to the procedure. When a procedure name does
not match a control name, it becomes a general procedure.

Procedures
You can simplify programming tasks by breaking programs into smaller logical components. These
components — called procedures — can then become building blocks that let you enhance and
extend Visual Basic.
Procedures are useful for condensing repeated or shared tasks, such as frequently used
calculations, text and control manipulation, and database operations.
There are two major benefits of programming with procedures:
Procedures allow you to break your programs into discrete logical units, each of which you can
debug more easily than an entire program without procedures.
Procedures used in one program can act as building blocks for other programs, usually with little
or no modification.
There are several types of procedures used in Visual Basic:
• Sub procedures do not return a value.
• Function procedures return a value.
• Property procedures can return and assign values, and set references to objects.

VB Functions
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. There are two types
of function, the built-in functions(or internal functions) and the functions created by the
programmers.
11 Prepared by Isaq
VB Notes summary
The general format of a function is;
functionName (arguments 1, arguments 2, arguments 3, etc)
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.

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, please refer Table below
for types of command button displayed. The Title argument will display the title of the message
dialogue box.
Style Value Named Constant Buttons Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
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. Table below shows the values, the
corresponding named constant and buttons.
Value Named Constant Button Clicked
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button
Example 1
i. The Interface:
You draw one command button and a label on a form set Properties and use codes below:
ii. The procedure for the test button:
Private Sub cmdTest_Click()
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
lblDisplay.Caption = "Testing Successful"
Else
lblDisplay.Caption = "Testing fail"
End If
End Sub

12 Prepared by Isaq
VB Notes summary
When a user click on the test button, a message will appear. As the user click on the OK button,
the message "Testing successful" will be displayed on label control and when he/she clicks on the
Cancel button, the message "Testing fail" will be displayed.

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

Value Named Constant Icon

16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

Example 2:
You could draw the same Interface as in example 1 but modify the codes as follows:
Private Sub Cmdtest2_Click()
Dim testMsg2 As Integer
testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg2 = 6 Then
lbldisplay2.Caption = "Testing successful"
ElseIf testMsg2 = 7 Then
lbldisplay2.Caption = "Are you sure?"
Else
lbldisplay2.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. The format is

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)


myMessage is a variant data type but typically it is declared as string, which accepts the message
input by the users. The arguments are explained as follows:

Prompt - The message displayed normally as a question asked.


Title - The title of the Input Box.
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.
x & y-position - The position or the coordinate of the input box.

Example 3
i. The Interface
You draw one command button and two labels on a form set Properties and use codes below:
ii. The procedure for the OK button
Private Sub cmdOK_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your message here", 500, 700)
If userMsg <> " " Then
lblmessage.Caption = userMsg
Else
lblmessage.Caption = "No Message"
End If
End Sub
13 Prepared by Isaq
VB Notes summary
When a user clicks the OK button, the input box will appear. After user entering the message and
click OK, the message entered will be displayed on the Label control caption, if he clicks Cancel,
"No message" will be displayed.

14 Prepared by Isaq