Visual Basic Programming Keypoint
Visual Basic Programming Keypoint
BY
KAYWHYTEE
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.
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
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.
Label1.Caption = Sum
End Sub
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.
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
Statements
End Sub
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.
yourpassword = Txt_Password.Text
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.
You can also reveal the password by setting the PasswordChr property back to normal
mode, as follows:
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")
In this program, insert a command button and a picture box. Enter the following code:
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
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")
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:
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.
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
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
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
Combo1.AddItem "Item1"
Combo1.AddItem "Item2"
Combo1.AddItem "Item3"
Combo1.AddItem "Item4"
End Sub
The Output
Figure 3.8 The ListBox
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
Else
End If
End Sub
The Output
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:
Form1.BackColor = vbRed
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.
If Index = 0 Then
MyShape.Shape = 0
MyShape.Shape = 1
MyShape.Shape = 3
MyShape.Shape = 4
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
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
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.
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
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.
& 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#
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.
Examples of valid and invalid variable names are displayed in Table 5.4
My_Car My.Car
ThisYear 1NewBoy
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:
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:
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:
For example,
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:
5.3 Constants
Constants are different from variables in the sense that their values do not change
during the running of the program.
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
End Sub
The Output
Figure 5.1
Figure 5.1
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.
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.
^ Exponential 2^4=16
* Multiplication 4*3=12,
/ Division 12/4=3
Example 6.1
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.
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
End Sub
3.'
Private Sub Form_Load()
password = "liewxun"
End Sub
The Output
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.
Operato Meaning
r
= Equal to
* 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.
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#@"
The Output
Figure 7.1
Figure 7.2
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
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
userNumber = entry.Text
If userNumber > realNumber Then
entry.Text = ""
entry.SetFocus
Else
hint.Caption = "Congratulation, your number is correct"
End If
End Sub
IIf(x, y, z)
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)
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.
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
Do
counter=counter+1
Loop until counter>1000
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
Next
Example 9.3 a
Example 9.3 b
Private Sub Command1_Click()
Example 9.3 c
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.
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.
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.
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.
0 vbOkOnly Ok button
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:
and
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.
1 vbOk Ok 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
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:
Figure 10.3
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:
Example 10.3
i.The Interface
Figure 10.4
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:-