In this chapter, we will understand various elements used in programming in Visual Basic. These are the building blocks. We will only understand what-is-what about various elements. The actual application of these elements will be clear to you when you read the rest of the material.
Data Types
Every variable has a data type. If you do not explicitly specify the data type then VB will use Variant data type, which can store any type of value. However, as Variant data type is not efficient, it is always better you specify what type of value the variable is supposed to contain.
Table 4.1 lists the available data types in VB.
Data Type Size in Bytes Range
Byte 1 0 to 255
Boolean 2 True or False.
Integer 2 -32768 to 32677
Long 4 -2147483648 to 2147483647
Single 4 -3.4e38 to –1.4e-45 for negative values; 1.4e-45 to 3.4e38 for positive values.
Double 8 -1.8e308 to –4.9e-324 for negative values; 4.9e-324 to 1.8e308 for positive values.
Currency 8 -9223372036854775808 to 9223372036854775807.
Date 8 1-1-100 to 31-12-9999.
Object 4 Any object reference
String(Variable length) 10 + String length Up to 2 billion characters.
String(fixed length) String length Up to 2 billion characters.
Variant ( numbers) 16 Up to range of Double.
Variant (characters) 22 + length of string Up to 2 Billion characters.
Table 4.1: Data Types available in Visual Basic 6.0.
Selecting the right data type
Though VB doesn’t require you to specify the data type at the time of declaring variables, it is a good idea to do so. Because it improves efficiency as it reduces time and space required to handle the data. For example, if you know that the value will be in the range 100 to 200 then it is better to choose Byte data type instead of going for any other data types.
The following are a few examples to illustrate how to use data types.
Example 1
dim st as string
st is a variable length string. It means the size of st changes according to the data stored in it.
Example 2
dim st as string * 10
Here variable st can contain only 10 characters and it always occupies 10 bytes whether it has any value or not.
Example 3
Dim x
Here variable x is of Variant type. It can contain any type of data.
Declaring Variables
Declaring variable is letting VB know about how we intend to use the variable. For example, if you declare a variable as String, then it means you want to store characters into it. Dim statement is used to declare variables.
Dim variable [as datatype]
Variable is the name of the variable and datatype is the type of variable. If datatype is not given then variable is taken to be of variant type.
Examples
Dim n as integer
Dim amount as long, discount as integer
Dim amount, totamount as long
In the last example, only totamount is taken to be long and amount is treated as variant type.
Note: when you are declaring multiple variable with a single dim statement, you have to specify the data type for each variable otherwise the data type applies to only to the last variable and the rest of the variables are taken to be of variant type.
Option Explicit Statement
By default Visual Basic doesn’t require variable to be declared before it is used. When VB encounters a variable for the first time in the code, it will implicitly declare the variable. But implicit declaration could cause severe logical bugs. So it is always better you declare variables before you use them.
Option Explicit statement, when given in General /Declarations section of a module makes variable declaration mandatory. So you must declare every variable that you use otherwise it will result in a syntax error.
You can also automatically insert Option Explicit statement into new module by following the below procedure.
1. Select Tools->Options.
2. When Options window is displayed, select Editor tab.
3. Check Require Variable Declaration option.
4. Click on Ok button.
Note: It is strongly recommended that you use Option Explicit statement in each module. And also note when you choose Require Variable Declaration option, it will effect only modules that are created after the option is turned on. So enter the statement manually for old modules.
Naming Rules
The following are the rules to be followed while creating variable names.
• Must start with an alphabet (A-Z or a-z).
• Can contain A-Z, a-z, 0-9 and special characters %,&,!, #,@, and $.
Operators
An operator is a symbol or a word that performs an operation. Depending upon the type of operation an operator performs, operators are classified as follows:
Category What it does?
Arithmetic Operators Used to perform arithmetic operations such as addition, subtraction etc.
Relational Operators Used in forming conditions used to compare values.
Logical Operators Used to combine conditions or to negate condition
Assignment Operator Used to assign a value to a variable
Concatenation Operator Used to concatenate ( join) two strings
Table 4.2: Operators categories.
Now, let us discuss operators in each category in detail.
Arithmetic Operators
The following are various arithmetic operators.
Operator What it does?
+ Addition
- Subtraction. This operator can also be used as unary operator. In this case, it negates the sign of the number. For example, if variable A contains –10 then –A will result in 10(positive 10).
/ Division
* Multiplication
Mod Modulus. Returns the remainder of the division.
\ Integer Division. Returns only integer portion of the quotient.
Table 4.3: Arithmetic Operators.
Relational Operators
The following are the operators used to form conditions. The result of any expression using a relational operator will be either True or False.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
= Equal to
<> Not equal to
Table 4.4: Relational Operators.
Note: In Visual Basic, True means –1 and False means 0.
Logical Operators
These operators are used to combine two relational operators. The following are the available logical operators.
Operator Meaning
AND Both the conditions must be true for the entire condition to be true.
OR If either condition is true then the entire condition is true.
NOT Reverses the result of the condition.
XOR The entire condition is true only when either of the conditions is true. If both the conditions are true or if both the conditions are false then entire condition is false.
EQV The entire condition is true only when both the conditions are either true or false.
IMP The entire condition is true except when the first condition is true and the second condition is false.
Table 4.5: Logical Operators.
Note: Most commonly used logical operators are AND, OR and NOT.
Examples:
If a > b and a > c then
Print “A is the biggest”
End if
If a > b or a > c then
Print “ A is greater than either b or c or both “
End if
If not workdone then
Print “Work is still in progress”
End if
In third example, workdone is assumed to be a Boolean variable, which either contains true or false. If workdone contains true then the result of the condition will be false and vice versa. Be familiar with such expressions, as they are very common in programming.
If Statement
It is very common to test a condition and take either of two possible actions based on the result of the test. If statement is used to test condition and act according to the result of the condition.
If condition Then
Statements
Else
Statements
End if
If condition is satisfied then statements given after Then will be executed otherwise statements given after Else are executed.
As you can understand from the syntax, Else is optional. If you do not give else then no statements will be executed when condition is not true.
Single Line vs. Multiple Line
You can give entire if statement in a single line. The following is an example of single line if statements.
If amount > 10000 then discount = amount * 0.10
Note that when you use single line if statement End if is NOT required.
If .. then .. elseif… else statement
When you have to test for multiple conditions and take action based on the result of conditions then multiple if statement is best suited.
If condition then
Statements
Elseif condition then
Statements
Else
Statements
End if
In the if..elseif ladder, if condition is ever true the statements after that conditions will be executed and control comes out of entire if statement.
The following is an example where we determine the percentage of discount based on the value of amount variable.
If amount > 20000 then
Dis = 10
Elseif amount > 15000 then
Dis = 8
Elseif amount > 10000 then
Dis = 5
Else
Dis = 0 ‘ no discount
End if
Select Case Statement
This statement is used when a single variable value is to be compared with different set of values.
Select Case expression
Case value-1
Statements
[Case value-2
Statements]…
[Case else
Statements]
End Select
Expression is evaluated in the beginning of the statement and the result is compared with the given values from top. If at any point the value is equivalent to the result of condition then the corresponding statements are executed and control comes out of Select Case statement.
Case Else is executed when none of the given values match the result of the expression.
The value may be either a single value or a range of values or a collection of values. It may also be a combination of all. The following example will explain the point.
Select Case code
Case 1
Dis = 10
Case 2 to 4
Dis = 12
Case 5, 7
Dis = 14
Case 6, 7 to 10
Dis = 11
Case else
Dis = 0
End select
In the above Select Case statement, first the value of variable code is compared with 1 (first case). If they are same then the corresponding action takes place (setting dis variable to value 10). Otherwise, code is compared with second case, in which case, condition will be true if code is in the range 2 to 4. In third case code is compared with 5 and 7. In fourth case, code is compared with value 6 and also with the range from 7 to 10.
In none of the given conditions are true, then statements given after Case Else are executed, where dis is set to 0. The following are the possible values that you can give after each case:
• A single constant. Ex: 10
• A single range. Ex: 1 to 5
• A collection of values each separated by comma. Ex: 1,4,6
• Any combination of the above three. Ex: 5,7, 10 to 15
Looping Structures
A looping structure allows a set of statements to be repeatedly executed. Visual Basic provides as many as five looping structures. The choice of the looping structure mainly depends on the requirement. If for example, you have to execute a set of statements for 10 times then For loop is ideal, if you have to execute statement until a condition is satisfied then Loop Until is to be used. In the following sessions I will discuss more about all the available looping structures in Visual Basic 6.0.
• DO WHILE … LOOP
• DO UNTIL … LOOP
• DO … LOOP WHILE
• DO … LOOP UNTIL
• FOR ... NEXT
The following sections discuss about each of the available looping structrues.
Do While … Loop
Executes given set of statements as long as the condition is true. Once condition is false then loop is terminated and control is transferred to the immediate next statement after the loop.
Do While condition
Statements
Loop
The following example will display numbers from 1 to 10.
I = 1
Do while I <= 10
Print I
I = I + 1
Loop
Do Until… Loop
Executes given set of statements until the condition is true. That means the statements are executed as long as condition is false. Once condition is true, loop is terminated and control is transferred to the immediate next statement after the loop.
Do Until condition
Statements
Loop
The following example will display numbers from 1 to 10.
I = 1
Do until I > 10
Print I
I = I + 1
Loop
Do … Loop While
Executes given set of statements as long as the condition is true. But in this, condition is checked after the loop is executed. As a result, the statements are executed at least for once. Except the difference between the minimum number of times the loop is executed, where for Do .. While it is 0 and for Do..Loop While it is 1, both these loops work identically.
do
Statements
loop while condition
The following example displays numbers from 1 to 10.
I = 1
Do
Print I
I = I + 1
Loop while I <= 10
Do… Loop Until
This is same as Do … Loop While except that it executes statements until the condition is true. In other words, as long as the condition is false.
do
Statements
loop until condition
The following example displays numbers from 1 to 10.
I = 1
Do
Print I
I = I + 1
Loop until I > 10
For ... Next Loop
This loop is used where the number of repetitions is known at the time of writing the program. For example, if you want to print numbers 1 to 10 then you know that the loop is to be repeated for 10 times. This loop is ideal in cases like this. Another advantage of this loop is; counter is automatically incremented or decremented by the loop. It is also possible to control the increment using Step option.
For counter = start to end [step value]
Statements
Next [counter]
Counter Is an integer variable whose value is initially set to start and then incremented after each iteration of the loop. When its value exceeds end value then loop is terminated.
Start Specifies the value that is to be assigned to counter at the beginning of the loop. It may be any valid Visual Basic expression.
End Specifies the ending value. Once counter exceeds this value the loop is terminated. This will be more than start for normal loop and less than start in reverse loop.
Step This entry is optional. If not given, it defaults to 1. This specifies the value by which counter is to be incremented at the end of each repetition. This should be negative, if start value is more than end value (reverse loop).
Statements The statements to be executed.
Next Identifies the ending of the statements to be executed. Upon reaching this, For increments the counter and checks whether counter exceeds end value. If not it enters into next iteration otherwise loop will be terminated. Though giving counter after Next is optional, it may make especially nested loops clear.
In the following example for loop is used to display only even numbers in the range 50 to 100.
For c = 50 to 100 step 2
Print c
Next c
Initially C is set to 50. After each iteration C is incremented by 2. When C exceeds 100 the loop is terminated, otherwise the value of C is printed.
The following is an example to print numbers from 10 to 1.
For c = 10 to 1 step -1
Print c
Next c
Here, as step value is –1 after each iteration counter (C) is decremented by 1. If C goes below 1 then loop is terminated.
Exit Do Statement
This statement is used to terminate DO loops from within the loop. Normally a loop is terminated or continued based on the result of the condition given in loop. But in some occasions, it is required to check for a condition within the loop and terminate loop depending upon the result of the condition.
In the following example, the loop is repeated until user entered 10 numbers or until a negative number is entered.
Cnt = 1
Do while cnt <= 10
‘ take value and place it in variable N
…
if N < 0 then
exit do
end if
…
loop
Exit For Statement
This is conceptually same as Exit do, but this is used to terminate a FOR loop.
GoTo Statement
This is used to transfer control to the specified label. Goto is NOT recommended, as it is difficult to follow the logic of the program if control is transferred from one place to another using GoTo. In other words GoTo spoils the structure of the program. However in some cases GoTo might come out as better choice than the remaining.
GoTo label
Here is an example, when control is transferred to the beginning of the procedure if user responds by entering you.
' It is an imaginary procedure to demonstrate how to use GOTO
Sub Procedure ()
Retry:
Statement
If resp = “YES” Then
GoTo retry
End if
End sub
Note: You can transfer control within a procedure.
We will see GoTo in action in runtime error handling
Language Elements
In this chapter, we will understand various elements used in programming in Visual Basic. These are the building blocks. We will only understand what-is-what about various elements. The actual application of these elements will be clear to you when you read the rest of the material.
Data Types
Every variable has a data type. If you do not explicitly specify the data type then VB will use Variant data type, which can store any type of value. However, as Variant data type is not efficient, it is always better you specify what type of value the variable is supposed to contain.
Table 4.1 lists the available data types in VB.
Data Type Size in Bytes Range
Byte 1 0 to 255
Boolean 2 True or False.
Integer 2 -32768 to 32677
Long 4 -2147483648 to 2147483647
Single 4 -3.4e38 to –1.4e-45 for negative values; 1.4e-45 to 3.4e38 for positive values.
Double 8 -1.8e308 to –4.9e-324 for negative values; 4.9e-324 to 1.8e308 for positive values.
Currency 8 -9223372036854775808 to 9223372036854775807.
Date 8 1-1-100 to 31-12-9999.
Object 4 Any object reference
String(Variable length) 10 + String length Up to 2 billion characters.
String(fixed length) String length Up to 2 billion characters.
Variant ( numbers) 16 Up to range of Double.
Variant (characters) 22 + length of string Up to 2 Billion characters.
Table 4.1: Data Types available in Visual Basic 6.0.
Selecting the right data type
Though VB doesn’t require you to specify the data type at the time of declaring variables, it is a good idea to do so. Because it improves efficiency as it reduces time and space required to handle the data. For example, if you know that the value will be in the range 100 to 200 then it is better to choose Byte data type instead of going for any other data types.
The following are a few examples to illustrate how to use data types.
Example 1
dim st as string
st is a variable length string. It means the size of st changes according to the data stored in it.
Example 2
dim st as string * 10
Here variable st can contain only 10 characters and it always occupies 10 bytes whether it has any value or not.
Example 3
Dim x
Here variable x is of Variant type. It can contain any type of data.
Declaring Variables
Declaring variable is letting VB know about how we intend to use the variable. For example, if you declare a variable as String, then it means you want to store characters into it. Dim statement is used to declare variables.
Dim variable [as datatype]
Variable is the name of the variable and datatype is the type of variable. If datatype is not given then variable is taken to be of variant type.
Examples
Dim n as integer
Dim amount as long, discount as integer
Dim amount, totamount as long
In the last example, only totamount is taken to be long and amount is treated as variant type.
Note: when you are declaring multiple variable with a single dim statement, you have to specify the data type for each variable otherwise the data type applies to only to the last variable and the rest of the variables are taken to be of variant type.
Option Explicit Statement
By default Visual Basic doesn’t require variable to be declared before it is used. When VB encounters a variable for the first time in the code, it will implicitly declare the variable. But implicit declaration could cause severe logical bugs. So it is always better you declare variables before you use them.
Option Explicit statement, when given in General /Declarations section of a module makes variable declaration mandatory. So you must declare every variable that you use otherwise it will result in a syntax error.
You can also automatically insert Option Explicit statement into new module by following the below procedure.
1. Select Tools->Options.
2. When Options window is displayed, select Editor tab.
3. Check Require Variable Declaration option.
4. Click on Ok button.
Note: It is strongly recommended that you use Option Explicit statement in each module. And also note when you choose Require Variable Declaration option, it will effect only modules that are created after the option is turned on. So enter the statement manually for old modules.
Naming Rules
The following are the rules to be followed while creating variable names.
• Must start with an alphabet (A-Z or a-z).
• Can contain A-Z, a-z, 0-9 and special characters %,&,!, #,@, and $.
Operators
An operator is a symbol or a word that performs an operation. Depending upon the type of operation an operator performs, operators are classified as follows:
Category What it does?
Arithmetic Operators Used to perform arithmetic operations such as addition, subtraction etc.
Relational Operators Used in forming conditions used to compare values.
Logical Operators Used to combine conditions or to negate condition
Assignment Operator Used to assign a value to a variable
Concatenation Operator Used to concatenate ( join) two strings
Table 4.2: Operators categories.
Now, let us discuss operators in each category in detail.
Arithmetic Operators
The following are various arithmetic operators.
Operator What it does?
+ Addition
- Subtraction. This operator can also be used as unary operator. In this case, it negates the sign of the number. For example, if variable A contains –10 then –A will result in 10(positive 10).
/ Division
* Multiplication
Mod Modulus. Returns the remainder of the division.
\ Integer Division. Returns only integer portion of the quotient.
Table 4.3: Arithmetic Operators.
Relational Operators
The following are the operators used to form conditions. The result of any expression using a relational operator will be either True or False.
Operator Meaning
< Less than > Greater than
<= Less than or equal to >= Greater than or equal to
= Equal to
<> Not equal to
Table 4.4: Relational Operators.
Note: In Visual Basic, True means –1 and False means 0.
Logical Operators
These operators are used to combine two relational operators. The following are the available logical operators.
Operator Meaning
AND Both the conditions must be true for the entire condition to be true.
OR If either condition is true then the entire condition is true.
NOT Reverses the result of the condition.
XOR The entire condition is true only when either of the conditions is true. If both the conditions are true or if both the conditions are false then entire condition is false.
EQV The entire condition is true only when both the conditions are either true or false.
IMP The entire condition is true except when the first condition is true and the second condition is false.
Table 4.5: Logical Operators.
Note: Most commonly used logical operators are AND, OR and NOT.
Examples:
If a > b and a > c then
Print “A is the biggest”
End if
If a > b or a > c then
Print “ A is greater than either b or c or both “
End if
If not workdone then
Print “Work is still in progress”
End if
In third example, workdone is assumed to be a Boolean variable, which either contains true or false. If workdone contains true then the result of the condition will be false and vice versa. Be familiar with such expressions, as they are very common in programming.
If Statement
It is very common to test a condition and take either of two possible actions based on the result of the test. If statement is used to test condition and act according to the result of the condition.
If condition Then
Statements
Else
Statements
End if
If condition is satisfied then statements given after Then will be executed otherwise statements given after Else are executed.
As you can understand from the syntax, Else is optional. If you do not give else then no statements will be executed when condition is not true.
Single Line vs. Multiple Line
You can give entire if statement in a single line. The following is an example of single line if statements.
If amount > 10000 then discount = amount * 0.10
Note that when you use single line if statement End if is NOT required.
If .. then .. elseif… else statement
When you have to test for multiple conditions and take action based on the result of conditions then multiple if statement is best suited.
If condition then
Statements
Elseif condition then
Statements
Else
Statements
End if
In the if..elseif ladder, if condition is ever true the statements after that conditions will be executed and control comes out of entire if statement.
The following is an example where we determine the percentage of discount based on the value of amount variable.
If amount > 20000 then
Dis = 10
Elseif amount > 15000 then
Dis = 8
Elseif amount > 10000 then
Dis = 5
Else
Dis = 0 ‘ no discount
End if
Select Case Statement
This statement is used when a single variable value is to be compared with different set of values.
Select Case expression
Case value-1
Statements
[Case value-2
Statements]…
[Case else
Statements]
End Select
Expression is evaluated in the beginning of the statement and the result is compared with the given values from top. If at any point the value is equivalent to the result of condition then the corresponding statements are executed and control comes out of Select Case statement.
Case Else is executed when none of the given values match the result of the expression.
The value may be either a single value or a range of values or a collection of values. It may also be a combination of all. The following example will explain the point.
Select Case code
Case 1
Dis = 10
Case 2 to 4
Dis = 12
Case 5, 7
Dis = 14
Case 6, 7 to 10
Dis = 11
Case else
Dis = 0
End select
In the above Select Case statement, first the value of variable code is compared with 1 (first case). If they are same then the corresponding action takes place (setting dis variable to value 10). Otherwise, code is compared with second case, in which case, condition will be true if code is in the range 2 to 4. In third case code is compared with 5 and 7. In fourth case, code is compared with value 6 and also with the range from 7 to 10.
In none of the given conditions are true, then statements given after Case Else are executed, where dis is set to 0. The following are the possible values that you can give after each case:
• A single constant. Ex: 10
• A single range. Ex: 1 to 5
• A collection of values each separated by comma. Ex: 1,4,6
• Any combination of the above three. Ex: 5,7, 10 to 15
Looping Structures
A looping structure allows a set of statements to be repeatedly executed. Visual Basic provides as many as five looping structures. The choice of the looping structure mainly depends on the requirement. If for example, you have to execute a set of statements for 10 times then For loop is ideal, if you have to execute statement until a condition is satisfied then Loop Until is to be used. In the following sessions I will discuss more about all the available looping structures in Visual Basic 6.0.
• DO WHILE … LOOP
• DO UNTIL … LOOP
• DO … LOOP WHILE
• DO … LOOP UNTIL
• FOR ... NEXT
The following sections discuss about each of the available looping structrues.
Do While … Loop
Executes given set of statements as long as the condition is true. Once condition is false then loop is terminated and control is transferred to the immediate next statement after the loop.
Do While condition
Statements
Loop
The following example will display numbers from 1 to 10.
I = 1
Do while I <= 10 Print I I = I + 1 Loop Do Until… Loop Executes given set of statements until the condition is true. That means the statements are executed as long as condition is false. Once condition is true, loop is terminated and control is transferred to the immediate next statement after the loop. Do Until condition Statements Loop The following example will display numbers from 1 to 10. I = 1 Do until I > 10
Print I
I = I + 1
Loop
Do … Loop While
Executes given set of statements as long as the condition is true. But in this, condition is checked after the loop is executed. As a result, the statements are executed at least for once. Except the difference between the minimum number of times the loop is executed, where for Do .. While it is 0 and for Do..Loop While it is 1, both these loops work identically.
do
Statements
loop while condition
The following example displays numbers from 1 to 10.
I = 1
Do
Print I
I = I + 1
Loop while I <= 10 Do… Loop Until This is same as Do … Loop While except that it executes statements until the condition is true. In other words, as long as the condition is false. do Statements loop until condition The following example displays numbers from 1 to 10. I = 1 Do Print I I = I + 1 Loop until I > 10
For ... Next Loop
This loop is used where the number of repetitions is known at the time of writing the program. For example, if you want to print numbers 1 to 10 then you know that the loop is to be repeated for 10 times. This loop is ideal in cases like this. Another advantage of this loop is; counter is automatically incremented or decremented by the loop. It is also possible to control the increment using Step option.
For counter = start to end [step value]
Statements
Next [counter]
Counter Is an integer variable whose value is initially set to start and then incremented after each iteration of the loop. When its value exceeds end value then loop is terminated.
Start Specifies the value that is to be assigned to counter at the beginning of the loop. It may be any valid Visual Basic expression.
End Specifies the ending value. Once counter exceeds this value the loop is terminated. This will be more than start for normal loop and less than start in reverse loop.
Step This entry is optional. If not given, it defaults to 1. This specifies the value by which counter is to be incremented at the end of each repetition. This should be negative, if start value is more than end value (reverse loop).
Statements The statements to be executed.
Next Identifies the ending of the statements to be executed. Upon reaching this, For increments the counter and checks whether counter exceeds end value. If not it enters into next iteration otherwise loop will be terminated. Though giving counter after Next is optional, it may make especially nested loops clear.
In the following example for loop is used to display only even numbers in the range 50 to 100.
For c = 50 to 100 step 2
Print c
Next c
Initially C is set to 50. After each iteration C is incremented by 2. When C exceeds 100 the loop is terminated, otherwise the value of C is printed.
The following is an example to print numbers from 10 to 1.
For c = 10 to 1 step -1
Print c
Next c
Here, as step value is –1 after each iteration counter (C) is decremented by 1. If C goes below 1 then loop is terminated.
Exit Do Statement
This statement is used to terminate DO loops from within the loop. Normally a loop is terminated or continued based on the result of the condition given in loop. But in some occasions, it is required to check for a condition within the loop and terminate loop depending upon the result of the condition.
In the following example, the loop is repeated until user entered 10 numbers or until a negative number is entered.
Cnt = 1
Do while cnt <= 10
‘ take value and place it in variable N
…
if N < 0 then
exit do
end if
…
loop
Exit For Statement
This is conceptually same as Exit do, but this is used to terminate a FOR loop.
GoTo Statement
This is used to transfer control to the specified label. Goto is NOT recommended, as it is difficult to follow the logic of the program if control is transferred from one place to another using GoTo. In other words GoTo spoils the structure of the program. However in some cases GoTo might come out as better choice than the remaining.
GoTo label
Here is an example, when control is transferred to the beginning of the procedure if user responds by entering you.
' It is an imaginary procedure to demonstrate how to use GOTO
Sub Procedure ()
Retry:
Statement
If resp = “YES” Then
GoTo retry
End if
End sub
Note: You can transfer control within a procedure.
We will see GoTo in action in runtime error handling
Data Types
Every variable has a data type. If you do not explicitly specify the data type then VB will use Variant data type, which can store any type of value. However, as Variant data type is not efficient, it is always better you specify what type of value the variable is supposed to contain.
Table 4.1 lists the available data types in VB.
Data Type Size in Bytes Range
Byte 1 0 to 255
Boolean 2 True or False.
Integer 2 -32768 to 32677
Long 4 -2147483648 to 2147483647
Single 4 -3.4e38 to –1.4e-45 for negative values; 1.4e-45 to 3.4e38 for positive values.
Double 8 -1.8e308 to –4.9e-324 for negative values; 4.9e-324 to 1.8e308 for positive values.
Currency 8 -9223372036854775808 to 9223372036854775807.
Date 8 1-1-100 to 31-12-9999.
Object 4 Any object reference
String(Variable length) 10 + String length Up to 2 billion characters.
String(fixed length) String length Up to 2 billion characters.
Variant ( numbers) 16 Up to range of Double.
Variant (characters) 22 + length of string Up to 2 Billion characters.
Table 4.1: Data Types available in Visual Basic 6.0.
Selecting the right data type
Though VB doesn’t require you to specify the data type at the time of declaring variables, it is a good idea to do so. Because it improves efficiency as it reduces time and space required to handle the data. For example, if you know that the value will be in the range 100 to 200 then it is better to choose Byte data type instead of going for any other data types.
The following are a few examples to illustrate how to use data types.
Example 1
dim st as string
st is a variable length string. It means the size of st changes according to the data stored in it.
Example 2
dim st as string * 10
Here variable st can contain only 10 characters and it always occupies 10 bytes whether it has any value or not.
Example 3
Dim x
Here variable x is of Variant type. It can contain any type of data.
Declaring Variables
Declaring variable is letting VB know about how we intend to use the variable. For example, if you declare a variable as String, then it means you want to store characters into it. Dim statement is used to declare variables.
Dim variable [as datatype]
Variable is the name of the variable and datatype is the type of variable. If datatype is not given then variable is taken to be of variant type.
Examples
Dim n as integer
Dim amount as long, discount as integer
Dim amount, totamount as long
In the last example, only totamount is taken to be long and amount is treated as variant type.
Note: when you are declaring multiple variable with a single dim statement, you have to specify the data type for each variable otherwise the data type applies to only to the last variable and the rest of the variables are taken to be of variant type.
Option Explicit Statement
By default Visual Basic doesn’t require variable to be declared before it is used. When VB encounters a variable for the first time in the code, it will implicitly declare the variable. But implicit declaration could cause severe logical bugs. So it is always better you declare variables before you use them.
Option Explicit statement, when given in General /Declarations section of a module makes variable declaration mandatory. So you must declare every variable that you use otherwise it will result in a syntax error.
You can also automatically insert Option Explicit statement into new module by following the below procedure.
1. Select Tools->Options.
2. When Options window is displayed, select Editor tab.
3. Check Require Variable Declaration option.
4. Click on Ok button.
Note: It is strongly recommended that you use Option Explicit statement in each module. And also note when you choose Require Variable Declaration option, it will effect only modules that are created after the option is turned on. So enter the statement manually for old modules.
Naming Rules
The following are the rules to be followed while creating variable names.
• Must start with an alphabet (A-Z or a-z).
• Can contain A-Z, a-z, 0-9 and special characters %,&,!, #,@, and $.
Operators
An operator is a symbol or a word that performs an operation. Depending upon the type of operation an operator performs, operators are classified as follows:
Category What it does?
Arithmetic Operators Used to perform arithmetic operations such as addition, subtraction etc.
Relational Operators Used in forming conditions used to compare values.
Logical Operators Used to combine conditions or to negate condition
Assignment Operator Used to assign a value to a variable
Concatenation Operator Used to concatenate ( join) two strings
Table 4.2: Operators categories.
Now, let us discuss operators in each category in detail.
Arithmetic Operators
The following are various arithmetic operators.
Operator What it does?
+ Addition
- Subtraction. This operator can also be used as unary operator. In this case, it negates the sign of the number. For example, if variable A contains –10 then –A will result in 10(positive 10).
/ Division
* Multiplication
Mod Modulus. Returns the remainder of the division.
\ Integer Division. Returns only integer portion of the quotient.
Table 4.3: Arithmetic Operators.
Relational Operators
The following are the operators used to form conditions. The result of any expression using a relational operator will be either True or False.
Operator Meaning
< Less than > Greater than
<= Less than or equal to >= Greater than or equal to
= Equal to
<> Not equal to
Table 4.4: Relational Operators.
Note: In Visual Basic, True means –1 and False means 0.
Logical Operators
These operators are used to combine two relational operators. The following are the available logical operators.
Operator Meaning
AND Both the conditions must be true for the entire condition to be true.
OR If either condition is true then the entire condition is true.
NOT Reverses the result of the condition.
XOR The entire condition is true only when either of the conditions is true. If both the conditions are true or if both the conditions are false then entire condition is false.
EQV The entire condition is true only when both the conditions are either true or false.
IMP The entire condition is true except when the first condition is true and the second condition is false.
Table 4.5: Logical Operators.
Note: Most commonly used logical operators are AND, OR and NOT.
Examples:
If a > b and a > c then
Print “A is the biggest”
End if
If a > b or a > c then
Print “ A is greater than either b or c or both “
End if
If not workdone then
Print “Work is still in progress”
End if
In third example, workdone is assumed to be a Boolean variable, which either contains true or false. If workdone contains true then the result of the condition will be false and vice versa. Be familiar with such expressions, as they are very common in programming.
If Statement
It is very common to test a condition and take either of two possible actions based on the result of the test. If statement is used to test condition and act according to the result of the condition.
If condition Then
Statements
Else
Statements
End if
If condition is satisfied then statements given after Then will be executed otherwise statements given after Else are executed.
As you can understand from the syntax, Else is optional. If you do not give else then no statements will be executed when condition is not true.
Single Line vs. Multiple Line
You can give entire if statement in a single line. The following is an example of single line if statements.
If amount > 10000 then discount = amount * 0.10
Note that when you use single line if statement End if is NOT required.
If .. then .. elseif… else statement
When you have to test for multiple conditions and take action based on the result of conditions then multiple if statement is best suited.
If condition then
Statements
Elseif condition then
Statements
Else
Statements
End if
In the if..elseif ladder, if condition is ever true the statements after that conditions will be executed and control comes out of entire if statement.
The following is an example where we determine the percentage of discount based on the value of amount variable.
If amount > 20000 then
Dis = 10
Elseif amount > 15000 then
Dis = 8
Elseif amount > 10000 then
Dis = 5
Else
Dis = 0 ‘ no discount
End if
Select Case Statement
This statement is used when a single variable value is to be compared with different set of values.
Select Case expression
Case value-1
Statements
[Case value-2
Statements]…
[Case else
Statements]
End Select
Expression is evaluated in the beginning of the statement and the result is compared with the given values from top. If at any point the value is equivalent to the result of condition then the corresponding statements are executed and control comes out of Select Case statement.
Case Else is executed when none of the given values match the result of the expression.
The value may be either a single value or a range of values or a collection of values. It may also be a combination of all. The following example will explain the point.
Select Case code
Case 1
Dis = 10
Case 2 to 4
Dis = 12
Case 5, 7
Dis = 14
Case 6, 7 to 10
Dis = 11
Case else
Dis = 0
End select
In the above Select Case statement, first the value of variable code is compared with 1 (first case). If they are same then the corresponding action takes place (setting dis variable to value 10). Otherwise, code is compared with second case, in which case, condition will be true if code is in the range 2 to 4. In third case code is compared with 5 and 7. In fourth case, code is compared with value 6 and also with the range from 7 to 10.
In none of the given conditions are true, then statements given after Case Else are executed, where dis is set to 0. The following are the possible values that you can give after each case:
• A single constant. Ex: 10
• A single range. Ex: 1 to 5
• A collection of values each separated by comma. Ex: 1,4,6
• Any combination of the above three. Ex: 5,7, 10 to 15
Looping Structures
A looping structure allows a set of statements to be repeatedly executed. Visual Basic provides as many as five looping structures. The choice of the looping structure mainly depends on the requirement. If for example, you have to execute a set of statements for 10 times then For loop is ideal, if you have to execute statement until a condition is satisfied then Loop Until is to be used. In the following sessions I will discuss more about all the available looping structures in Visual Basic 6.0.
• DO WHILE … LOOP
• DO UNTIL … LOOP
• DO … LOOP WHILE
• DO … LOOP UNTIL
• FOR ... NEXT
The following sections discuss about each of the available looping structrues.
Do While … Loop
Executes given set of statements as long as the condition is true. Once condition is false then loop is terminated and control is transferred to the immediate next statement after the loop.
Do While condition
Statements
Loop
The following example will display numbers from 1 to 10.
I = 1
Do while I <= 10 Print I I = I + 1 Loop Do Until… Loop Executes given set of statements until the condition is true. That means the statements are executed as long as condition is false. Once condition is true, loop is terminated and control is transferred to the immediate next statement after the loop. Do Until condition Statements Loop The following example will display numbers from 1 to 10. I = 1 Do until I > 10
Print I
I = I + 1
Loop
Do … Loop While
Executes given set of statements as long as the condition is true. But in this, condition is checked after the loop is executed. As a result, the statements are executed at least for once. Except the difference between the minimum number of times the loop is executed, where for Do .. While it is 0 and for Do..Loop While it is 1, both these loops work identically.
do
Statements
loop while condition
The following example displays numbers from 1 to 10.
I = 1
Do
Print I
I = I + 1
Loop while I <= 10 Do… Loop Until This is same as Do … Loop While except that it executes statements until the condition is true. In other words, as long as the condition is false. do Statements loop until condition The following example displays numbers from 1 to 10. I = 1 Do Print I I = I + 1 Loop until I > 10
For ... Next Loop
This loop is used where the number of repetitions is known at the time of writing the program. For example, if you want to print numbers 1 to 10 then you know that the loop is to be repeated for 10 times. This loop is ideal in cases like this. Another advantage of this loop is; counter is automatically incremented or decremented by the loop. It is also possible to control the increment using Step option.
For counter = start to end [step value]
Statements
Next [counter]
Counter Is an integer variable whose value is initially set to start and then incremented after each iteration of the loop. When its value exceeds end value then loop is terminated.
Start Specifies the value that is to be assigned to counter at the beginning of the loop. It may be any valid Visual Basic expression.
End Specifies the ending value. Once counter exceeds this value the loop is terminated. This will be more than start for normal loop and less than start in reverse loop.
Step This entry is optional. If not given, it defaults to 1. This specifies the value by which counter is to be incremented at the end of each repetition. This should be negative, if start value is more than end value (reverse loop).
Statements The statements to be executed.
Next Identifies the ending of the statements to be executed. Upon reaching this, For increments the counter and checks whether counter exceeds end value. If not it enters into next iteration otherwise loop will be terminated. Though giving counter after Next is optional, it may make especially nested loops clear.
In the following example for loop is used to display only even numbers in the range 50 to 100.
For c = 50 to 100 step 2
Print c
Next c
Initially C is set to 50. After each iteration C is incremented by 2. When C exceeds 100 the loop is terminated, otherwise the value of C is printed.
The following is an example to print numbers from 10 to 1.
For c = 10 to 1 step -1
Print c
Next c
Here, as step value is –1 after each iteration counter (C) is decremented by 1. If C goes below 1 then loop is terminated.
Exit Do Statement
This statement is used to terminate DO loops from within the loop. Normally a loop is terminated or continued based on the result of the condition given in loop. But in some occasions, it is required to check for a condition within the loop and terminate loop depending upon the result of the condition.
In the following example, the loop is repeated until user entered 10 numbers or until a negative number is entered.
Cnt = 1
Do while cnt <= 10
‘ take value and place it in variable N
…
if N < 0 then
exit do
end if
…
loop
Exit For Statement
This is conceptually same as Exit do, but this is used to terminate a FOR loop.
GoTo Statement
This is used to transfer control to the specified label. Goto is NOT recommended, as it is difficult to follow the logic of the program if control is transferred from one place to another using GoTo. In other words GoTo spoils the structure of the program. However in some cases GoTo might come out as better choice than the remaining.
GoTo label
Here is an example, when control is transferred to the beginning of the procedure if user responds by entering you.
' It is an imaginary procedure to demonstrate how to use GOTO
Sub Procedure ()
Retry:
Statement
If resp = “YES” Then
GoTo retry
End if
End sub
Note: You can transfer control within a procedure.
We will see GoTo in action in runtime error handling
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment