# Thread: VISUAL BASIC part 2

1. ## VISUAL BASIC part 2

Here goes part 2:

Lesson 7 : Controlling Program Flow
7.1 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 etc. These operators are shown in Table 7.1.
Table 7.1: Conditional Operators

Operator Meaning
= Equal to
> More than
< Less Than
>= More than and equal
<= Less than and equal
<> Not Equal to
* You can also compare strings with the above operators. However, there are certain rules to follows: Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D".......<"Z" and number are less than letters.

7.2 Logical Operators
In addition to conditional operators, there are a few logical operators which offer added power to the VB programs. There are shown in Table 7.2.
Table 7.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

7.3 Using If.....Then.....Else Statements with Opreators
To effectively control the VB program flow, we shall use If...Then...Else statement together with the conditonal operators and logical operators.
The general format for the if...then...else statement is
If conditions Then
VB expressions
Else
VB expressions
End If
* any If..Then..Else statement must end with End If. Sometime it is not necessary to use Else.
Example:
Private Sub OK_Click()
firstnum = Val(usernum1.Text)
secondnum = Val(usernum2.Text)
total = Val(sum.Text)
If total = firstnum + secondnum And Val(sum.Text) <> 0 Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If
End Sub
Lesson 8 : More On Program Control
8.1 Select Case
If you have a lot of conditional statements, using If..Then..Else could be very messy. For multiple conditional statements, it is better to use Select Case
The format is :
Select Case expression
Case value1
Block of one or more VB statements
Case value2
Block of one or more VB Statements
Case value3
Block of one or more VB statements
Case value4
.
.
.
Case Else
Block of one or more VB Statements
End Select
* The data type specified in expression must match that of Case values.

8.2 Examples
Example 8.1
' Examination Grades
Dim grade As String
Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
result.Caption="High Distinction"
Case "A-"
result.Caption="Distinction"
Case "B"
result.Caption="Credit"
Case "C"
result.Caption="Pass"
Case Else
result.Caption="Fail"
End Select
*Please note that grade is a string, so all the case values such as "A" are of String data type.

Example 8.2
Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text

Select Case mark
Case Is >= 85

comment.Caption = "Excellence"
Case Is >= 70

comment.Caption = "Good"
Case Is >= 60
comment.Caption = "Above Average"
Case Is >= 50
comment.Caption = "Average"
Case Else
comment.Caption = "Need to work harder"
End Select
End Sub
* Note we use the keyword Is here to impose the conditions. This is generally used for numeric data.

Example 8.3
Example 8.2 could be rewritten as follows:
Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text

Select Case mark
Case 0 to 49

comment.Caption = "Need to work harder"

Case 50 to 59

comment.Caption = "Average"

Case 60 to 69
comment.Caption = "Above Average"
Case 70 to 84
comment.Caption = "Good"
Case Else
comment.Caption = "Excellence"
End Select
End Sub
Lesson 9: Looping
Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called looping .

9.1 Do Loop
The format are
a) Do While condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While condition
c) Do Until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until condition
Example 9.1
Do while counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter >1000.
The above example can be rewritten as
Do
num.Text=counter
counter=counter+1
Loop until counter>1000

9.2 For....Next Loop
The format is:

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

Example:
(a) For counter=1 to 10
display.Text=counter

Next
(b) For counter=1 to 1000 step 10
counter=counter+1

Next
(c) For counter=1000 to 5 step -5
counter=counter-10
Next
Lesson 10: Introduction to VB Functions- Part I
Functions are similar to normal procedures but the main purpose of the functions is to accept certain inputs and pass them on to the main program to finish the execution. They are two types of function, the built-in functions(or internal functions) and the functions created by the programmers.
The general format of a function is

functionName(arguments)
where arguments are values that are passed on to the functions.
In this lesson, we are going to learn two very basic but useful internal functions, i.e. the MsgBox( ) and InputBox ( ) functions.
10.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 message box format is as follows:
yourMsg=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer Table 10.1 for types of command button displayed. The Title argument will display the title of the message board.
Table 10.1: Style Values

Style Value Named Constant Buttons Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
We can use named constant in place of integers for the second argument to make the programs more readable. Infact, VB6 will automatically shows up a list of names constant where you can select one of them.
example: yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")
and yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")
are the same.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Table 10.2 shows the values, the corresponding named constant and buttons.
Table 10.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 10.1
i. The Interface:
You draw three command buttons and a label as shown in Figure 10.1
Figure 10.1

ii. The procedure for the test button:

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

When a 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 sucessful" will be diplayed 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. The are four types of icons available in VB as shown in Table 10.3

Table 10.3

Value Named Constant Icon
16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

Example 10.2
In this example, the following message box will be displayed:
Figure 10.3

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

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

10.2 The InputBox( ) Function
An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text. The format is

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)
myMessage is a variant data type but typically it is declared as string, which accept the message input bu the users.The arguments are explained as follows:

