Category Archives: Visual Basic

Arrays

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, we might have difficulty in declaring 100 different names, this is a waste of time and efforts. So,  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. , which will make declaring variables streamline and much systematic.

13.2 Dimension of an Array

An array can be one dimensional or multidimensional. One dimensional array is like a list of items or a table that consists of one row of items or one column of items. A twodimensional array will be a table of items that make up of rows and columns. While the format for a one dimensional array is ArrayName(x), the format for a two dimensional array is ArrayName(x,y) while a three dimensional array is ArrayName(x,y,z) . Normally it is sufficient to use one dimensional and two dimensional array ,you only need to use higher dimensional arrays if you need with engineering problems or even some accounting problems.Let me illustrates the the arrays with tables.

Table 13.1. One dimensional Array

Student Name Name(1) Name(2) Name(3) Name(4) Name(5) Name(6)

Table 13.2 Two Dimensional Array

Name(1,1) Name(1,2) Name(1,3) Name(1,4)
Name(2,1) Name(2,2) Name(2,3) Name(2,4)
Name(3,1) Name(3,2) Name(3,3) Name(3,4)

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 a one dimensional 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)

CusName(1) CusName(2) CusName(3) CusName(4) CusName(5) CusName(6) CusName(7) CusName(8) CusName(9) 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)

The general format to declare a two dimensional array is as follow:

Dim ArrayName(Sub1,Sub2) as dataType

Example 13.3

Dim StudentName(10,10) will declare a 10×10 table make up of 100 students’ Names, starting with StudentName(1,1)  and end with StudentName(10,10).

13.3 Sample Programs

(i) 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

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.

Creating VBA Functions For MS Excel

Creating  VBA  Functions For MS Excel

12.1 The Needs to Create VBA Functions in MS-Excel

You can create  your own functions to supplement the  built-in functions in Microsoft Excel spreadsheet, which are quite limited in some aspects. These user-defined functions are also called  Visual Basic for Applications functions, or simply VBA functions. They are 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 functions 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%

12.2 Using Microsoft Excel Visual Basic  Editor

To create VBA functions in MS Excel, you can  click on tools,

select macro and then click on Visual Basic Editor as shown in Figure 12.1

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 window, type in the titles Sales Volume and Commissions in any two cells. By referring 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  dragging  the bottom right corner of cell C4 to the required cells, a nice and neat table that shows the commissions will automatically appear (as shown in figure 12.3). It can also be updated anytime

Figure 12.3: MS Excel Windows- Sales Volume

Introduction to VB Functions- Part II

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

Introduction to VB Functions Part I-Built-in Functions

Introduction to VB Functions Part I-Built-in Functions

A function is similar to a normal procedure but the main purpose of the functios 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 format 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. You can also learn about mathematical functions, formatting functions and string manipulation functions by clicking the links at the end of this page.

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  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. In fact, VB6 will automatically shows up a list of names constant  where you can select one of them.

example: yourMsg=MsgBox( “Click OK to Proceed”, 1, “Startup Menu”)

and yourMsg=Msg(“Click OK to Proceed”. vbOkCancel,”Startup Menu”)

are the same.

yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Table 10.2 shows the values, the corresponding named constant and buttons.

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
An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text. The format is

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

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

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

Example 10.3

i.  The Interface

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.

Visual Basic – Looping

Looping

Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called  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

9.2 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 folowing example

9.3  For….Next Loop

The format is:

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next

Pease refer to example 9.3a,9.3b and 9.3 c

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. Let’s examine example 9.3 d.

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

Example 9.2

Dim sum, n As Integer

Private Sub Form_Activate()

List1.AddItem “n” & vbTab & “sum”

Do

n = n + 1

Sum = Sum + n

List1.AddItem n & vbTab & Sum

If n = 100 Then

Exit Do

End If

Loop

End Sub

Explanation

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 AddItem method to populate the ListBox. The statement List1.AddItem “n” & vbTab & “sum” will display the headings in the ListBox, where it uses the vbTab function to create a space between the headings n and sum.

Example 9.3 a

For  counter=1 to 10

display.Text=counter

Next

Example 9.3 b

For counter=1 to 1000 step 10

counter=counter+1

Next

Example 9.3 c

For counter=1000 to 5 step -5

