Visual Studio VB 2008
Visual Studio VB 2008
There are many types of data that we come across in our daily life. For example, we need
to handle data such as names, addresses, money, date, stock quotes, statistics and etc
everyday. Similarly in Visual Basic 2008, we have to deal with all sorts of of data, some
can be mathematically calculated while some are in the form of text or other forms.
VB2008 divides data into different types so that it is easier to manage when we need to
write the code involving those data.
6.1 Visual Basic 2008 Data Types
Visual Basic 2008 classifies the information mentioned above into two major data types,
they are the numeric data types and the non-numeric data types.
6.1.1 Numeric Data Types
Numeric data types are types of data that consist of numbers, which can be computed
mathematically with various standard operators such as add, minus, multiply, divide
and so on. Examples of numeric data types are your examination marks, your height,
your weight, the number of students in a class, share values, price of goods, monthly
bills, fees and etc. In Visual Basic 2008, numeric data are divided into 7 types,
depending on the range of values they can store. Calculations that only involve round
figures or data that don't need precision can use Integer or Long integer in the
computation. Programs that require high precision calculation need to use Single and
Double decision data types, they are also called floating point numbers. For currency
calculation , you can use the currency data types. Lastly, if even more precision is
requires to perform calculations that involve a many decimal points, we can use the
decimal data types. These data types summarized in Table 6.1
Table 6.1: Numeric Data Types
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).
6.1.2 Non-numeric Data Types
Nonnumeric data types are data that cannot be manipulated mathematically using
standard arithmetic operators. The non-numeric data comprises text or string data types,
the Date data types, the Boolean data types that store only two values (true or false),
Object data type and Variant data type .They are summarized in Table 6.2
Table 6.2: Nonnumeric Data Types
Data Type Storage Range
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
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 bytes Same as variable-length string
6.1.3 Suffixes for Literals
Literals are values that you assign to a data. In some cases, we need to add a suffix
behind a literal so that VB2008 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 6.3.
Table 6.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#
6.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 VB2008, 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 2008, you have to follow a set of
rules.
6.2.1 Variable Names
The following are the rules when naming the variables in Visual Basic 2008
It must be less than 255 characters
No spacing is allowed
It must not begin with a number
Period is not permitted
Examples of valid and invalid variable names are displayed in Table 6.4
Table 6.4
Valid Name Invalid Name
My_Car My.Car
ThisYear 1NewBoy
Long_Name_Can_beUSE He&HisFather *& is not
acceptable
6.2.2 Declaring Variables
In Visual Basic 2008, one needs to declare the variables before using them by assigning
names and data types. If you fail to do so, the program will show an error. They are
normally declared in the general section of the codes' windows using the Dim statement.
The format is as follows:
Dim Variable Name As Data Type
Example 6.1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles MyBase.Load
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
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,.............
For string declaration, there are two possible formats, one for the variable-length
string and another for the fixed-length string. For the variable-length string, just use the
same format as example 6.1 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 6.2:
Dim yourName as String * 10
yourName can holds no more than 10 Characters.
6.2.3 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
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
6.3 Constants
Constants are different from variables in the sense that their values do not change during
the running of the program.
6.3.1 Declaring a Constant
The format to declare a constant is
Const Constant Name As Data Type = Value
Example 6.3
Private Sub Form1_Load(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles MyBase.Load
Const Pi As Single=3.142
Const Temp As Single=37
Const Score As Single=100
End Sub
Lesson 7: Mathematical Operations
Computer can perform mathematical calculations much faster than human beings.
However, computer itself cannot perform any mathematical calculations without
receiving instructions from the user. In VB2008, we can write code to instruct the
computer to perform mathematical calculations such as addition, subtraction,
multiplication, division and other kinds of arithmetic operations. In order for VB2008 to
carry out arithmetic calculations, we need to write code that involve the use of various
arithmetic operators. The VB2008 arithmetic operators are very similar to the normal
arithmetic operators, only with slight variations. The plus and minus operators are the
same while the multiplication operator use the * symbol and the division operator use the
/ symbol. The list of VB2008 arithmetic operators are shown in table 7.1 :
Table 7.1: Arithmetic Operators
Operator Mathematical function Example
+ Addition 1+2=3
-- Subtraction 4-1=3
^ Exponential 2^4=16
* Multiplication 4*3=12, (5*6))2=60
/ Division 12/4=3
Mod
Modulus (return the remainder from an
integer division)
15 Mod 4=3 255 mod
10=5
\
Integer Division (discards the decimal
places)
19\4=4
Example 7.1
In this program, you need to insert two text boxes, four labels and one button. Click the
button and enter the code as shown below. When you run the program, it will perform the
four basic arithmetic operations and display the results on the four labels.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim sum, num1, num2, difference, product, quotient As Single
num1 = TextBox1.Text
num2 = TextBox2.Text
sum=num1+num2
difference=num1-num2
product = num1 * num2
quotient=num1/num2
Label1.Text=sum
Label2.Text=difference
Label3.Text = product
Label4.Text = quotient
End Sub
Example 7.2
The program can use Pythagoras Theorem to calculate the length of hypotenuse c given
the length of the adjacent side a and the opposite side b. In case you have forgotten the
formula for the Pythagoras Theorem, it is written as
c^2=a^2+b^2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim a, b, c As Single
a = TextBox1.Text
b = TextBox2.Text
c=(a^2+b^2)^(1/2)
Label3.Text=c
End Sub
Example 7.3: BMI Calculator
A lot of people are obese now and it could affect their health seriously . Obesity has
proven by the medical experts to be a one of the maincauses of various medical problems,
including the heart disease and diabetics. If a person BMI is more than 30, he or she can
be considered obese. You can refer to the following range of BMI values for your weight
status.
Underweight = <18.5
Normal weight = 18.5-24.9
Overweight = 25-29.9
Obesity = BMI of 30 or greater
In order to calculate your BMI, you do not have to consult your doctor, you could just use
a calculator or a home made computer program, this is exactly what I am showing you
here. The BMI calculator is a Visual Basic program that can calculate the body mass
index, or BMI of a person based on the body weight in kilogram and the body height in
meter. BMI can be calculated using the formula weight/( height )
2
, where weight is
measured in kg and height in meter. If you only know your weight and height in lb and
feet, then you need to convert them to the metric system (you could indeed write a VB
program for the conversion).
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim height, weight, bmi As Single
height = TextBox1.Text
weight = TextBox2.Text
bmi = (weight) / (height ^ 2)
Label4.Text = bmi
End Sub
The output is shown in the diagram below. In this example, your height is 1.80m( about 5
foot 11),your weight is 78 kg( about 170 Ib), and your BMI is found to be 23.5. The
reading suggests that you are healthy. (Note; 1 foot=0.3048, 1 lb=.45359237 kilogram)
As
From the above examples, you can see that performing arithmetic operations is relatively
easy in VB2008. Here are more arithmetic projects you can try to programs:
Area of a triangle
Area of a rectangle
Area of a circle
Volume of a cylinder
Volume of a cone
Volume of a sphere
Compound interest
Future value
Mean
Variance
Sum of angles in polygons
Conversion of lb to kg
Conversion of Fahrenheit to Celsius
Lesson 8: String Manipulation
String manipulation is an important part of programming because it helps to process data
that come in the form of non-numeric types such as name, address, gender, city, book
title and more.
8.1 String Manipulation Using + and & signs.
Strings can be manipulated using the & sign and the + sign, both perform the string
concatenation which means combining two or more smaller strings into larger strings.
For example, we can join "Visual" and "Basic" into "Visual Basic" using
"Visual"&"Basic" or "Visual "+"Basic", as shown in the example below
Example 8.1
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim text1, text2, text3 As String
text1 = "Visual"
text2 = "Basic"
text3 = text1 + text2
Label1.Text = text3
End Sub
End Class
The line text3=text1+ text2 can be replaced by text3=text1 & text2 and produced the
same output. However, if one of the variables is declared as numeric data type, you
cannot use the + sign, you can only use the & sign.
Example 8.2
Dim text1, text3 as string
Dim Text2 As Integer
text1 = "Visual"
text2=22
text3=text1+text2
Label1.Text = text3
This code will produce an error because of data mismatch.However, using & instead of +
will be all right.
Dim text1, text3 as string
Dim Text2 As Integer
text1 = "Visual"
text2=22
text3=text1 & text2
Label1.Text = text3
You can combine more than two strings to form a larger strings, like the following
example:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim text1, text2, text3, text4, text5, text6 As String
text1 = "Welcome"
text2 = " to"
text3 = " Visual"
text4 = " Basic"
text5 = " 2008"
text6 = text1 + text2 + text3+text4+Text5
Label1.Text = text6
End Sub
End Class
Running the above program will produce the following screen shot.
8.2 String Manipulation Using VB2008 Built-in Functions
A function is similar to a normal procedure but the main purpose of the function is to
accept a certain input and return a value which is passed on to the main program to finish
the execution.There are numerous string manipulation functions built into VB2008 but I
will only discuss a few here and will explain the rest of them in later lessons.
8.2 (a) The Len Function
The length function returns an integer value which is the length of a phrase or a sentence,
including the empty spaces. The format is
Len (Phrase)
For example,
Len (Visual Basic) = 12 and Len (welcome to VB tutorial) = 22
Example 8.3
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Label1.Text = Len(TextBox1.Text)
End Sub
End Class
The output:
8.2(b) The Right Function
The Right function extracts the right portion of a phrase. The format for Visual Basic 6 is
Right (Phrase, n)
Where n is the starting position from the right of the phase where the portion of the
phrase is going to be extracted. For example,
Right(Visual Basic, 4) = asic
However, this format is not applicable in VB2008. In VB2008, we need use the following
format
Microsoft.VisualBasic.Right("Phrase",n)
Example 8.3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim text1 As String
text1 = TextBox1.Text
Label1.Text = Microsoft.VisualBasic.Right(text1, 4)
End Sub
The above program will return four right most characters of the phrase entered into the
textbox.
The Output
*The reason of using the full reference is because many objects have the Right properties
so using Right on its own will make it ambiguous to VB2008.
8.2(c)The Left Function
The Left function extract the left portion of a phrase. The format is
Microsoft.VisualBasic.Left("Phrase",n)
Where n is the starting position from the left of the phase where the portion of the phrase
is going to be extracted. For example,
Microsoft.VisualBasic.Left (Visual Basic, 4) = Visu .
I Other functions will be discussed in future lessons.
Lesson 9: Controlling Program Flow
In the previous lessons, we have learned how to program code that accept input from the
users and display the output without controlling the program flow. In this chapter, you
will learn how to write VB2008 code that can make decision when it process input from
the users, and control the program flow in the process. Decision making process is an
important part of programming because it will help solve practical problems intelligently
so that it can provide useful output or feedback to the user. For example, we can write a
VB2008 program that can ask the computer to perform certain task until a certain
condition is met, or a program that will reject non-numeric data. In order to control the
program flow and to make decisions, we need to use theconditional operators and
the logical operators together with the If control structure.
9.1 Conditional Operators
The conditional operators are powerful tools that resemble mathematical operators .
These operators allow a VB2008 program to compare data values and then decide what
actions to take, whether to execute a program or terminate the program and more. They
are also known as numerical comparison operators. Normally they are used to compare
two values to see whether they are equal or one value is greater or less than the other
value. The comparison will return a true or false result. These operators are shown in
Table 9.1.
Table 9.1: Conditional Operators
Operator Meaning
= Equal to
> More than
< Less Than
>= More than and equal
<= Less than and equal
<> Not Equal to
9.2 Logical Operators
Sometimes we might need to make more than one comparisons before a decision can be
made and an action taken. In this case, using numerical comparison operators alone is not
sufficient, we need to use additional operators, and they are the logical operators. These
logical operators are shown in Table 9.2.
Table 9.2
Operator Meaning
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
truth
* Normally the above
operators are use to compare
numerical data. However,
you can also compare strings
with the above operators. In
making strings comparison,
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.
9.3 Using the If control structure with the Comparison Operators
To effectively control the VB2008 program flow, we shall use the If control structure
together with the conditional operators and logical operators. There are basically three
types of If control structures, namely If....Then statement, If....Then... Else statement
and If....Then....ElseIf statement.
9.3(a) If....Then Statement
This is the simplest control structure which ask the computer to perform a certain action
specified by the VB expression if the condition is true. However, when the condition is
false, no action will be performed. The general format for the if...then.. statement is
If condition Then
VB expression
End If
Example 9.1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = " You win a lucky prize"
End If
End Sub
* When you run the program and enter a number that is greater than 100, you will see the
"You win a lucky prize" statement. On the other hand, if the number entered is less than
or equal to 100, you don't see any display.
9.3(b) If....Then...Else Statement
Using jus If....Then statement is not very useful in programming and it does not provide
choices for the users. In order to provide a choice, we can use theIf....Then...Else
Statement. This control structure will ask the computer to perform a certain action
specified by the VB expression if the condition is true. And when the condition is false
,an alternative action will be executed. The general format for the if...then..
Else statement is
If condition Then
VB expression
Else
VB expression
End If
Example 9.2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = " Congratulation! You win a lucky prize"
Else
Label2.Text = " Sorry, You dif not win any prize"
End If
End Sub
* When you run the program and enter a number that is greater than 100, the statement
"Congratulation! You win a lucky prize" will be shown. On the other hand, if the number
entered is less than or equal to 100, you will see the "Sorry, You dif not win any prize"
statement
Example 9.3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myNumber, MyAge As Integer
myNumber = TextBox1.Text
MyAge = TextBox2.Text
If myNumber > 100 And myAge > 60 Then
Label2.Text = " Congratulation! You win a lucky prize"
Else
Label2.Text = " Sorry, You did not win any prize"
End If
End Sub
* This program use the logical And operator beside the conditional operators. This means
that both the conditions must be fulfilled in order for the conditions to be true, otherwise
the second block of code will be executed. In this example, the number entered must be
more than 100 and the age must be more than 60 in order to win a lucky prize, any one of
the above conditions not fulfilled will disqualify the user from winning a prize.
9.3(c) If....Then...ElseIf Statement
If there are more than two alternative choices, using jus If....Then....Else statement will
not be enough. In order to provide more choices, we can use theIf....Then...ElseIf
Statement. executed. The general format for the if...then.. Else statement is
If condition Then
VB expression
ElseIf condition Then
VB expression
ElseIf condition Then
VB expression
.
.
Else
VB expression
End If
Example 9.4
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Mark As Integer
Dim Grade as String
Mark = TextBox1.Text
If myNumber >=80 Then
Grade="A"
ElseIf Mark>=60 and Mark<80 then
Grade="B"
ElseIf Mark>=40 and Mark<60 then
Grade="C"
Else
Grade="D"
End If
End Sub
Lesson 10: Select Case Control Structure
In the previous lesson, we have learned how to control the program flow using
the If...ElseIf control structure. In this chapter, you will learn another way to control the
program flow, that is, the Select Case control structure. However, the Select
Case control structure is slightly different from the If....ElseIfcontrol structure . The
difference is that the Select Case control structure basically only make decision on one
expression or dimension (for example the examination grade) while the If ...ElseIf
statement control structure may evaluate only one expression, each If....ElseIf statement
may also compute entirely different dimensions. Select Case is preferred when there exist
many different conditions because using If...Then..ElseIf statements might become too
messy.
10.1 The Select Case...End Select Structure
The Select Case control structure is shown below:
Select Case test expression
Case expression list 1
Block of one or more VB statements
Case expression list 2
Block of one or more VB Statements
Case expression list 3
Block of one or more VB statements
.
.
.
Case Else
Block of one or more VB Statements
End Select
Example 10.1
' Examination Grades
Example 10.2
Dim grade As String
Private Sub
Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
Label1.Text="High
Distinction"
Case "A-"
Label2.Text="Distinction"
Case "B"
Label3.Text="Credit"
Case "C"
Label4.Text="Pass"
Case Else
Label5.Text="Fail"
End Select
In this example, you can use the keyword Is together with the
comparison operators.
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
'Examination Marks
Dim mark As Single
mark = mrk.Text
Select Case mark
Case Is >= 85
Label1.Text= "Excellence"
Case Is >= 70
Label2.Text= "Good"
Case Is >= 60
Label3.Text = "Above Average"
Case Is >= 50
Label4.Text= "Average"
Case Else
Label5.Text = "Need to work harder"
End Select
End Sub
Example 10.3
Example 10.2 could be rewritten as follows:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
'Examination Marks
Dim mark As Single
mark = mrk.Text
Select Case mark
Case 0 to 49
Label1.Text = "Need to work harder"
Case 50 to 59
Label2.Text = "Average"
Case 60 to 69
Label3.Text= "Above Average"
Case 70 to 84
Label4.Text = "Good"
Case Else
Label5.Text= "Excellence"
End Select
End Sub
Lesson 11: Looping
Private Sub CharCount(vStr As String, vChar As String) As Long
Dim I As Long
Dim mCount As Long
mCount = 0
For I = 1 To Len(vStr) If Mid$(vStr, I, 1)=vChar Then
mCount = mCount + 1
Next
CharCount = mCount
End Sub
Link: http://www.ddth.com/showthread.php/206624-s-l-chui-trong-
VB#ixzz2mI3PhNYO
Visual Basic 2008 allows a procedure to be repeated as many times as long as the
processor and memory could support. This is generally called looping . Looping is
required when we need to process something repetitively until a certain condition is met.
For example, we can design a program that adds a series of numbers until the
sum exceeds a certain value, or a program that asks the user to enter data repeatedly until
he/she enters the word 'Finish'.
In Visual Basic 2008, there are three types of Loops, they are the For.....Next loop,
the Do loop. and the While.....End while loop. We shall examine the structure of each
of the loops in details as well as demonstrating them with examples
Example 11.1 a
Dim counter as Integer
For counter=1 to 10
ListBox1.Items.Add (counter)
Next
* The program will enter number 1 to 10 into the list box.
.
11.1 For....Next Loop
The format is:
For counter=startNumber to endNumber (Step increment)
One or more VB statements
Next
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. For its application, you can
refer to example 11.1 d.
Example 11.1b
Dim counter , sum As Integer
For counter=1 to 100 step 10
sum+=counter
ListBox1.Items.Add (sum)
Next
* The program will calculate the sum of the numbers as
follows:
sum=0+10+20+30+40+.....
Example 11.1c
Dim counter, sum As Integer
sum = 1000
For counter = 100 To 5 Step -5
sum - = counter
ListBox1.Items.Add(sum)
Next
*Notice that increment can be negative.
The program will compute the subtraction as follow:
1000-100-95-90-..........
Example 11.1d
Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
Else
ListBox1.Items.Add (
n)
Next
End If
Next
The process will stop
when n is greater than
6.
11.2 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
* Exiting the Loop
Sometime we need exit to exit a loop prematurely because of a
certain condition is fulfilled. The syntax to use is known as Exit
Do. Lets examine the following example
Example 11.2(a)
Do while counter
<=1000
TextBox1.Text=counter
counter +=1
Loop
* The above example
will keep on adding
until counter >1000.
The above example can
be rewritten as
Do
TextBox1.Text=counter
counter+=1
Loop until
counter>1000
Example 11.2(b)
Private Sub
Button1_Click(ByVal
sender As
System.Object, ByVal e
As System.EventArgs)
Handles Button1.Click
Dim sum, n As Integer
Do
n += 1
sum += n
ListBox1.Items.Add(n
& vbTab & sum)
If n = 100 Then
Exit Do
End If
Loop Sub
In the above example,
we find 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 Add method to
populate the ListBox.
The statement
ListBox1.Items.Add(n
& vbTab & sum) will
display the values of n
and sum and uses the
vbTab function to create
a space between the
headings n and sum.
11.3 While ...End While Loop
The structure of a While.End While is very similar to the Do
Loop. it takes the following format:
While condition
Statements
End While
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.
Example 11.3
Dim sum, n As Integer
Private Sub
Button1_Click(ByVal
sender As
System.Object, ByVal e
As System.EventArgs)
Handles Button1.Click
Dim sum, n As Integer
While n <> 100
n += 1
sum = sum + n
ListBox1.Items.Add(n
& vbTab & sum)
End While
End Sub
Lesson 12: Functions-Part I
A function is similar to a normal procedure but the main purpose of the function is to
accept a certain input and return a value which is passed on to the main program to finish
the execution. There are two types of functions, the built-in functions (or internal
functions) and the functions created by the programmers.
The general syntax of a function is
FunctionName (arguments)
The arguments are values that are passed on to the function.
In this lesson, we are going to learn two very basic but useful internal functions of Visual
basic , i.e. the MsgBox( ) and InputBox ( ) functions.
12.1 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 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 ton Table 12.1 for types of command button displayed. The Title argument will
display the title of the message board.
Table 12.1: Style Values
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 constants in place of integers for the second argument to make the
programs more readable. In fact, VB6 will automatically shows up a list of
named constants 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
12.2 shows the values, the corresponding named constant and buttons.
Table 12.2 : Return Values and Command 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 12.1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub
To make the message box looks more sophisticated, you can add an icon besides the
message. There are four types of icons available in VB2008 as shown in Table 12.3
Value Named Constant
Icon
16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
Example 12.2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg = 6 Then
MessageBox.Show("You have clicked the yes button")
ElseIf testMsg = 7 Then
MessageBox.Show("You have clicked the NO button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub
The first argument, Prompt, will display the message. The output is as shown below:
12.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. In VB2005, you can use the following format:
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 enter.
x-position and y-position - the position or tthe coordinates of the input box.
However, the format won't work in VB2008 because InputBox is considered a
namespace. So, you need to key in the full reference to the Inputbox namespace, which is
Microsoft.VisualBasic.InputBox(Prompt, Title, default_text, x-position, y-position)
The parameters remain the same.
Example 12.3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry
Form", "Enter your messge here", 500, 700)
If userMsg <> "" Then
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
The inputbox will appear as shown in the figure below when you press the command
button
Lesson 13: Functions Part II- String Functions
We have learned about the basic concept of function as well as the MsgBox and
InputBox functions in Lesson 12. I. In fact, I have already shown you a few string
manipulation functions in Lesson 8, they are the Len function, the Left function and
the Right Function. In this lesson, we will learn other string manipulation functions.
13.1 The Mid Function
The Mid function is used to retrieve a part of text form a given phrase. The syntax of the
Mid Function is
Mid(phrase, position,n)
where
phrase is the string from which a part of text is to be retrieved.
position is the starting position of the phrase from which the retrieving process
begins.
n is the number of characters to retrieve.
Example 13.1:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myPhrase As String
myPhrase = Microsoft.VisualBasic.InputBox("Enter your phrase")
Label1.Text = Mid(myPhrase, 2, 6)
End Sub
In this example, when a user clicks the command button, an input box will pop up asking
the user to input a phrase. After a phrase is entered and the OK button is pressed, the
label will show the extracted text starting from position 2 of the phrase and the number
of characters extracted is 6. The diagrams are shown below:
The Output
13.2 The Right Function
The Right function extracts the right portion of a phrase. The syntax is
Microsoft.Visualbasic.Right (Phrase, n)
Where n is the starting position from the right of the phase where the portion of the
phrase is going to be extracted. For example:
Microsoft.Visualbasic.Right (Visual Basic, 4) = asic
Example 13.2: The following code extracts the right portion any phrase entered by the
user.
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myword As String
myword = TextBox1.Text
Label1.Text = Microsoft.VisualBasic.Right (myword, 4)
End Sub
13.3 The Left Function
The Left function extracts the left portion of a phrase. The syntax is
Microsoft.Visualbasic.Right (Phrase, n)
Where n is the starting position from the left of the phase where the portion of the phrase
is going to be extracted. For example:
Microsoft.Visualbasic.Left(Visual Basic, 4) = asic
Example 13.3: The following code extracts the left portion any phrase entered by the
user.
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myword As String
myword = TextBox1.Text
Label1.Text = Microsoft.VisualBasic.Left (myword, 4)
End Sub
13.4 The Trim Function
The Trim function trims the empty spaces on both side of the phrase. The syntax is
Trim(Phrase)
.For example, Trim ( Visual Basic ) = Visual basic
Example 13.4
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myPhrase As String
myPhrase = Microsoft.VisualBasic.InputBox("Enter your phrase")
Label1.Text = Trim(myPhrase)
End Sub
13.5 The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase. The syntax is
Ltrim(Phrase)
.For example,
Ltrim ( Visual Basic)= Visual basic
13.6 The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase. The syntax
is
Rtrim(Phrase)
.For example,
Rtrim (Visual Basic ) = Visual Basic
13.7 The InStr function
The InStr function looks for a phrase that is embedded within the original phrase and
returns the starting position of the embedded phrase. The syntax is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the embedded
phrase. For example
Instr(1, Visual Basic, Basic)=8
*The function returns a numeric value.
You can write a program code as shown below:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Label1.Text = InStr(1, "Visual Basic", "Basic")
End Sub
13.8 The Ucase and the Lcase Functions
The Ucase function converts all the characters of a string to capital letters. On the other
hand, the Lcase function converts all the characters of a string to small letters.
The syntax is
Microsoft.VisualBasic.UCase(Phrase)
Microsoft.VisualBasic.LCase(Phrase)
For example,
Microsoft.VisualBasic.Ucase(Visual Basic) =VISUAL BASIC
Microsoft.VisualBasic.Lcase(Visual Basic) =visual basic
13.9 The Chr and the Asc functions
The Chr function returns the string that corresponds to an ASCII code while
the Asc function converts an ASCII character or symbol to the corresponding ASCII
code. ASCII stands for American Standard Code for Insyntaxion Interchange.
Altogether there are 255 ASCII codes and as many ASCII characters. Some of the
characters may not be displayed as they may represent some actions such as the pressing
of a key or produce a beep sound. The syntax of the Chr function is
Chr(charcode)
and the syntax of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% ,
Asc(B)=66, Asc(&)=38
sage 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.
Lesson 14: Functions Part III- Math Functions
14.1 The Abs function
The Abs return the absolute value of a given number. It means it will return only positive
numbers.
The syntax is
Math. Abs (number)
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Number1, Number2 as Single
Number1= TextBox1.Text
Number2=Math.Abs(Number1)
Label1.Text=Number2
End Sub
If Number1= - 100 then Number2=100
* The Math keyword here indicates that the Abs function belong to the Math class.
However, not all mathematical functions belong to the Math class.
14.2 The Exp function
The Exp of a number x is the exponential value of x, i.e. e
x
. For example,
Exp(1)=e=2.71828182
The syntax is Math.Exp (number)
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Exp(num1)
Label1.Text = num2
End Sub
14.3 The Fix Function
The Fix function truncate the decimal part of a positive number and returns the largest
integer smaller than the number. However, when the number is negative, it will return
smallest integer larger than the number. For example, Fix(9.2)=9 but Fix(-9.4)=-9
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Fix(num1)
Label1.Text = num2
End Sub
14.4 The Int Function
The Int is a function that converts a number into an integer by truncating its decimal part
and the resulting integer is the largest integer that is smaller than he number. For example
Int(2.4)=2, Int(6.9)=6 , Int(-5.7)=-6, Int(-99.8)=-100
14.5 The Log Function
The Log function is the function that returns the natural logarithm of a number. For
example, Log(10)=2.302585
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Log(num1)
Label1.Text = num2
End Sub
* The logarithm of num1 will be displayed on label1
14.6 The Rnd( ) Function
The Rnd is very useful when we deal with the concept of chance and probability. The
Rnd function returns a random value between 0 and 1. Random numbers in their original
form are not very useful in programming until we convert them to integers. For example,
if we need to obtain a random output of 6 integers ranging from 1 to 6, which makes the
program behave like a virtual dice, we need to convert the random numbers to integers
using the formulaInt(Rnd*6)+1.
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim num as integer
Randomize( )
Num=Int(Rnd()*6)+1
Label1.Text=Num
End Sub
In this example, Int(Rnd*6) will generate a random integer between 0 and 5 because the
function Int truncates the decimal part of the random number and returns an integer.
After adding 1, you will get a random number between 1 and 6 every time you click the
command button. For example, let say the random number generated is 0.98, after
multiplying it by 6, it becomes 5.88, and using the integer function Int(5.88) will convert
the number to 5; and after adding 1 you will get 6.
14.7 The Round Function
The Round function is the function that rounds up a number to a certain number of
decimal places. The Format is Round (n, m) which means to round a number n to m
decimal places. For example, Math.Round (7.2567, 2) =7.26
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Round(num1, 2)
Label1.Text = num2
End Sub
* The Math keyword here indicates that the Round function belong to the Math class
Lesson 15: Functions Part IV- Formatting Functions
The function to customize the output is the Format function , a very powerful function
which can display numeric values in various forms. There are two types of Format
functions, one of them is the built-in or predefined format while another one can be
defined by the users.
(i) The syntax of the predefined Format function is
Format (n, style argument)
where n is the number to be displayed and style argument is the style of the displayed
number .
Style arguments are listed in Table 15.1.
Table 15.1 List of style arguments
Style
argument
Explanation Example
General
Number
To display the number
without having separators
between thousands.
Format(8972.234, General
Number)=8972.234
Fixed To display the number
without having separators
between thousands and
rounds it up to two
decimal places.
Format(8972.2, Fixed)=8972.23
Standard To display the number
with separators or
separators between
thousands and rounds it up
to two decimal places.
Format(6648972.265, Standard)=
6,648,972.27
Currency To display the number
with the dollar sign in
front, has separators
between thousands as well
as rounding it up to two
decimal places.
Format(6648972.265, Currency)=
$6,648,972.27
Percent Converts the number to the
percentage form and
displays a % sign and
rounds it up to two
decimal places.
Format(0.56324, Percent)=56.32 %
Example 15.1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, "General Number")
Label2.Text = Format(8972.2, "Fixed")
Label3.Text = Format(6648972.265, "Standard")
Label4.Text = Format(6648972.265, "Currency")
Label5.Text = Format(0.56324, "Percent")
End Sub
The Output window is shown below:
ii) The syntax of the user-defined Format function is
Format (n, users format)
Although it is known as user-defined format, we still need to follows certain formatting
styles. Examples of user-defined formatting style are listed in Table 15.2
Table15.2: User-Defined format
Example Explanation Output
Format(781234.57,0) Rounds to whole number without
separators between thousands.
781235
Format(781234.57,0.0) Rounds to 1 decimal place without
separators between thousands.
781234.6
Format(781234.576,0.00) Rounds to 2 decimal places without
separators between thousands.
781234.58
Format(781234.576,#,##0.00) Rounds to 2 decimal places with
separators between thousands.
781,234.58
Format(781234.576,$#,##0.00) Shows dollar sign and rounds to 2
decimal places with separators
between thousands.
$781,234.58
Format(0.576,0%) Converts to percentage form
without decimal places.
58%
Format(0.5768,0.00%) Converts to percentage form with 2
decimal places.
57.68%
Example 15.2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, "0.0")
Label2.Text = Format(8972.2345, "0.00")
Label3.Text = Format(6648972.265, "#,##0.00")
Label4.Text = Format(6648972.265, "$#,##0.00")
Label5.Text = Format(0.56324, "0%")
End Sub
The Output window is shown in the diagram below:
The Output window is shown in the diagram below:
Lesson 16: Functions Part V- Formatting Date and Time
6.1 Formatting Date and time using predefined formats
Date and time can be formatted using predefined formats and also user-defined formats.
The predefined formats of date and time are shown in Table 16.1.
Table 16.1 Predefined formats of date and time
Format Explanation
Format (Now, General date) Formats the current date and time.
Format (Now, Long Date) Displays the current date in long format.
Format (Now, Short date) Displays current date in short format
Format (Now, Long Time) Display the current time in long format.
Format (Now, Short Time) Display the current time in short format.
* Instead of "General date", you can also use the abbreviated format "G" , i.e. Format
(Now, "G"). And for "Long Time", you can use the abbreviated format "T". As for
"Short Time", you may use the abbreviated format "t"
Example 16.1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Label1.Text = Format(Now, "General Date")
Label2.Text = Format(Now, "Long Date")
Label3.Text = Format(Now, "short Date")
Label4.Text = Format(Now, "Long Time")
Label5.Text = Format(Now, "Short Time")
End Sub
The output is shown in the diagram below:
The output is shown in the diagram below:
16.2 Formatting Date and time using user-defined formats
Beside using the predefined formats, you can also use the user-defined formatting
functions. The general format of a user-defined for date/time is
Format (expression,style)
Table 16.2 Some of the user-defined format functions for date and time
Format Explanation
Format (Now, M) Displays current month and date
Format (Now, MM) Displays current month in double digits.
Format (Now, MMM) Displays abbreviated name of the current month
Format (Now, MMMM) Displays full name of the current month.
Format (Now, dd/MM/yyyy) Displays current date in the day/month/year format.
Format (Now, "MMM,d,yyyy")
Displays current date in the Month, Day, Year Format
Format (Now, "h:mm:ss tt")
Dispalys current time in hour:minute:second format and show
am/pm
Format (Now, "MM/dd/yyyy
h:mm:ss)
Dispalys current date and time in hour:minute:second format
Example 16.2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
Label1.Text = Format(Now, "M")
Label2.Text = Format(Now, "MM")
Label3.Text = Format(Now, "MMM")
Label4.Text = Format(Now, "MMMM")
Label5.Text = Format(Now, "dd/MM/yyyy")
Label6.Text = Format(Now, "MMM,d,yyyy")
Label7.Text = Format(Now, "h:mm:ss tt")
Label8.Text = Format(Now, "MM/dd/yyyy h:mm:ss tt")
End Sub
The output is shown in the diagram below:
Lesson 17: Using Check Box
The Check box is a very useful control in Visual Basic 2008. It allows the user to select
one or more items by checking the checkbox/checkboxes concerned. For example, in the
Font dialog box of any Microsoft Text editor like FrontPage, there are many checkboxes
under the Effects section such as that shown in the diagram below. The user can choose
underline, subscript, small caps, superscript, blink and etc. In Visual Basic, you may
create a shopping cart where the user can click on checkboxes that correspond to the
items they intend to buy, and the total payment can be computed at the same time as
shown in Example 17.1.
Example 17.1:Shopping Cart
Private Sub BtnCalculate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnCalculate.Click
Const LX As Integer = 100
Const BN As Integer = 500
Const SD As Integer = 200
Const HD As Integer = 80
Const HM As Integer = 300
Const AM As Integer = 150
Dim sum As Integer
If CheckBox1.Checked = True Then
sum += LX
End If
If CheckBox2.Checked = True Then
sum += BN
End If
If CheckBox3.Checked = True Then
sum += SD
End If
If CheckBox4.Checked = True Then
sum += HD
End If
If CheckBox5.Checked = True Then
sum += HM
End If
If CheckBox6.Checked = True Then
sum += AM
End If
Label5.Text = sum.ToString("c")
Here is another example
Example 17.2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Const large As Integer = 10.0
Const medium As Integer = 8
Const small As Integer = 5
Dim sum As Integer
If CheckBox1.Checked = True Then
sum += large
End If
If CheckBox2.Checked = True Then
sum += medium
End If
If CheckBox3.Checked = True Then
sum += small
End If
Label5.Text = sum.ToString("c")
The Check box is a very useful control in Visual Basic 2008. It allows the user to select
one or more items by checking the checkbox/checkboxes concerned. For example, in the
Font dialog box of any Microsoft Text editor like FrontPage, there are many checkboxes
under the Effects section such as that shown in the diagram below. The user can choose
underline, subscript, small caps, superscript, blink and etc. In Visual Basic, you may
create a shopping cart where the user can click on checkboxes that correspond to the
items they intend to buy, and the total payment can be computed at the same time as
shown in Example 17.1.
Example 17.1:Shopping Cart
The Code
Private Sub BtnCalculate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnCalculate.Click
Const LX As Integer = 100
Const BN As Integer = 500
Const SD As Integer = 200
Const HD As Integer = 80
Const HM As Integer = 300
Const AM As Integer = 150
Dim sum As Integer
If CheckBox1.Checked = True Then
sum += LX
End If
If CheckBox2.Checked = True Then
sum += BN
End If
If CheckBox3.Checked = True Then
sum += SD
End If
If CheckBox4.Checked = True Then
sum += HD
End If
If CheckBox5.Checked = True Then
sum += HM
End If
If CheckBox6.Checked = True Then
sum += AM
End If
Label5.Text = sum.ToString("c")
Here is another example
Example 17.2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Const large As Integer = 10.0
Const medium As Integer = 8
Const small As Integer = 5
Dim sum As Integer
If CheckBox1.Checked = True Then
sum += large
End If
If CheckBox2.Checked = True Then
sum += medium
End If
If CheckBox3.Checked = True Then
sum += small
End If
Label5.Text = sum.ToString("c")
Example 17.3
In this example, the user can enter text into a textbox and format the font using the three
checkboxes that represent bold, italic and underline.
The code is as follow:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Bold)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not
FontStyle.Bold)
End If
End Sub
Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles CheckBox2.CheckedChanged
If CheckBox2.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not
FontStyle.Italic)
End If
End Sub
Private Sub CheckBox3_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles CheckBox3.CheckedChanged
If CheckBox3.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or
FontStyle.Underline)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not
FontStyle.Underline)
End If
End Sub
* The above program uses the CheckedChanged event to respond to the user selection by
checking a particular checkbox, it is similar to the click event. The statement
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic)
will retain the original font type but change it to italic font style.
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not
FontStyle.Italic)
will also retain the original font type but change it to regular font style. (The other
statements emply the same logic)
Lesson 18: Using Radio Button
The radio button is also a very useful control in Visual Basic 2008. However, it operates
differently from the check boxes. While the checkboxes work independently and allows
the user to select one or more items , radio buttons are mutually exclusive, which means
the user can only choose one item only out of a number of choices. Here is an example
which allows the users to select one color only.
Example 18.1
The Code:
Dim strColor As String
Private Sub RadioButton8_CheckedChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles RadioButton8.CheckedChanged
strColor = "Red"
End Sub
Private Sub RadioButton7_CheckedChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles RadioButton7.CheckedChanged
strColor = "Green"
End Sub
Private Sub RadioYellow_CheckedChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles RadioYellow.CheckedChanged
strColor = "Yellow"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Label2.Text = strColor
End Sub
Although the user may only select one item at a time, he may make more than one
selection if those items belong to different categories. For example, the user wish to
choose T-shirt size and color, he needs to select one color and one size, which means one
selection in each category. This is easily achieved in VB2008 by using the Groupbox
control under the containers categories. After inserting the Groupbox into the form, you
can proceed to insert the radio buttons into the Groupbox. Only the radio buttons inside
the Groupbox are mutually exclusive, they are not mutually exclusive with the radio
buttons outside the Groupbox. In Example 18.2, the users can select one color and one
size of the T-shirt.
Example 18.2
Dim strColor As String
Dim strSize As String
Private Sub RadioButton8_CheckedChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles RadioButton8.CheckedChanged
strColor = "Red"
End Sub
Private Sub RadioButton7_CheckedChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles RadioButton7.CheckedChanged
strColor = "Green"
End Sub
Private Sub RadioYellow_CheckedChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles RadioYellow.CheckedChanged
strColor = "Yellow"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Label2.Text = strColor
Label4.Text = strSize
End Sub
Private Sub RadioXL_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioXL.CheckedChanged
strSize = "XL"
End Sub
Private Sub RadioL_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioL.CheckedChanged
strSize = "L"
End Sub
Private Sub RadioM_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioM.CheckedChanged
strSize = "M"
End Sub
Private Sub RadioS_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioS.CheckedChanged
strSize = "S"
End Sub
Mt s cu lnh v hm trong VB
GII THIU S LC
Tn bi vit:
Mt s cu lnh v hm trong VB
Tc gi:
Trng Vnh Phc
Cp bi vit:
Cn bn
Tm tt:
M t Mt s cu lnh v hm c sn trong VB
Ngi gi:
vinhphuoc91
vo lc 15/04/08, 14:06
Lin kt:
Xem ton b Ch trn Din n
THNG K
nh gi :
(im nh gi: Cha nh gi)
Xem / Bnh lun:
41957 / 3 lt
Tng s nh km:
0
Bnh lun cui cng:
06/03/13, 07:59
gi bi lesptin
Chia s bn b qua:
NI DUNG BI VIT
Cc Pht biu v hm chun trong Visual Basic
I. CC PHT BIU IU KHIN
a. Cu trc chn la IF :
IF < Biu thc Logic iu kin> THEN
Khi iu kin ng
Ni dng cc cu lnh cn thc hin
ELSE
Khi iu kin sai
Ni dng cc cu lnh cn thc hin
END IF
- Trong cu lnh khng nht thit phi s dng ELSE, c th b qua n ty vo mc ch
b. Cu trc SELECT CASE :
SELECT CASE <Bin hay mt biu thc>
CASE <gi tr nht ca bin hay ca 1 biu thc>
CASE <gi tr hai ca bin hay ca 1 biu thc>
CASE <gi tr n ca bin hay ca 1 biu thc>
CASE ELSE
Khi tt c cc gi tr trn u khng ng
Ni dung cc lnh cn thc hin
END SELECT
- Tng t nh IF trong cu lnh khng nht thit phi s dng CASE ELSE, c th b
qua n ty vo mc ch
II. CC CU TRC LP :
a. Cu trc DO WHILE ... LOOP :
DO WHILE <Biu thc iu kin>
Cc cu lnh mun thc thi biu thc iu kin cn ng
LOOP Quay v DO WHILE kim tra biu thc iu kin
- Khi VB thc hin vng lp ny, u tin s kim tra biu thc iu kin. Nu Sai, n s
dng li vng lp ngay v thc hin cu lnh k tip cn nu ng th thc hin cc lnh
bn trong. Vy cu trc DO WHILE LOOP thc hin cc cu lnh bn trong n khi
iu kin ng.
b. Cu trc DO LOOP WHILE :
DO
Cc cu lnh thc thi
LOOP WHILE <Biu thc iu kin> Quay v DO nu iu kin ng
- Khi VB thc hin vng lp ny, u tin s thc hin khi lnh bn trong n ngai. Sau
khi thc hin n s kim tra iu kin. Nu ng s quay li cn sai th dng vng lp.
c. Cu trc DO LOOP UNTIL :
DO
Cc cu lnh thc thi
LOOP UNTIL <Biu thc iu kin> Quay v DO nu iu kin sai
- Ging nh DO LOOP WHILE nhng n s thot khi vng lp khi iu kin ng
d. Cu trc FOR NEXT
FOR <Bin = Gi tr u> TO <Gi tr cui> [STEP khong tng]
Phn cc lnh thc thi khi bin cha t gi tr cui
NEXT Bin
(Phn Step c th c hoc khng, VB ngm hiu l +1)
- Cu trc ny lp vi s ln bit trc, lp t Gi tr u n gi tr cui (gi tr u c
th ln hn gi tr cui nu step <0)
III. MT S LNH :
1 .EXIT FOR
Cu lnh : EXIT FOR
Lng vo trong vng lp For khi mun dng li vng lp bt c lc no.
2 .EXIT DO
Cu lnh : EXIT DO
Lng vo trong vng lp c cu trc DO khi mun dng li vng lp bt c lc no.
3 .EXIT FOR
Cu lnh : EXIT SUB
Thot khi th tc m bt c lc no m khng cn thc hin cc lnh bnh trong n.
4 .END
- Chm dt chng trnh ngay, tt c cc ca s chng trnh u ng li khi bn thc
hin thao tc ny.
5. Beep
- Pht ra ting ku Beep
6. Lnh Date :
Cho php bn t li ngy h thng, hay ly ngy h thng
C php : DATE = <ngy bn t>
VD: Date = #June 12, 2000#
7. TIME
- Cho php t li gi h thng, hay ly gi h thng
C php : TIME = <Gi bn t>
VD: Time = # 5 : 12 : 45 PM #
8.LOAD
- Np 1 form (dng n m 1 Form)
C php : LOAD <Tn Form>
lm xut hin hoc n i s dng phng thc SHOW, v d form1.Show hay
form.Hide
9. Lnh ChDrive
Dng i a lm vic
C php : ChDrive <Tn a :>
10. MkDir
Dng to mt th mc mi trn a
C Php : MkDir <ng dn>
V d : MkDir D:\Caulacbovb
11. Lnh ChDir
Lnh ny dng thay i th mc lm vic ti a ang lm vic
C php : ChDir <ng dn th mc>
12. Lnh RmDir :
Dng xa 1 th mc rng.
C php : RmDir <ng dn th mc>
13. Lnh KILL
- Xa 1 hay nhiu tp tin trn a
C php : KILL <ng dn n tp tin>
V d : Kill D:\vinhphuoc.txt
Kill D:\*.txt
14. Lnh NAME :
Dng i tn tp tin
C php : NAME <ng dn tp tin cn i tn> AS <ng dn v tn tp mi>
V d : NAME C:\Phuoc.txt AS C:\VINHPHUOC91.txt
15. Lnh AppActive
Dng kch hot mt ca s ca mt chng trinhg ang chy trn Windows
C php : AppActive title [Wait]
Wait : Nu l False th chng trnh s kch hot ngay khi thc hin lnh gi ny (VB
ngm hiu l False).
V d : AppActive Microsoft Word
IV. MT S HM :
Tt c cc hm u c dng : Tn hm (cc i s)
1. Hm Abs (Number)
Tr v mt gi tr l gi tr tuyt i ca Number
2. Hm Sin (Number as Double)
Tr v mt s thc l Sin ca mt gc (tnh bng n v Radian)
3. Hm Cos (Number as Double)
Tr v mt s thc l Cos ca mt gc (tnh bng n v Radian)
4. Hm Tan (Number as Double)
Tr v mt s thc l Tan ca mt gc (tnh bng n v Radian)
5. Hm Atn (Number as Double)
Tr v mt s thc l ArcTan ca mt gc (tnh bng n v Radian)
6. Hm Int (Number) :
Tr v phn nguyn ca Number nu n l s dng, cn nu s m th c gi tr nh hn
phn nguyn 1 n v
7. Hm Fix (Number)
Tr v phn nguyn ca Number nu n l s dng, cn nu s m th c gi tr ln hn
phn nguyn 1 n v
8. Hm Sgn (Number)
Tr v mt s nguyn
Nu Number > 0 s tr v 1
Nu Number < 0 s tr v -1
Nu Number = 0 s tr v 0
9. Hm Sqr (Number)
Tr v cn bc hai ca Number
10. Hm Exp (x)
a ra e ly tha x, e l c s Logarit t nhin. Hm tr v mt s thc
11. Hm Log (x)
a ra Logarit t nhin ca x
12. Hm Round (Expression [s])
Hm ny s lm trn s
[,s] : s lm trn qua chm thp phn.
VD : Round(9.7) = 10
Round (9.785 , 2) = 9.79
13. Rnd (Number) ;
To 1 s ngu nhin l 1 s thc t 0 n Number, vi Number l 1 s nguyn.
14. Hm Now :
Hm ny tr v ngy thng nm v thi gian hin hnh.
15. Hm Day (NgayThangNam)
Tr v ngy trong NgayThangNam m bn ghi.
Ta thng s dng Day(Now) ly ngy h thng
16. Hm Month (NgayThangNam)
Tr v Thng trong NgayThangNam m bn ghi.
Ta thng s dng Month(Now) ly thng h thng
17. Hm Year (NgayThangNam)
Tr v Nm trong NgayThangNam m bn ghi.
Ta thng s dng Year(Now) ly nm h thng
18. Hm Weekday (NgayThangNam)
Tr v ngy th my trong tun ng vi NgayThangNam m bn nhp vo
Ta c th s dng Weekday(Now) ly th ca ngy hin ti
19. Hm Hour (ThoiGian)
Tr v gi ng vi ThoiGian m bn nhp vo
Ta c th s dng Hour(Now) ly gi ca h thng hin ti
20. Hm Minute (ThoiGian)
Tr v pht ng vi ThoiGian m bn nhp vo
Ta c th s dng Minute(Now) ly pht ca h thng hin ti
21. Hm Second (ThoiGian)
Tr v giy ng vi ThoiGian m bn nhp vo
Ta c th s dng Second(Now) ly giy ca h thng hin ti
22. Hm Replace(chuoi, chuoicantim, chuoithaythe, Vitrithaythe, solanthaythe)
Hm ny s tr v mt chui mi theo ngha nh trn. V d
Replace(2322 , 2 , 5 , 1 , 2) = 5352
Replace(2322 , 2 , 5 , 2 , 2) = 355
23. Hm Val(String)
Hm ny c tc dng i 1 chui thnh 1 s, nu chui ny c k t u l k t th s tr
v 0
24. Hm Str (Number)
Ngc li Hm Val.
Hm ny c tc dng i 1 s thnh 1 chui.
25 Hm QBColor (color)
S cho bn mu ca mt i tng no , th hin t 0 n 15.
V d : QBColor (0) s cho mu en, QBColor (4) s cho mu ,
26. Hm RGB (Red, Green, Blue)
Chn mt mu theo mt t l no ngoi cc mu t 0 15. N s l s kt hp ca 3
mu.
27. Hm Asc (String)
S tr v mt con s, con s ny l m ASCII ca k t String, nu l mt chui gm
nhiu k t th k t s ly k t u tin.
28. Hm Chr(CharCode)
Hm tr v mt k t tng ng vi mt m ASCII no .
ChrCode l m ASCII ca k t m bn cn bit
29. Hm Len (String)
Tr v d di ca chui String, k c khong trng
30. Hm Ltrim (String)
Hm tr v chui mi sau khi ct b cc khong trng bn tri chui String
31. Hm Rtrim (String)
Hm tr v chui mi sau khi ct b cc khong trng bn phi chui String
32. Hm Trim (String)
Hm tr v chui mi sau khi ct b cc khong trng bn tri v bn phi chui String
33. Hm Left (String,n)
Tr v mt chui k t (k c khong trng) c ct t bn tri ca chui String, s k t
ct ly l n.
34. Hm Right (String,n)
Tr v mt chui k t (k c khong trng) c ct t bn phi ca chui String, s k
t ct ly l n.
35. Hm MID (String, Start, [Length])
Tr v mt chui, chui ny c ly t chui String v bt u t Start v ly Length k
t
Nu Length b trng hoc ln hn di String th coi nh ly t v tr Start cho n hn.
36. Hm Space (Number)
Hm tr v mt chui gm Number khong trng
37. Hm String (Number, Character)
Tr v mt chui gm Number k t ging nhau v ging Character
[b]38. Hm InStr (Start, String1, String2, Compare)[/b]
Hm ny dng tm mt chui con c nm trong chui m hay khng, nu tm thy th
s cho bit nm v tr th my ca chui m.
Start : Tm bt u t v tr Start trong chui m, nu khng ghi th tm v tr u tin
String1: Chui m
String2 : Chui con
Compare : c cc gi tr 0, 1, 2
+ 0 : so snh chnh xc tng k t, y l gi tr mc nhin
+ 1 : So snh khng phn bit ch hoa v ch thng
+ 2 : ch dng trong khi lp trnh cho MS Access
* Khi dng n i s Compare th i s Start khng c b trng
39. Hm Ucase (String)
Tr v my chui k t vit hoa ca chui String
40. Hm Lcase (String)
Tr v mt chui k t vit thng ca chui String
41. Hm Format (Value, format)
Hm ny dng nh dng theo ca bn
Value : Gi tr cn nh dng
Format : Cc k hiu nh dng.
0 nu c gi tr th th hin gi tr , nu khng c th ghi s 0. Nu s 0 t hn th gi tr
vn c ghi y
# : Th hin cc gi tr tng ng, nu k t s v tr khng c th b qua, nu # t
hn th gi tr vn c ghi y .
$ : Du $ bn c th dng chung vi s 0 hay #
. : Du ngn cch phn thp phn
, : Du ngn cch phn nghn
% : Khi c k hiu phn trm ny trong i s Format, con s s t thm % vo sau
dd/mm/yyyy : nh dng Ngy Thng Nm, vi i s Value = Now
hh:mm:ss AM/PM : nh dng Gi pht giy theo dng, vi i s Value = Now
hh:mm:ss AM/PM dd/mm/yyyy : nh dng Gi pht giy va nh dng ngy thng
nm theo dng, vi i s Value = Now
hh:mm : nh dng ch c gi v pht vi Value=Now.
V d :
Format(12345.5 , 0000000.00) = 012345.50
Format(12345.5, ######.##) = 12345.5
Format(12345.5, $###.##) = $12345.5
Format(0.34, ###%) = 34%
42. Hm IIF(<iu kin>, Truepart, Falsepart)
Hm ny s tr v gi tr truepart nu iu kin ng v cho False khi iu kin sai
Hm ny l cch vit ngn hn ca IFEND IF
V d txt1.text = IFF(x<400,Lng bn cn thp,Bn c lng cao)
Top