• Prompt - The message displayed normally as a question asked.
• Title - The title of the Input Box.
• default-text - The default text that appears in the input field where users can use it as his intended input or he may change to the message he wish to key in.
• x-position and y-position - the position or the coordinate of the input box.
Example 10.3
i. The Interface
Figure 10.4

ii. The procedure for the OK button
Private Sub OK_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your messge here", 500, 700)
If userMsg <> "" Then
message.Caption = userMsg
Else
message.Caption = "No Message"
End If
End Sub
When a user click the OK button, the input box as shown in Figure 10.5 will appear. After user entering the message and click OK, the message will be displayed on the caption, if he click Cancel, "No message" will be displayed.

Lesson 11: Introduction to VB Functions- Part II
11.1 Creating Your Own Functions
The general format of a function is as follows:
Public Function functionName (Arg As dataType,..........) As dataType
or
Private Function functionName (Arg As dataType,..........) As dataType
* Public indicates that the function is applicable to the whole program and
Private indicates that the function is only applicable to a certain module or procedure.

Example 11.1
In this example, a user can calculate future value of a certain amount of money he has today based on the interest rate and the number of years from now(supposing he will invest this amount of money somewhere). The calculation is based on the compound interest rate.

Public Function FV(PV As Variant, i As Variant, n As Variant) As Variant
'Formula to calculate Future Value(FV)
'PV denotes Present Value
FV = PV * (1 + i / 100) ^ n
End Function
Private Sub compute_Click()
'This procedure will calculate Future Value
Dim FutureVal As Variant
Dim PresentVal As Variant
Dim interest As Variant
Dim period As Variant
PresentVal = PV.Text
interest = rate.Text
period = years.Text
FutureVal = FV(PresentVal, interest, period)
MsgBox ("The Future Value is " & FutureVal)
End Sub
Example 11.2
The following program will automatically compute examination grades based on the marks that a student obtained.

Public Function grade(mark As Variant) As String
Select Case mark
Case Is >= 80
grade = "A"
Case Is >= 70
grade = "B"
Case Is >= 60
grade = "C"
Case Is >= 50
grade = "D"
Case Is >= 40
grade = "E"
Case Else
grade = "F"
End Select
End Function
Private Sub compute_Click()
grading.Caption = grade(mark)

End Sub
Private Sub End_Click()
End
End Sub
Lesson 12: Creating VB Functions For MS Excel
12.2 The Needs to Create User-Defined Functions in MS-Excel
You can create your own functions to supplement the built-in functions in Microsoft Excel spreadsheet which are quite limited. These functions could be very useful and powerful if you know how to program them properly. One main reason we need to create user defined functions is to enable us to customize our spreadsheet environment for individual needs. For example, we might need a function that could calculate commissions payment based on the sales volume, which is quite difficult if not impossible by using the built-in function alone. Lets look at the table below:
Table 12.1: Commissions Payment Table
Sales Volume(\$) Commissons
<500 3%
<1000 6%
<2000 9%
<5000 12%
>5000 15%
In the above table, if a saleman attain a sale volume of \$6000, he will be paid \$6000x12%=\$720.00. A visual basic function to calculate the commissions could be written as
follows:
Function Comm(Sales_V As Variant) as Variant
If Sales_V <500 Then
Comm=Sales_V*0.03
Elseif Sales_V>=500 and Sales_V<1000 Then
Comm=Sales_V*0.06
Elseif Sales_V>=1000 and Sales_V<2000 Then
Comm=Sales_V*0.09
Elseif Sales_V>=200 and Sales_V<5000 Then
Comm=Sales_V*0.12
Elseif Sales_V>=5000 Then
Comm=Sales_V*0.15
End If
End Function
12.2 Using Microsoft Excel Visual Basic Editor
Figure 12.1: Inserting Ms_Excel Visual Basic Editor

Upon clicking the Visual Basic Editor, the VB Editor windows will appear as shown in figure 12.2. To create a function, type in the function as illustrated in section 12.1 above After typing, save the
file and then return to the Excel windows.
Figure 12.2 : The VB Editor

In the Excel windows, type in the titles Sales Volume and Commissions in any two cells. By refering to figure 12.3, key-in the Comm function at cell C4 and by referencing the value in cell B4, using the format Comm(B4). Any value appear in cell B4 will pass the value to the Comm function in cell C4. For the rest of the rows, just copy the formula by draging the bottom right corner of cell C4 to the required cells, and a nice and neat table that show the commisions will automatically appear. It can also be updated anytime

Figure 12.3: MS Excel Windows- Sales Volume

Lesson 13: Arrays
13.1 Introduction to Arrays
By definition, an array is a list of variables, all with the same data type and name. When we work with a single item, we only need to use one variable. However, if we have a list of items which are of similar type to deal with, we need to declare an array of variables instead of using a variable for each item. For example, if we need to enter one hundred names, instead of declaring one hundred different variables, we need to declare only one array. We differentiate each item in the array by using subscript, the index value of each item, for example name(1), name(2),name(3) .......etc.

