If you are just starting out with the language, why not pick up a few good habits right now and it may make your life a lot easier down the road.
- Use comments when appropriate but not so many as to overwhelm the code; the apostrophe ' is the comment identifier; it can be at the beginning of a line or after the code.
' This is a comment
' on 2 lines.
DIM intNumber AS Integer 'This is a comment
- Use indents - code must be indented under control structures such as If ... Then or Sub - it makes it so much easier to follow the logic.
FOR i = 1 TO 5
value(i) = 0 ' Indent used in control structures
NEXT i
- Use standard capitalization - keywords like If, Dim, Option, Private start with a capital letter with the rest in lower case; variable names, control names, etc. are usually mixed case: ClientName, StudentId, etc.
- Write extra-long statements on 2 lines using the continuation character _ (space underscore); in VB each line is assumed to be an individual statement unless there is a continuation at the end of the first line.
Data1.RecordSource = _
"Select * From Titles" ' One statement on 2 lines is OK
Naming conventions
These are the rules to follow when naming elements in VB - variables, constants, controls, procedures, and so on:
- A name must begin with a letter.
- May be as much as 255 characters long (but don't forget that somedy has to type the stuff!).
- Must not contain a space or an embedded period or type-declaration characters used to specify a data type ; these are ! # % $ & @
- Must not be a reserved word (that is part of the code, like Option, for example).
- The dash, although legal, should be avoided because it may be confused with the minus sign. Instead of Family-name use Family_name or FamilyName.
Data types
| Data type |
Storage size |
Range |
| Byte | 1 byte | 0 to 255 |
| Boolean | 2 bytes | True or False |
| Integer | 2 bytes | -32,768 to 32,767 |
| Long
(long integer) | 4 bytes | -2,147,483,648 to 2,147,483,647 |
| Single
(single-precision floating-point) | 4 bytes | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values |
| Double
(double-precision floating-point) | 8 bytes | -1.79769313486232E308 to
-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values |
| Currency
(scaled integer) | 8 bytes | -922,337,203,685,477.5808 to 922,337,203,685,477.5807 |
| Decimal | 14 bytes | +/-79,228,162,514,264,337,593,543,950,335 with no decimal point;
+/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is
+/-0.0000000000000000000000000001 |
| Date | 8 bytes | January 1, 100 to December 31, 9999 |
| Object | 4 bytes | Any Object reference |
| String
(variable-length) | 10 bytes + string length | 0 to approximately 2 billion |
| String
(fixed-length) | Length of string | 1 to approximately 65,400 |
| Variant
(with numbers) | 16 bytes | Any numeric value up to the range of a Double |
| Variant
(with characters) | 22 bytes + string length | Same range as for variable-length String |
| User-defined
(using Type) | Number required by elements | The range of each element is the same as the range of its data type. |
In all probability, in 90% of your applications you will use at most six types: String, Integer, Long, Single, Boolean and Date. The Variant type is often used automatically when type is not important. A Variant-type field can contain text or numbers, depending on the data that is actually entered. It is flexible but it is not very efficient in terms of storage.
Declaring variables
Declaring a variable means giving it a name, a data type and sometimes an initial value. The declaration can be
explicit or
implicit.
An
explicit declaration: variable is declared in the Declarations Section or at the beginning of a Procedure. An explicit declaration looks like:
Dim MyNumber As Integer
Now the variable
MyNumber exists and a 2-byte space has been reserved for it.
An
implicit declaration: the variable is declared "on the fly", its data type is deduced from other variables. For example:
Dim Total1 As Integer 'Explicit declaration
Dim Total2 As Integer 'Explicit declaration
Total3 = Total1 + Total2 'Implicit declaration
Total3 is not formally declared but is implied, it is "arrived at" from the other declarations.
It is never a good idea to have implicit declarations. It goes against the rules for clarity, readability and ease of use of the code.
To make sure that this rule is followed, start the Declarations with the
Option Explicit clause. This tells the compiler to consider implicit declarations as errors and forces the programmer to declare everything explicitly.
Other examples of declarations:
Dim MyName As String
Dim StudentDOB As Date
Dim Amount5, Amount6, Amount7
In the last example the type assigned to each variable will be: Variant. It is the default type when none is specified.
There can be multiple explicit declarations in a statement:
Dim EmpName As String, SalaryMonth As Currency, SalaryYear As Currency
In this final example, what are the types assigned to the three variables:
Dim Amount1, Amount2, Amount3 As Single
All Single-precision floating point, you say.
Wrong! Only Amount3 is Single. Amount1 and Amount2 are considered Variant because VB specifies that each variable in a statement must be explicitly declared. Thus Amount1 and Amount2 take the default data type. This is different from what most other languages do.
Constants
A constant is a value that does not change during the execution of a procedure. The constant is defined with:
Const ValuePi = 3.1416
The Scope of variables
The term
Scope refers to whether the variable is available outside the procedure in which it appears. The scope is
procedure-level or
module-level.
A variable declared with Dim at the beginning of a procedure is only available in that procedure. When the procedure ends, the variable disappears. Consider the following example:
Option Explicit
Dim Total2 As Integer
Private Sub Command1_Click ()
Dim Total1 As Integer
Static Total3 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Private Sub Command2_Click ()
Dim Total1 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Every time Button1 is clicked, Total1 is declared as a new variable during the execution of that clicked event. It is a
procedure-level variable. It will always stay at 1. The same for the Button2 event: Total1 is a new variable in that procedure. When the procedure ends, Total1 disappears.
Total2 is declared in the Declarations section. It is a
module-level variable, meaning it is available to every control in this Form. When Button1 is clicked, it increments by 1 and it retains that value. When Button2 is clicked, Total2 is incremented from its previous value, even if it came from the Button1 event.
Total3 shows another way of retaining the value of a local variable. By declaring it with
Static instead of Dim, the variable acts like a module-level variable, although it is declared in a procedure.
Another scope indicator that you will see when you study examples of code is
Private and
Public. This determines whether a procedure is available only in this Form (module) or if it is available to any module in the application. For now, we will work only with Private procedures.
Operators
Mathematical and Text operators
| Operator |
Definition |
Example |
Result |
| ^ |
Exponent (power of) |
4 ^ 2 |
16 |
| * |
Multiply |
5 * 4 |
20 |
| / |
Divide |
20 / 4 |
5 |
| + |
Add |
3 + 4 |
7 |
| - |
Subtract |
7 - 3 |
4 |
| Mod |
Remainder of division |
20 Mod 6 |
2 |
| \ |
Integer division |
20 \ 6 |
3 |
| & |
String concatenation |
"Joan" & " " & "Smith" |
"Joan Smith" |
Note that the order of operators is determined by the usual rules in programming. When a statement includes multiple operations the order of operations is:
Parentheses ( ), ^, *, /, \, Mod, +, -
Logical operators
| Operator |
Definition |
Example |
Result |
| = |
Equal to |
9 = 11 |
False |
| > |
Greater than |
11 > 9 |
True |
| < |
Less than |
11 < 9 |
False |
| >= |
Greater or equal |
15 >= 15 |
True |
| <= |
Less or equal |
9 <= 15 |
True |
| <> |
Not equal |
9 <> 9 |
False |
| AND |
Logical AND |
(9 = 9) AND (7 = 6) |
False |
| OR |
Logical OR |
(9 = 9) OR (7 = 6) |
True |
Control Structures
If...Then...Else
If condition1 Then
statements1
Else
statements2
End If
If condition1 is True, then statements1 block is executed; Else, condition1 is not True, therefore statements2 block gets executed. The structure must be terminated with the End If statement.
The Else clause is optional. In a simple comparison, statements1 get executed or not.
If condition1 Then
statements1
End If
Select Case
Can be used as an alternative to the If...Then...Else structure, especially when many comparisons are involved.
Select Case ShirtSize
Case 1
SizeName.Caption = "Small"
Case 2
SizeName.Caption = "Medium"
Case 3
SizeName.Caption = "Large"
Case 4
SizeName.Caption = "Extra Large"
Case Else
SizeName.Caption = "Unknown size"
End Select
Do...Loop
Used to execute a block of statements an unspecified number of times.
Do While condition
statements
Loop
First, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed.
For...Next
When the number of iterations of the loop is known, it is better to use the For...Next rather than the Do...Loop.
For counter = start To end
statements
Next
1) The counter is set to the value of start.
2) Counter is checked to see if it is greater than end; if yes, control passes to the statement after the Next; if not the statements are executed.
3)At Next, counter is incremented and goes back to step 2).
More will be covered on Control strucures as it becomes necessary in upcoming lessons. Meanwhile,if you want to know more, consult the VB Language Reference.
Assignment
To practise your coding and editing skills, try modifying the Football example by adapting it for different sports. For example, in American football, which is similar to rugby, there are 4 different ways to score, as shown here:
| Touchdown |
6 points |
| Field goal |
3 points |
| 2-point Convert or Safety |
2 points |
| Convert |
1 point |
Look at "Lesson 11 - Downloads" for the solution.
If you haven't found the Visual Basic resource you're looking for,
use our Google Search box for more information.