counter=counter-10

Next

*Notice that increment can be negative

Example 9.3 d

Private Sub Form_Activate( )

For n=1 to 10

If n>6 then

Exit For

End If

Else

Print n

End If

End Sub

Select Case Control Structure

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….ElseIf control 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.

The format of the Select Case control structure is show below:

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.

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

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

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

Visual Basic – Conditional Operators

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.

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.1: Conditional Operators

Operator Meaning
= Equal to
> More than
< Less Than
>= More than and equal
<= Less than and equal
<> Not Equal to

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

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.3  Using  If…..Then…..Else  Statements  with Operators

To effectively control the VB program flow, we shall use If…Then…Else statement together with the conditional operators and logical operators.
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

VisualBasic Assigning Values to Variables

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

Operators in Visual Basic

In order 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.

Table 6.1: Arithmetic Operators

Operator Mathematical function Example
^ 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
+ or & String concatenation “Visual”&”Basic”=”Visual Basic”

Example 6.1

Dim firstName As String

Dim secondName As String

Dim yourName As String

Private Sub Command1_Click()

firstName = Text1.Text

secondName = Text2.Text

yourName = secondName + “  ” + firstName

Label1.Caption = yourName

End Sub

In this example, 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 above, three variables are declared as integer and two variables are declared as variant. Variant means the variable can hold any numeric data type. The program computes the total and average of the three numbers that are entered into three text boxes.

Writing the Visual Basic Code

In lesson 2, you have learned how to enter the program code and run the sample VB programs but without much understanding about the logics of VB programming. Now, let’s get down to learning some basic rules about writing the VB program code.

Each control or object in VB can usually run many kinds of events or procedures; these events are listed in the dropdown list in the code window  that is displayed when you double-click on an object and click on the procedures’ box(refer to Figure 2.3). Among the events are loading a form, clicking of a command button, pressing a key on the keyboard or dragging an object and more. For each event, you need to write an event procedure so that it can perform  an action or a series of actions

To start writing an event procedure, you need to double-click an object. For example, if you want to write an event procedure when a user clicks   a command button, you double-click on the command button and an event procedure will appear as shown in Figure 2.1. It takes the following format:

Private Sub Command1_Click

(Key in your program code here)

End Sub

You then need to key-in the procedure in the space between Private Sub Command1_Click…………. End Sub.  Sub actually stands for sub procedure that made up a part of all the procedures in a program. The program code is made up of a number of statements that set certain properties or trigger some actions. The syntax of Visual Basic’s program code is almost like the normal English language though not exactly the same, so it is very easy to learn.

The syntax to set the property of an object or to pass certain value to it is :

Object.Property
where Object and Property is separated by a period (or dot). For example, the statement Form1.Show means to show the form with the name Form1, Iabel1.Visible=true means label1 is set to be visible, Text1.text=”VB” is to assign the text VB to the text box with the name Text1, Text2.text=100 is to pass a value of 100 to the text box with the name text2, Timer1.Enabled=False is to disable the timer with the name Timer1 and so on. Let’s examine a few examples below:

Working With Controls

Working With Controls

3.1 The Control Properties

Before writing an event procedure for the control to response to a user’s input, you have to set certain properties for the control to determine its appearance and how it will work with the event procedure. You can set the properties of the controls in the properties window or at runtime.

You can rename the form caption to any name that you like best. In the properties window, the item appears at the top part is the object currently selected (in Figure 3.1, the object selected is Form1). At the bottom part, the items listed in the left column represent the names of various properties associated with the selected object while the items listed in the right column represent the states of the properties. Properties can be set by highlighting the items in the right column then change them by typing or selecting the options available.

For example, in order to change the caption, just highlight Form1 under the name Caption and change it to other names. You may also try to alter the appearance of the form by setting it to 3D or flat. Other things you can do are to change its foreground and background color, change the font type and font size, enable or disable minimize and maximize buttons and etc.

You can also change the properties at runtime to give special effects such as change of color, shape, animation effect and so on. For example the following code will change the form color to red every time the form is loaded. VB uses hexadecimal system to represent the color. You can check the color codes in the properties windows which are showed up under ForeColor and BackColor .

Private Sub Form_Load()
Form1.Show
Form1.BackColor = &H000000FF&
End Sub

