0% found this document useful (0 votes)
16 views

Visual Basic Programming Keypoint

Visual Basic is a third-generation programming language first released by Microsoft in 1991. It evolved from earlier versions of BASIC and enables users to easily develop graphical user interface applications. The Visual Basic 6 integrated development environment contains tools like the toolbox, form, and properties window to build applications. A Visual Basic application typically comprises one or more forms as the primary building blocks. Common controls like text boxes, labels, command buttons, list boxes, and check boxes allow users to enter input and display output in applications.

Uploaded by

audibertm260
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Visual Basic Programming Keypoint

Visual Basic is a third-generation programming language first released by Microsoft in 1991. It evolved from earlier versions of BASIC and enables users to easily develop graphical user interface applications. The Visual Basic 6 integrated development environment contains tools like the toolbox, form, and properties window to build applications. A Visual Basic application typically comprises one or more forms as the primary building blocks. Common controls like text boxes, labels, command buttons, list boxes, and check boxes allow users to enter input and display output in applications.

Uploaded by

audibertm260
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

VISUAL BASIC PROGRAMMING KEYPOINT

BY
KAYWHYTEE

Visual Basic is a third-generation event-driven programming language first released by


Microsoft in 1991. It evolved from the earlier DOS version called BASIC. BASIC means
Beginners' All-purpose Symbolic Instruction Code. Since then Microsoft has released
many versions of Visual Basic, from Visual Basic 1.0 to the final version Visual Basic
6.0. Visual Basic is a user-friendly programming language designed for beginners, and
it enables anyone to develop GUI window applications easily.

When you start a new Visual Basic 6 Standard EXE project, you will be presented with
the Visual Basic 6 Integrated Development Environment (IDE). The Visual Basic 6
Integrated Programming Environment is shown in Figure 1.2. It consists of the toolbox,
the form, the project explorer and the properties window.

VB6 Programming Environment


The Form is the primary building block of a Visual Basic 6 application. A Visual Basic 6
application can actually comprise many forms, but we shall focus on developing an
application with one form first.

Creating Your First Application


First of all, launch Microsoft Visual Basic 6 compiler that you have installed earlier. In
the New Project Dialog , choose Standard EXE to enter Visual Basic 6 integrated
development environment. In the VB6 IDE, a default form with the name Form1 will
appear. Next, double click on Form1 to bring up the source code window for Form1

When you click on the object box, the drop-down list will display a list of objects you
have inserted into your form, as shown in figure 2.2. Here, you can see a form with the
name Form1, a command button with the name Command1, a Label with the name
Label1 and a Picture Box with the name Picture1.
Similarly, when you click on the procedure box, a list of procedures associated with the
object will be displayed
EXAMPLE ➖
Private Sub Form_Activate ( )

Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10

End Sub

Handling some of the common Controls

below is the VB6 toolbox that shows the basic controls.


The TextBox

The text box is the standard control for accepting input from the user as well as to
display the output. It can handle string (text) and numeric data but not images or
pictures. A string entered into a text box can be converted to a numeric data by using
the function Val(text). The following example illustrates a simple program that processes
the input from the user.

Example 3.1

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.

Private Sub Command1_Click()

'To add the values in TextBox1 and TextBox2

Sum = Val(Text1.Text) +Val(Text2.Text)

'To display the answer on label 1

Label1.Caption = Sum

End Sub

The output is shown in Figure 3.3


Figure 3.3

3.2.2 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 . You can change its caption in the properties window and also at
runtime. Please refer to Example 3.1 and Figure 3.1 for the usage of the label.

3.2.3 The Command Button

The command button is one of the most important controls 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

Example 3.2 A Simple Password Cracker

In this program, we want to crack a secret passoword entered by the user. In the design
phase, insert a command button and change its name to cmd_ShowPass. Next, insert a
TextBox and rename it as TxtPassword and delete Text1 from the Text property.
Besides that, set its PasswordChr to *. Now, enter the following code in the code
window.

Private Sub cmd_ShowPass_Click()

Dim yourpassword As String

yourpassword = Txt_Password.Text

MsgBox ("Your password is: " & yourpassword)

End Sub

Run the program and enter a password, then click on the Show Password button to
reveal the password, as shown in Figure 3.4.

Figure 3.4 The Password Cracker

