Lesson 6: Working with Variables
6.1 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.2 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)
|
194=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.
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.
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
Lesson 5: Managing Visual Basic Data
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, 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. VB divides data into different types so that it is easier to manage when we need to write the code involving those data.
5.1 Visual Basic Data Types
Visual Basic classifies the information mentioned above into two major data types, they are the numeric data types and the non-numeric data types.
5.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, 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 5.1
Table 5.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).
|
|
|
5.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 5.2
Table 5.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
|
5.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 VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double type data. Some of the suffixes are displayed in Table 5.3.
Table 5.3
Suffix
|
Data Type
|
&
|
Long
|
!
|
Single
|
#
|
Double
|
@
|
Currency
|
In addition, we need to enclose string literals within two quotations and date and time literals within two # sign. Strings can contain any characters, including numbers. The following are few examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
5.2 Managing Variables
Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the mail boxes. In term of VB, variables are areas allocated by the computer memory to hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic, you have to follow a set of rules.
5.2.1 Variable Names
The following are the rules when naming the variables in Visual Basic
- It must be less than 255 characters
- No spacing is allowed
- It must not begin with a number
- Period is not permitted
Examples of valid and invalid variable names are displayed in Table 5.4
Table 5.4
Valid Name
|
Invalid Name
|
My_Car
|
My.Car
|
ThisYear
|
1NewBoy
|
Long_Name_Can_beUSE
|
He&HisFather *& is not acceptable
|
5.2.2 Declaring Variables
In Visual Basic, one needs to declare the variables before using them by assigning names and data types. They are normally declared in the general section of the codes' windows using the Dim statement.
The format is as follows:
Dim Variable Name As Data Type
Example 5.1
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date
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,.............
If data type is not specified, VB will automatically declare the variable as a Variant.
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 5.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 5.2:
Dim yourName as String * 10
yourName can holds no more than 10 Characters.
5.3 Constants
Constants are different from variables in the sense that their values do not change during the running of the program.
5.3.1 Declaring a Constant
The format to declare a constant is
Const Constant Name As Data Type = Value
Example 5.3
Const Pi As Single=3.142
Const Temp As Single=37
Const Score As Single=100
Lesson 4 Writing the Codes
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 learning a few 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 etc. For each event, you need to write an event procedure so that an action or a series of actions can be performed.
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:
Example 4.1
Private Sub Command1_click
Label1.Visible=false
Label2.Visible=True
Text1.Text=”You are correct!”
End sub
Example 4.2
Private Sub Command1_click
Label1.Caption=” Welcome”
Image1.visible=true
End sub
Example 4.3
Private Sub Command1_click
Pictuire1.Show=true
Timer1.Enabled=True
Lable1.Caption=”Start Counting
End sub
In example 4.1, clicking on the command button will make label1 become invisible and label2 become visible; and the text” You are correct” will appear in TextBox1. In example 4.2, clicking on the command button will make the caption label1 change to “Welcome” and Image1 will become visible. In example 4.3 , clicking on the command button will make Picture1 show up, timer starts running and the caption of label1 change to “Start Counting”.
Syntaxes that do not involve setting of properties are also English-like, some of the commands are Print, If…Then….Else….End If, For…Next, Select Case…..End Select , End and Exit Sub. For example, Print “ Visual Basic” is to display the text Visual Basic on screen and End is to end the program. Other commands will be explained in details in the coming lessons.
Program codes that involve calculations is very easy to write, you need to write them almost liket what you do in mathematics. However, in order to write an event procedure that involves calculations, you need to know the basic arithmetic operators in VB as they are not exactly the same as the normal operators we use, except for + and - . For multiplication, we use *, for division we use /, for raising a number x to the power of n, we use x ^n and for square root, we use Sqr(x). More advanced mathematical functions such as Sin, Cos, Tan , Log and etc. There are also two important functions that are related to arithmetic operations, i.e. the functions Val and Str$ where Val is to convert text entered into a textbox to numerical value and Str$ is to display a numerical value in a textbox as a string (text). While the function Str$ is as important as VB can display a numeric values as string implicitly, failure to use Val will results in wrong calculation. Let’s examine example 4.4 and example 4.5.
Example 4.4
Private Sub Form_Activate()
Text3.text=text1.text+text2.text
End Sub
|
Example 4.5
Private Sub Form_Activate()
Text3.text=val(text1.text)+val(text2.text)
End Sub
|
When you run the program in example 4.4 and enter 12 in textbox1 and 3 in textbox2 will give you a result of 123, which is wrong. It is because VB treat the numbers as string and so it just joins up the two strings. On the other hand, running exampled 4.5 will give you the correct result, i.e., 15.
Lesson 3-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.
Figure 3.1 on the right is a typical properties window for a form. 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 that is used to receive 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 inputs 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 Figure 3.2

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 a very important control 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 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 programImagesgrape.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 programImagesgrape.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 to select or unselect 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 unmark the Check Box, and 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, you will be able to select different drives from your computer as shown in Figure 3.3
Figure 3.3 The Drive List Box

3.2.11 The Directory List Box
The Directory List Box is used to display the list of directories or folders in a selected drive. When you place this control into the form and run the program, you will be able to select different directories from a selected drive in your computer as shown in Figure 3.4
Figure 3.4 The Directory List Box

3.2.12 The File List Box
The File List Box is used to display the list of files in a selected directory or folder. When you place this control into the form and run the program, you will be able to a list of files in a selected directory as shown in Figure 3.5
You can coordinate the Drive List Box, the Directory List Box and the File List Box to search for the files you want. The procedure will be discussed in later lessons.
1.1 What is computer programming?
Before we begin, let us understand some basic concepts of programming. According to Webopedia, a computer program is an organized list of instructions that, when executed, causes the computer to behave in a predetermined manner. Without programs, computers are useless. Therefore, programming means designing or creating a set of instructions to ask the computer to carry out certain jobs which normally are very much faster than human beings can do. In order to do programming, we need to use certain computer language to communicate with the computer. There are many computer languages out there, some of the examples are Visual Basic, Fortran, Cobol, Java, C++, Turbo Pascal, Assembly language and etc. Among them, I pick Visual Basic because it is the easiest to learn as it uses a language very similar to human language. It involves using words such as If, Then, Else, Goto, Select and so on, so it is very fast for any beginner to pick the language.
1.1 What is Visual Basic ?
VISUAL BASIC is a high level programming language 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.
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 benefit the most.
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. 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.2 The Visual Basic 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:
Microsoft Visual Basic 6.0 Professional
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.
Figure 1.1 The Visual Basic Start-up Dialog Box