Another example is to change the control Shape to a particular shape at runtime by writing the following code. This code will change the shape to a circle at runtime. Later you will learn how to change the shapes randomly by using the RND function.

Private Sub Form_Load()
Shape1.Shape = 3
End Sub

I would like to stress that knowing how and when to set the objects’ properties is very important as it can help you to write a good program or you may fail to write a good program. So, I advice you to spend a lot of time playing with the objects’ properties.

I am not going into the details on how to set the properties. However, I would like to stress a few important points about setting up the properties.

  • You should set the Caption Property of a control clearly so that a user knows what to do with that command. For example, in the calculator program, all the captions of the command buttons such as +, – , MC, MR are commonly found in an ordinary calculator, a user should have no problem in manipulating the buttons.
  • A lot of programmers like to use a meaningful name for the Name Property may be because it is easier for them to write and read the event procedure and easier to debug or modify the programs later. However, it is not a must to do that as long as you label your objects clearly and use comments in the program whenever you feel necessary. T
  • One more important property is whether the control is enabled or not.
  • Finally, you must also considering making the control visible or invisible at runtime, or when should it become visible or invisible.

3.2 Handling some of the common controls

3.2.1 The Text Box

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. String in 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. The output is shown in Figure 3.2

Private Sub Command1_Click()

‘To add the values in text box 1 and text box 2

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

‘To display the answer on label 1

Label1.Caption = Sum

End Sub

3.2.2 The Label

The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label.Caption, it can display text and numeric data . You can change its caption in the properties window and also at runtime.  Please refer to Example 3.1 and Figure 3.1 for the usage of label.

3.2.3 The Command Button

The command button is one of the most important controls as it is used to execute commands. It displays an illusion that the button is pressed when the user click on it. The most common event associated with the command button is the Click event, and the syntax for the procedure is

Private Sub Command1_Click ()

Statements

End Sub

3.2.4 The Picture Box

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:\VB program\Images\grape.gif”)

You will learn more about the picture box in future lessons. The image in the picture box is not resizable.

3.2.5 The Image Box

The Image Box is another control that handles images and pictures. It functions almost identically to the picture box. 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 Picture Box. 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:\VB program\Images\grape.gif”)

3.2.6 The List Box

The function of the List Box is to present a list of items where the user can click and select the items from the list. In order to add items to the list, we can use the AddItem method. For example, if you wish to add a number of items to list box 1, you can key in the following statements

Example 3.2

Private Sub Form_Load ( )

List1.AddItem “Lesson1”

List1.AddItem “Lesson2”

List1.AddItem “Lesson3”

List1.AddItem “Lesson4”

End Sub

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

3.2.7 The Combo Box

The function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method. For example, if you wish to add a number of items to Combo box 1, you can key in the following statements

Example 3.3

Private Sub Form_Load ( )

Combo1.AddItem “Item1”

Combo1.AddItem “Item2”

Combo1.AddItem “Item3”

Combo1.AddItem “Item4”

End Sub

3.2.8 The Check Box

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 will change the background color of the form to red when the check box is unchecked and it will change to blue when the check box is checked.  You will learn about the conditional statement If….Then….Elesif in later lesson. VbRed and vbBlue are color constants and BackColor is the background color property of the form.

3.2.9 The Option Box

The Option Box control also lets the user selects one of the choices. However, two or more Option Boxes must work together because as one of the Option Boxes is selected, the other Option Boxes 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”. In the following example, the shape control is placed in the form together with six Option Boxes. When the user clicks on different option boxes, different shapes will appear. The 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 rounded rectangle and a rounded square respectively.

Example 3.4

Private Sub Option1_Click ( )

Shape1.Shape = 0

End Sub

Private Sub Option2_Click()

Shape1.Shape = 1

End Sub

Private Sub Option3_Click()

Shape1.Shape = 2

End Sub

Private Sub Option4_Click()

Shape1.Shape = 3

End Sub

Private Sub Option5_Click()

Shape1.Shape = 4

End Sub

Private Sub Option6_Click()

Shape1.Shape = 5

End Sub

3.2.10 The Drive List Box

The Drive ListBox is used to display a list of drives available in your computer. When you place this control into the form and run the program