You can also reveal the password by setting the PasswordChr property back to normal
mode, as follows:

Private Sub cmd_ShowPass_Click()

Dim yourpassword As String

Txt_Password.PasswordChar = ""

End Sub
3.2.4 The PictureBox

The Picture Box is one of the controls that is 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. For example, the statement will load the picture grape.gif into
the picture box.

Picture1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")

Example 3.4 Loading Picture

In this program, insert a command button and a picture box. Enter the following code:

Private Sub cmd_LoadPic_Click()

MyPicture.Picture = LoadPicture("C:\Users\admin.DESKTOP-G1G4HEK\Documents\My
Websites\vbtutor\vb6\images\uranus.jpg")

End Sub

* You must ensure the path to access the picture is correct. Besides that, the image in
the picture box is not resizable. The output is shown in Figure 3.5
Figure 3.5 The Picture Viewer

View our more advanced picture viewer here.

3.2.5 The Image Control

The Image Control is another control that handles images and pictures. It functions
almost identically to the pictureBox. 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 PictureBox. Similar to the Picture Box, it can also use the LoadPicture
method to load the picture. For example, the statement loads the picture grape.gif into
the image box.

Image1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")

Example 3.5 Loading Image

In this program, we insert a command button and an image control into the form.
Besides that, we set the image Strech property to true. Next, enter te following code:

Private Sub cmd_LoadImg_Click()

MyImage.Picture = LoadPicture("C:\Users\admin.DESKTOP-G1G4HEK\Documents\My
Websites\vbtutor\vb6\images\uranus.jpg")

End Sub
Figure 3.6 The Image Viewer

* Note the the difference between the image in Figure 3.5 and Figure 3.6.

3.2.6 The ListBox

The function of the ListBox 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 3.2

Private Sub Form_Load ( )

List1.AddItem “Lesson1”

List1.AddItem “Lesson2”

List1.AddItem “Lesson3”

List1.AddItem “Lesson4”

End Sub

The Output
Figure 3.7 The ListBox

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 third item has
a ListIndex 2 and so on

3.2.7 The ComboBox

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 3.3

Private Sub Form_Load ( )

Combo1.AddItem "Item1"

Combo1.AddItem "Item2"

Combo1.AddItem "Item3"

Combo1.AddItem "Item4"

End Sub

The Output
Figure 3.8 The ListBox

3.2.8 The CheckBox

The Check Box control lets the user selects or unselects 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 to unmark the Check Box, as well as use them to initiate certain
actions. For example, the program in Example 3.4 will show which items are selected in
a message box.

Example 3.4

Private Sub Cmd_OK_Click()

If Check1.Value = 1 And Check2.Value = 0 And Check3.Value = 0 Then

MsgBox "Apple is selected"

ElseIf Check2.Value = 1 And Check1.Value = 0 And Check3.Value = 0 Then

MsgBox "Orange is selected"

ElseIf Check3.Value = 1 And Check1.Value = 0 And Check2.Value = 0 Then

MsgBox "Orange is selected"

ElseIf Check2.Value = 1 And Check1.Value = 1 And Check3.Value = 0 Then

MsgBox "Apple and Orange are selected"

ElseIf Check3.Value = 1 And Check1.Value = 1 And Check2.Value = 0 Then

MsgBox "Apple and Pear are selected"


ElseIf Check2.Value = 1 And Check3.Value = 1 And Check1.Value = 0 Then

MsgBox "Orange and Pear are selected"

Else

MsgBox "All are selected"

End If

End Sub

The Output

Figure 3.9 The ListBox

3.2.9 The OptionButton

The OptionButton control also lets the user selects one of the choices. However, two or
more Option buttons must work together because as one of the option buttons is
selected, the other Option button will be unselected. In fact, only one Option Box can be
selected at one time. When an option box is selected, its value is set to “True” and when
it is unselected; its value is set to “False”.
Example 3.4

In this example, we want to change the background color of the form according to the
selected option. We insert three option buttons and change their captions to "Red
Background","Blue Background" and "Green Background" respectively. Next, insert a
command button and change its name to cmd_SetColor and its caption to "Set
Background Color". Now, click on the command button and enter the following code in
the code window:

Private Sub cmd_SetColor_Click()

If Option1.Value = True Then

Form1.BackColor = vbRed

ElseIf Option2.Value = True Then

Form1.BackColor = vbBlue

Else

Form1.BackColor = vbGreen

End If

End Sub

Run the program, select an option and click the "Set Background Color" produces the
output, as shown in Figure 3.10.

Figure 3.10
3.2.10 The Shape Control

In the following example, the shape control is placed in the form together with six
OptionButtons. To determine the shape of the shape control, we use the shape property.
The property values of the shape control are 0, 1, and 2,3,4,5 which will make it appear
as a rectangle, a square, an oval shape, a circle, a rounded rectangle and a rounded
square respectively.

Example 3.5

In this example, we insert six option buttons. It is better to make the option buttons into
a control array as they perform similar action, i.e to change shape. In order to create a
control array, click on the first option button, rename it as MyOption. Next, click on the
option button and select copy then paste. After clicking the paste button, a popup dialog
(Figure 3.11)will ask you whether you wish to create a control array, select yes. The
control array can be accessed via its index value, MyOtion(Index. In addition, we also
insert a shape control.

Figure 3.11

Now, enter the code in the code window. We use the If..Then..Else program structure to
determine which option button is selected by the user. You can learn about
If..Then..Else in Lesson 7.

Private Sub MyOption_Click(Index As Integer)

If Index = 0 Then

MyShape.Shape = 0

ElseIf Index = 1 Then

MyShape.Shape = 1

ElseIf Index = 2 Then


MyShape.Shape = 2

ElseIf Index = 3 Then

MyShape.Shape = 3

ElseIf Index = 4 Then

MyShape.Shape = 4

ElseIf Index = 5 Then

MyShape.Shape = 5

End If

End Sub

Run the program and you can change the shape of the shape control by clicking one of
the option buttons. The output is shown in Figure 3.12.

Figure 3.12

3.2.10 The DriveListBox


The DriveListBox is for displaying a list of drives available in your computer. When you
place this control into the form and run the program, you will be able to select different
drives from your computer as shown in Figure 3.13

Figure 3.13 The


Drive List Box

3.2.11 The DirListBox

The DirListBox means the Directory List Box. It is for displaying a list of directories or
folders in a selected drive. When you place this control into the form and run the
program, you will be able to select different directories from a selected drive in your
computer as shown in Figure 3.14
Figure 3.14 The

DirListBox

3.15 The FileListBox

You can coordinate the Drive List Box, the Directory List Box and the File List Box to
search for the files you want. The procedure will be discussed in later lessons.

In Visual Basic, most of the syntaxes resemble the English language. Among the
syntaxes are Print, If…Then….Else….End If, For…Next, Select Case…..End Select ,
End and Exit Sub. For example, Print “ Visual Basic” is to display the text Visual
Basic on screen and End is to end the program.
Program code that involves calculations is fairly easy to write, just like what you do in
mathematics. However, in order to write an event procedure that involves calculations,
you need to know the basic arithmetic operators in VB as they are not exactly the same
as the normal operators , except for + and - .

For multiplication, we use *, for division we use /, for raising a number x to the power of
n, we use x ^n and for square root, we use Sqr(x). VB offers many more advanced
mathematical functions such as Sin, Cos, Tan and Log, they will be discussed in lesson
10. There are also two important functions that are related to arithmetic operations, i.e.
the functions Val and Str$ where Val is to convert text to a numerical value and Str$ is
to convert numerical to a string (text). While the function Str$ is as important as VB can
display a numeric value as string implicitly, failure to use Val will result in the wrong
calculation. Let’s examine Example 4.4 and example 4.5.

Example 4.4
Private Sub Form_Activate()
Text3.text=text1.text+text2.text
End Sub

Example 4.5
Private Sub Form_Activate()
Text3.text=val(text1.text)+val(text2.text)
End Sub

When you run the program in example 4.4 and enter 12 in textbox1 and 3 in textbox2
will give you a result of 123, which is wrong. It is because VB treat the numbers as
string and so it just joins up the two strings. On the other hand, running exampled 4.5
will give you the correct result, i.e., 15.
Visual Basic Data Types

In our daily lives, we encounter a wide variety of data. Whether it's names, addresses,
monetary values, dates, stock quotes, or statistics, we constantly handle various types
of information. Likewise, when working with Visual Basic, we encounter diverse forms of
data, including mathematically calculable values as well as text and other formats. To
facilitate efficient coding, VB categorizes data into different types. In VB6, these types
are primarily divided into two major categories: numeric data types and non-numeric
data types.

5.1.1 Numeric Data Types

Numeric data types are fundamental data types that encompass numbers capable of
being manipulated through mathematical computations using standard operators. They
serve as containers for various types of quantitative information, such as height, weight,
share values, prices of goods, monthly bills, fees, and more. In Visual Basic, numeric
data is categorized into seven distinct types based on the range of values they can
accommodate.

Calculations involving round figures can make use of the Integer or Long Integer data
types. However, for programs that necessitate high precision calculations, the preferred
choice is to employ the Single and Double data types, commonly known as
floating-point numbers. When it comes to currency calculations, it is advisable to use
currency data types. Lastly, if utmost precision is indispensable for calculations involving
numerous decimal points, the decimal data types prove to be the most suitable option.
These data types summarized in Table 5.1

Type Storage Range of Values

Byte 1 byte 0 to 255

Integer 2 bytes -32,768 to 32,767

Long 4 bytes -2,147,483,648 to 2,147,483,648

Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative


values 1.401298E-45 to 3.402823E+38 for positive
values.
Double 8 bytes -1.79769313486232e+308 to
-4.94065645841247E-324 for negative values
4.94065645841247E-324 to
1.79769313486232e+308 for positive values.

Currency 8 bytes -922,337,203,685,477.5808 to


922,337,203,685,477.5807

Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no


decimal is use +/-
7.9228162514264337593543950335 (28 decimal
places).

5.1.2 Non-numeric Data Types

Nonnumeric data types are data that cannot be manipulated mathematically.


Non-numeric data comprises string data types, date data types, boolean data types that
store only two values (true or false), object data type and Variant data type .They are
summarized in Table 5.2

Data Type Storage Range

String(fixed length) Length of string 1 to 65,400 characters

String(variable Length + 10 0 to 2 billion characters


length) bytes

Date 8 bytes January 1, 100 to December


31, 9999

Boolean 2 bytes True or False

Object 4 bytes Any embedded object

Variant(numeric) 16 bytes Any value as large as Double

Variant(text) Length+22 Same as variable-length string


bytes
5.1.3 Suffixes for Literals

Literals are values that you assign to data. In some cases, we need to add a suffix
behind a literal so that VB can handle the calculation more accurately. For example, we
can use num=1.3089# for a Double type data. Some of the suffixes are displayed in
Table 5.3.

Suffix Data Type

& Long

! Single

# Double

@ Currency

In addition, we need to enclose string literals within two quotations and date and time
literals within two # sign. Strings can contain any characters, including numbers. The
following are few examples:

memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#

5.2 Managing Variables

Variables are like mail boxes in the post office. The contents of the variables changes
every now and then, just like the mail boxes. In term of VB, variables are areas
allocated by the computer memory to hold data. Like the mail boxes, each variable must
be given a name. To name a variable in Visual Basic, you have to follow a set of rules.

5.2.1 Variable Names


The following are the rules when naming the variables in Visual Basic

● It must be less than 255 characters


● No spacing is allowed
● It must not begin with a number
● Period is not permitted
● Cannot use exclamation mark (!), or the characters @, &, $, #
● Cannot repeat names within the same level of scope.

Examples of valid and invalid variable names are displayed in Table 5.4

Valid Name Invalid Name

My_Car My.Car

ThisYear 1NewBoy

Long_Name_Can_beU He&HisFather *& is not


SE acceptable

5.2.2 Declaring Variables Explicitly

In Visual Basic, it is a good practice to declare the variables before using them by
assigning names and data types. They are normally declared in the general section of
the codes' windows using the Dim statement. You can use any variable to hold any data
, but different types of variables are designed to work efficiently with different data types
.
The syantax is as follows:

Dim VariableName As DataType

If you want to declare more variables, you can declare them in separate lines or you
may also combine more in one line , separating each variable with a comma, as follows:

Dim VariableName1 As DataType1, VariableName2 As


DataType2,VariableName3 As DataType3
Example 5.1
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date
Dim password As String, yourName As String, firstnum As Integer

Unlike other programming languages, Visual Basic actually doesn't require you to
specifically declare a variable before it's used. If a variable isn't declared, VB will
automatically declare the variable as a Variant. A variant is data type that can hold any
type of data.

For string declaration, there are two possible types, one for the variable-length string
and another for the fixed-length string. For the variable-length string, just use the same
format as example 5.1 above. However, for the fixed-length string, you have to use the
syntax as shown below:

Dim VariableName as String * n

where n defines the number of characters the string can hold.

For example,

Dim yourName as String * 10

*yourName can holds no more than 10 Characters.

5.2.2 Scope of Declaration

Other than using the Dim keyword to declare the data, you can also use other keywords
to declare the data. Three other keywords are private ,static and public. The forms are
as shown below:

Private VariableName as Datatype


Static VariableName as Datatype
Public VariableName as Datatype
The above keywords indicate the scope of the declaration. Private declares a local
variable or a variable that is local to a procedure or module. However, Private is rarely
used, we normally use Dim to declare a local variable. The Static keyword declares a
variable that is being used multiple times, even after a procedure has been terminated.
Most variables created inside a procedure are discarded by Visual Basic when the
procedure is finished, static keyword preserves the value of a variable even after the
procedure is terminated. Public is the keyword that declares a global variable, which
means it can be used by all the procedures and modules of the whole program.

5.3 Constants

Constants are different from variables in the sense that their values do not change
during the running of the program.

5.3.1 Declaring a Constant

The syntax to declare a constant is

Constant Name As Data Type = Value

Example 5.3

In this example, we insert a Shape control and two command buttons. Set the shape
value of the Shape control to 3 so that it becomes a circle. Rename one of the
command buttons to CmdResize for changing the size of the circle. Rename the other
command button as CmdArea for calculation of the area of the circle. In this program,
we declare four variables and a constant in the General section. The varaible h is to
store the value of height of the circle and the variable r is to store the value of the radius
which is half of the height. In addtion, the variable a is to store the value of area in twip
using the formula area of circle=πr2. Besides that, the constant Pi represents π which
we fixed at 3.142. Finally, the variable area is to store the value in cm by multiplying a
with 0.001763889. (1 twip =0.001763889 cm)

The Code
Dim h, r, a, rad, area As Single
Const Pi As Single = 3.142

Private Sub CmdArea_Click()


r=h/2
rad = r * 0.001763889
a = Pi * rad ^ 2
area = Round(a, 2)
MsgBox ("The Area of the circle is " & area)
End Sub

Private Sub CmdResize_Click()


h = InputBox("Enter the value of height")
MyShape.Height = h

End Sub

The Output

Figure 5.1
Figure 5.1

Assigning Values to Variables

After declaring various variables using the Dim statements, we can assign values to
those variables. The syntax 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 more.

The following are some examples variable assignment:

firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
X = (3.14159 / 180) * A
6.2 Operators in Visual Basic
To compute inputs from users and to generate results, we need to use various
mathematical operators. In Visual Basic, except for + and -, the symbols for the
operators are different from normal mathematical operators, as shown in Table 6.1.

Operato Mathematical function Example>


r

^ Exponential 2^4=16

* Multiplication 4*3=12,

/ Division 12/4=3

Mod Modulus (returns the remainder from an 15 Mod 4=3


integer division)

\ Integer Division(discards the decimal 19\4=4


places)

+ or & String concatenation "Visual"&"Basic"="Visual


Basic"

Example 6.1

Private Sub Command1_Click()

Dim firstName As String


Dim secondName As String
Dim yourName As String

firstName = Text1.Text
secondName = Text2.Text
yourName = secondName +"" + firstName
Label1.Caption = yourName
End Sub

In Example 6.1, three variables are declared as string. For variables firstName and
secondName will receive their data from the user’s input into textbox1 and textbox2,
and the variable yourName will be assigned the data by combining the first two
variables. Finally, yourName is displayed on Label1.

Example 6.2
Dim number1, number2,number3 as Integer
Dim total, average as variant
Private sub Form_Click()

number1=val(Text1.Text)
number2=val(Text2.Text)
number3= val(Text3.Text)
Total=number1+number2+number3
Average=Total/5
Label1.Caption=Total
Label2.Caption=Average
End Sub

In the Example 6.2, three variables are declared as integer and two variables are
declared as variant. Variant means the variable can hold any data type. The program
computes the total and average of the three numbers that are entered into three text
boxes.

Example 6.3 Easy Math

This is a simple math drill program where the user enter two numbers and calculate its
sum. The program will tell him whether the answer is right or wrong. To add some gist to
the program, the user needs to enter the password before he or she can proceed.

The Code
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date

Private Sub Command1_Click()


If userpass.Text = password Then
Label2.Visible = True
number1.Visible = True
number2.Visible = True
sum.Visible = True
Label3.Visible = True
Command3.Visible = True
usernum1.Visible = True
usernum2.Visible = True
OK.Visible = True
Label4.Visible = True
Label4.Caption = textbox1.Text
textbox1.Visible = False
userpass.Visible = False
username.Visible = False
Label1.Visible = False
Command1.Visible = False
Else
userpass.Text = ""
userpass.SetFocus
End If

End Sub

3.'
Private Sub Form_Load()
password = "liewxun"
End Sub

Private Sub OK_Click()


firstnum = usernum1.Text
secondnum = usernum2.Text
total = sum.Text
If total = firstnum + secondnum And Val(sum.Text) <> 0 Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If
End Sub

The Output

Figure 6.1 The Login dialog

Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically,
they resemble mathematical operators. Conditional operators are very powerful tools,
they let the VB program compare data values and then decide what action to take,
whether to execute a program or terminate the program and more. These operators are
shown in Table 7.1.

Table 7.1: Conditional Operators

Operato Meaning
r

= Equal to

> More than

< Less Than

> More than


or equal

<= Less than


or equal

<> Not Equal


to

7.2 Logical Operators


In addition to conditional operators, there are a few logical operators that offer added
power to the VB programs. They are shown in Table 7.2.

Table 7.2:Logical Operators


Operator Description

And Both sides must be true


Or One side or other must be true

Xor One side or other must be true but not both

Not Negates true

* You can also compare strings with the operators. However, there are certain rules to
follow where upper case letters are less than lowercase letters, and number are less
than letters.

7.3 Using If.....Then.....Else Statements with Operators


To effectively control the VB program flow, we shall use If...Then...Else statement
together with the conditional operators and logical operators.

If conditions Then

VB expressions

Else

VB expressions

End If

Example 7.1:

This program simulates a sign in process. If the username and password are correct,
sign in is successful else sign in failed. Start VB6 and insert two textboxes on the form,
rename them UsrTxt and pwTxt, the first textbox is to accept username input and the
second one for password input. For pwTxt, set the PasswordChr(password characters)
property to * so that the password will appear as * instead of the actual character. We
have written the code so that both username and password must be correct to enable
sign in if either one of them incorrect sign in will fail.

The Code
Private Sub OK_Click()
Dim username, password As String
username = "John123"
password = "qwertyupi#@"

If UsrTxt.Text = username And pwTxt.Text = password Then


MsgBox ("Sign in sucessful")
ElseIf UsrTxt.Text <> username Or pwTxt.Text <> password Then

MsgBox ("Sign in failed")


End If
End Sub

The Output

Figure 7.1

Figure 7.2

You can check out our animated passwords cracker program

Example 7.2
This example calculate the commission based on sales volume attained. Let's say the
commission structure is laid out as in the table below:

Sale Commission(
Volume($) %)

<5000 0

5000-9999 5

1000-14999 10

15000-19999 15

20000 and 20
above

In this example, we insert a textbox to accept sale volume input and a label to display
commission. Insert a command button to trigger the calculation

The Code
Private Sub cmdCalComm_Click()
Dim salevol, comm As Currency
salevol = Val(TxtSaleVol.Text)
If salevol >= 5000 And salevol < 10000 Then
comm = salevol * 0.05
ElseIf salevol >= 10000 And salevol < 15000 Then
comm = salevol * 0.1
ElseIf salevol >= 15000 And salevol < 20000 Then
comm = salevol * 0.15
ElseIf salevol >= 20000 Then
comm = salevol * 0.2
Else
comm = 0
End If
LblComm.Caption = Format(comm, "$#,##0.00")
End Sub

The Output
Figure 7.3

Example 7.3: Guess a Number Game

This is a guess a number game where the user key in a number and see check whether
the answer is correct. Thr program will provide a hint whether the number is too small or
too big. After a number of trial, the user should get the right answer. The program
employ the If..Then..Else technique to check whether the entry is correct.

The Code
'Guess a Number
Const realNumber = 99
Dim userNumber As Integer

Private Sub EXit_Click()


End
End Sub

Private Sub OK_Click()

userNumber = entry.Text
If userNumber > realNumber Then

hint.Caption = "Your number is too big"


ElseIf userNumber < realNumber Then

hint.Caption = "Your number is too small"

entry.Text = ""
entry.SetFocus
Else
hint.Caption = "Congratulation, your number is correct"

End If

End Sub

7.4 The IIf() Function


The IIf function denotes immediate decision function. It provides a simple decision
making process based on three arguments, as follows:

IIf(x, y, z)

x represents a logical expression while y and z represent a numeric or a string


expression.

For example, the IIF(x>y, expression 1, expression 2) function evaluates the values of x
and y, if x>y. then expression 1 is true, otherwise the expression 2 is true.

Example 7.3
Private Sub CmdNumeric_Click()
Dim x, y, a, b, ans As Double
x = InputBox("Enter a number")
y = InputBox("Enter another number")
a = Val(x)
b = Val(y)

ans = IIf(a < b, b - a, a * b)


MsgBox ans
End Sub

Private Sub CmdString_Click()


Dim A, B, C As String
A = InputBox("Enter a word")
B = InputBox("Enter another word")
C = IIf(A < B, A, B)
MsgBox C
End Sub
Figure 7.4: The Interface

If you click test string and enter the first word long and the second word short, the
logical condition is true, hence the word long will be displayed, as shown in Figure 7.5.

Figure 7.5

If you click test numeric and enter the first number 200 and the second number 40, the
logical condition is false, hence the second expression will be executed, which is
20x40=800, as shown in Figure 7.6.
Looping
We can create a Visual Basic procedure that enables the program to run iteratively until
specific conditions are satisfied. This procedure is commonly referred to as looping.
Looping is an invaluable feature of Visual Basic as it simplifies repetitive tasks and
enhances efficiency. There are three kinds of loops in Visual Basic, the
Do...Loop ,the For.......Next loop and the While.....Wend Loop.

9.1 The Do Loop

The Do Loop statements have four different forms, as shown below:

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 9.1

Do while
counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter > 1000

The above example can be rewritten as

Do
counter=counter+1
Loop until counter>1000

9.2 Exiting the Loop

Sometime we need exit to exit a loop earlier when a certain condition is fulfilled. The
keyword to use is Exit Do. You can examine Example 9.2 for its usage.

Example 9.2
Dim sum, n as Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
Do
n=n+1
sum=sum+n-resize
List1.AddItem n & vbTab & sum
If n=100 Then
Exit Do
End If
Loop
End Sub

Explanation

In the above example, we compute the summation of 1+2+3+4+……+100. In the


design stage, you
need to insert a ListBox into the
form for displaying the output, named
List1. The program uses the AddItem
method to populate the ListBox. The
statement List1.AddItem "n" & vbTab &
"sum" will display the
headings in the
ListBox, where it uses the vbTab
function to create a space between the
headings n and sum.

9.3 The For....Next Loop

The For....Next Loop event procedure is written as follows:

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next

Example 9.3 a

Private Sub Command1_Click()


Dim counter As Integer
For counter = 1 To 10
List1.AddItem counter
Next
End Sub

Example 9.3 b
Private Sub Command1_Click()

Dim counter As Integer


For counter = 1 To 1000 Step 10
counter = counter + 1
Print counter
Next
End Sub

Example 9.3 c

For counter=1000 to 5 step -5


counter=counter-10
If counter<50 then
Exit For
Else
Print "Keep Counting"
End If
Next

Example 9.3 d
Private Sub Form_Activate( )
For n=1 to 10
If n>6 then
Exit For
Else
Print n
Enf If
Next
End Sub

Sometimes the user might want to get out from the loop before the whole repetitive
process is executed, the command to use is Exit For. To exit a For….Next Loop, you
can place the Exit For statement within the loop; and it is normally used together with
the If…..Then… statement. Its usages is shown in Example 9.3 d.

9.4 Nested For...Next Loop


When you have a loop within a loop, then you have created a nested loop. You can
actually have as many loops as you want in a nested loop provided the loops are not
the never-ending type. For a nested loop that consists of two loops, the first cycle of the
outer loop will be processed first, then it will process the whole repetitive process of the
inner loop, then the second cycle of the outer loop will be processed and again the
whole repetitive process of the inner loop will be processed. The program will end when
the whole cycle of the outer loop is processed.

The Structure of a nested loop is :

For counter1=startNumber to endNumber (Step increment)


For counter2=startNumber to endNumber (Step increment)
One or more VB statements
Next counter2
Next counter1

Example 9.4
Private Sub Form_Activate ( )
For firstCounter= 1to 5
Print "Hello"
For secondCounter=1 to 4
Print "Welcome to the VB tutorial"
Next secondCounter
Next firstCounter
Print"Thank you"
End Sub
Figure 9.1

The output of the above program is shown in Figure 9.1. As the outer loop has five
repetitions, it will print the word “Hello” five times. Each time after it prints the word
“Hello”, it will print four lines of the “Welcome to the VB tutorial” sentences as the inner
loop has four repetitions.

9.5 The While….Wend Loop

The structure of a While….Wend Loop is very similar to the Do Loop. it takes the
following form:

While condition
Statements
Wend

The above loop means that while the condition is not met, the loop will go on. The loop
will end when the condition is met. Let’s examine the program listed in example 9.4.

Example 9.5
Dim sum, n As Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
While n <> 100
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
Wend
End Sub

Built-in Functions
In programming, a function is comparable to a procedure, but it serves a distinct
purpose. While both accept input and perform specific actions, the primary objective of
a function is to receive user input, process it, and return a value that is subsequently
utilized by the main program to complete its execution. In VB6, there exist two
categories of functions: built-in functions, also known as internal functions, and
user-defined functions crafted by programmers.

In this lesson, you will learn two very basic but useful internal functions of
Visual basic , i.e. the MsgBox( ) and InputBox ( ) functions. We shall learn about other
built-in functions in coming lessons.

10.1 MsgBox ( ) Function


The objective of MsgBox is to produce a pop-up message box that prompt the user to
click on a command button before he /she can continues. The 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 10.1 for types of command button displayed. The Title argument will
display the title of the message board.

Table 10.1: Style Values


Style Named Constant Buttons Displayed
Value

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 10.2 shows the values, the corresponding named constant and buttons.

Value Named Button


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

i. The Interface:

You draw three command buttons and a label as shown in Figure 10.1

Figure 10.1

The procedure for the test button:

Private Sub Test_Click()


Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
Display.Caption = "Testing Successful"
Else
Display.Caption = "Testing fail"
End If
End Sub

When the user click on the test button, the image like the one shown in Figure 10.2 will
appear. As the user click on the OK button, the message "Testing successful" will be
displayed and when he/she clicks on the Cancel button, the message "Testing fail" will
be displayed.
Figure 10.2

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 10.3

Table 10.3
Value Named
Constant Icon

16 vbCritical

3 vbQuestion

48 vbExclamation

64 vbInformation

Example 10.2

You draw the same Interface as in example 10.1 but modify the codes as follows:

Private Sub test2_Click()


Dim testMsg2 As
Integer testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation,
"TestMessage")
If testMsg2 = 6 Then
display2.Caption ="Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else display2.Caption ="Testing fail"
End If
End Sub

In this example, the following message box will be displayed:

Figure 10.3

10.2 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 accept 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-position and y-position - the position or the coordinate of the input box.

Example 10.3

i.The Interface
Figure 10.4

ii. The procedure for the OK button

Private Sub OK_Click()


Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your
messge here", 500, 700)
If userMsg <>"" Then
message.Caption = userMsg
Else
message.Caption = "No Message"
End If
End Sub

When the user clicks the OK button, the input box as shown in Figure 10.5 will appear.
Upon entering the message and click OK, the message will be displayed on the caption,
if the Cancel button is clicked, "No message" will be displayed.
SOLUTIONS TO EXAM QUESTION:-

design a form and write a visual basic smaple


code for calculate area of traiangle

Private Sub cmdClick_Click()


Dim h As Integer, b As Integer
Dim area As Double
h = Val(Text1.Text)
b = Val(Text2.Text)
area = (0.5) * h * b
Label3.Caption = "Area of Triangle " & area
End Sub

You might also like