13.2 Declaring Arrays
We could use Public or Dim statement to declare an array just as the way we declare a single variable. The Public statement declares an array that can be used throughout an application while the Dim statement declare an array that could be used only in a local procedure.
The general format to declare an array is as follow:
Dim arrayName(subs) as dataType
where subs indicates the last subscript in the array.
Example 13.1
Dim CusName(10) as String
will declare an array that consists of 10 elements if the statement Option Base 1 appear in the declaration area, starting from CusName(1) to CusName(10). Otherwise, there will be 11 elements in the array starting from CusName(0) through to CusName(10)
Example 13.2
Dim Count(100 to 500) as Integer
declares an array that consists of the first element starting from Count(100) and ends at Count(500)

13.3 Sample Programs
The codes
Dim studentName(10) As String
Dim num As Integer
Private Sub addName()
For num = 1 To 10
studentName(num) = InputBox("Enter the student name", "Enter Name", "", 1500, 4500)
If studentName(num) <> "" Then
Form1.Print studentName(num)
Else
End
End If
Next
End Sub

Private Sub Exit_Click()
End
End Sub
Private Sub Start_Click()
Form1.Cls
addName
End Sub
The above program accepts data entry through an input box and displays the entries in the form itself. As you can see, this program will only allows a user to enter 10 names each time he click on the start button.
(ii)
The Codes
Dim studentName(10) As String
Dim num As Integer
Private Sub addName( )
For num = 1 To 10
studentName(num) = InputBox("Enter the student name")
List1.AddItem studentName(num)
Next
End Sub

Private Sub Start_Click()
addName
End Sub
The above program accepts data entries through an InputBox and displays the items in a list box.
Lesson 14: Working with Files
14.1 Introduction
Up until lesson 13 we are only creating programs that could accept data at runtime, when a program is terminated, the data also disappear. Is it possible to save data accepted by a VB
program into a storage device, such as a hardisk or diskette, or even CDRW? The answer is possible. Is this chapter, we will learn how to create files by writing them into a storage device and then retrieve the data by reading the contents of the files using customized VB programs.
14.2 Creating files
To create a file , use the following command
Open "fileName" For Output As #fileNumber
Each file created must have a file name and a file number for identification. As for file name, you must also specify the path where the file will reside.
For example
Open "c:\My Documents\sample.txt" For Output As #1
will create a text file by the name of sample.txt in the My Document folder. The accompany file number is 1. If you wish to create and save the file in A drive, simply change the path, as follows"
Open "A:\sample.txt" For Output As #1
If you wish to create a HTML file , simple change the extension to .html
Open "c:\My Documents\sample.html" For Output As # 2
14.2.1 Sample Program : Creating a text file
Private Sub create_Click()
Dim intMsg As String
Dim StudentName As String
Open "c:\My Documents\sample.txt" For Output As #1
intMsg = MsgBox("File sample.txt opened")
StudentName = InputBox("Enter the student Name")
Print #1, StudentName
intMsg = MsgBox("Writing a" & StudentName & " to sample.txt ")
Close #1
intMsg = MsgBox("File sample.txt closed")
End Sub
* The above program will create a file sample.txt in the My Documents' folder and ready to receive input from users. Any data input by users will be saved in this text file.

14.3 Reading files
To read a file created in section 14.2, you can use the input # statemment. However, we can only read the file according to the format when it was written. You have to open the file according to its file number and the variable that hold the data. We also need to declare the variable using the DIM command.
14.3.1 Sample Program: Reading file
Private Sub Reading_Click()
Dim variable1 As String
Open "c:\My Documents\sample.txt" For Input As #1
Input #1, variable1
Text1.Text = variable1
Close #1
End Sub
* This program will open the sample.txt file and display its contents in the Text1 textbox.

2. thanks for the 2nd part. as this is what i am trying to learn. i try to give you greenies but it say i cant give you more. maybe cuz i gave you greenies yesterday. i dont really know how it all works on this board.

wortcraft

3. thanks but you cant give greenies until you have 50 positive antipoints

4. Hey Blow do you know where I could get somtihng to change the appearance of my VB forms? I'm new to VB and I just got done reading your tutorial. I liked the part about using files. I found that interesting. Well anyways it was a good read.

5. Last time you posted no.1 didn't you say that you hadn't written this tutorial? If so, why didn't you post that again this time blow? Just wondering, I may be wrong.

Yeah, you did write that. Just wondering why you didn't write that on this tutorial.
First of all, i wanted to say that i didnt write this tutorial. Srill, it helped me and im hoping it will help other people too.
Second, you can download VB 5.0 and other versions free at, http://msdn.microsoft.com/vbasic/downloads/VisualBasic5

6. very nice tut blow!

7. That tutorial was *cough*stolen*cough* from http://www.vbtutor.net/lesson7.html (where it is much more readable)....

8. stealing tutorials - is really really low..

anyways, i use vb all the time, in asp..so it didnt explain anything to me :_)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•