Creating Your First Application

In this section, we are not going into the technical aspects of VB programming, you just try out the examples below:

Example 2.1.1 is a simple program. First of all, you have to launch Microsoft Visual Basic. Normally, a default form Form1 will be available for you to start your new project. Now, double click on form1, the source code window for form1. The top of the source code window consists of a list of objects and their associated events or procedures.

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, command button with the name Command1, a Label with the name Label1 and a PictureBox with the name Picture1. Similarly, when you click on the procedure box, a list of procedures associated with the object will be displayed as shown in figure 2.3. Some of the procedures associated with the object Form are Activate, Click, DblClick (which means Double-Click) , DragDrop, keyPress and etc. Each object has its own set of procedures. You can always select an object and write codes for any of its procedure in order to perform certain tasks.

You do not have to worry about the beginning and the end statements (i.e. Private Sub Form_Load…….End Sub.); Just key in the lines in between the above two statements exactly as are shown here. When you press F5 to run the program, you will be surprise that nothing shown up .In order to display the output of the program, you have to add the Form1.show statement like in Example 2.1.1  or you can just use Form_Activate ( )  event procedure as shown in example 2.1.2. The command Print does not mean printing using a printer but it means displaying the output on the computer screen. Now, press F5 or click on the run button to run the program and you will get the output as shown in figure 2.4.

You can also perform simple arithmetic calculations as shown in example 2.1.2. VB uses * to denote the multiplication operator and / to denote the division operator. The output is shown in figure 2.3, where the results are arranged vertically.

What is Visual Basic ?

What is  Visual Basic ?

VISUAL BASIC is a high level programming language which was evolved from the earlier DOS version called BASIC. BASIC means Beginners’ All-purpose Symbolic Instruction Code. It is a very  easy programming language to learn. The codes look a lot  like English Language. Different software companies produced different version of BASIC, such as Microsoft QBASIC, QUICKBASIC, GWBASIC ,IBM BASICA and so on. However, it seems people only use Microsoft Visual Basic today, as it is a well developed programming language and supporting resources are available everywhere.

VISUAL BASIC is a VISUAL and  events driven Programming Language. These are the main divergence from the old BASIC. In BASIC, programming is done in a text-only environment and the program is executed sequentially. In VISUAL BASIC, programming is done in a graphical environment. In the old BASIC, you have to write program codes for each graphical object you wish to display it on screen, including its position and its color. However, In Visual Basic , you just need to drag and drop any graphical object anywhere on the form, and you can change its color any time using the properties windows.

On the other hand, because  users may click on a certain object randomly, so each object has to be programmed independently to be able to response to those actions (events). Therefore, a VISUAL BASIC Program is made up of many subprograms, each has its own program codes, and each can be executed independently and at the same time each can be linked together in one way or another.

1.3 What programs can you create with Visual Basic?

With Visual Basic, you can program practically everything depending on your objective. For example, you can program educational software to teach science , mathematics, language, history , geography and so on. You can also program financial and accounting software to make you a more efficient accountant or financial controller. For those of you who like games, you can program that as well. Indeed, there is no limit to what you can program! There are many such program in this tutorial, so you must spend more time on the tutorial in order to learn how to create those programs. If you wish to see some sample programs, take a look at the  link below:

1.3 The Visual Basic 6 Integrated Development Environment

Before you can program in Visual Basic, you need to install VB6 in your computer. If you do not own  VB6 yet , you can purchase it from Amazon.com by clicking the link below:

Basically any present computer systems should be able to run the program, be it a  Intel Pentium II, Intel Pentium III, Intel Pentium IV or even AMD machines, VB6 can run without any problem. It may not be true for VB2005, older machines might not be able to run VB2005 as it take up much more resources, therefore I still prefer using VB6 as it is light and easy to program. It is still very useful and powerful, and I am happy to know that Microsoft Windows Vista can support VB6.

On start up, Visual Basic 6.0  will display the following dialog box as shown in figure 1.1. You can choose to either start a new project, open an existing project or select a list of recently opened programs. A project is a collection of files that make up your application. There are various types of applications we could create, however, we shall concentrate on creating Standard EXE programs (EXE means executable program). Now, click on the Standard EXE icon to go into the actual VB programming environment.