Sign In
Link to us
Home
1. Introduction
2. Introducing VB
3. Projects
4. Containers
5. Controls
6. Code
 6.1 Variables
 6.2 Procedures
 6.3 Events
 6.4 Modules
 6.5 VB Code Syntax
 6.6 Using Files
 6.7 Printing

7. Forms
8. Debugging Code
9. Error Handling
10. Objects
11. User Controls
12. Data Projects
13. API
14. Distribution

Other Resources


Affiliated Links:
www.freefunfings.com


6. Code

6.1 Variables

A Variable is a symbol which Visual Basic uses to refer to an area of memory that stores a single item of data. Variables work in a similar way to the variables in algebra. For example, consider the equation:

y= mx + c
If we assigned values to m, x and c, we could calculate y, but since this relationship is true for many different values, we represent it using the symbols m, x and c. Similarly, in Visual Basic, we can use symbols (Variables) to represent values which can be changed, or use fixed values.

For example, the value of the variable "intN" is calculated by adding the values of the variable "intX" and a constant, 150:

IntN = intX + 150
Therefore, if the value of the variable "intX" is 25, the variable "intN" will be changed to 175 by this line of code.

6.1.1 Declaring Variables
It is necessary to declare a variable before it is used. This tells Visual Basic that you intend to use the variable's symbol to reference some data. Even if you do not explicitly declare a variable before use, Visual Basic will make a judgement about the variable when it compiles you program code and attempt to declare it itself.

Occasionally, Visual Basic may declare a variable incorrectly because it uses your program code in context to 'predict' what Type the variable should be. If this happens, you may get strange conversion errors occurring, so it is advised that all variables are expressly declared.

To make sure that Visual Basic doesn't try to declare variables itself (say, if you've mis-spelled a variable which Visual Basic thinks is a new one), type "Option Explicit" at the top of the code window in each module (see later).

6.1.1.1 Standard Types
When declaring and using variables in Visual Basic, you must specify what Data Type you want them to be. A variable must be declared so that Visual Basic can decide how much memory to allocate for storage of the variable's data. A Boolean type (Yes/No) variable only requires 1 bit, whereas an Integer (-32768 to 32767) requires 2 bytes.

Even if you don't explicitly say what type you want the variable to be, Visual Basic defaults to a Variant type - so you have implicitly declared it as a Variant. A Variant is a special data type that is capable of storing all other kinds of data. Unfortunately, in order to do this, it must be allocated a large area of memory.

There are several standard Data Types in Visual Basic, but you can also create custom Data Types. The standard Data Types are:

Data TypeRange
BooleanTrue or False
Byte0 to 255 (integer)
Currency-922,337,203,685,477.5808 to 922,337,203,685,477.5807 (4 decimal places)
DateJanuary 1, 0100, to December 31, 9999, including time (stored as variant)
Double-1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values (float)
Integer-32,768 to 32,767 (integer)
Long-2,147,483,648 to 2,147,483,647 (integer)
Single-3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values (float)
StringASCII characters length 1 to 65535 if fixed, or 1 to 2 Billion if variable
VariantAll other types supported, except fixed length strings

Note:  Although Variant types can actually store values in any of the above formats, the memory occupied by a Variant Type is far greater than that of say, an Integer.

A variable is generally declared using the Dim keyword and the As modifier as follows:

Dim MyVariable As DataType
e.g.        Dim strName As String
e.g.        Dim blnFound As Boolean
6.1.1.2 Custom Types
Visual Basic provides a facility for customising Data Types. This is known as a Type Declaration. A Type can be scoped as Public or Private, if omitted Visual Basic defaults the Type to Public.

Scope Type NewTypeName
    TypeVariable1 As Type
    --etc--
    TypeVariableN As Type
End Type

e.g.	
Private Type Co_Employee
    Name As String
    JobTitle As String
    Pay As Single
End Type
Once you have declared the custom Type, you can used it to declare variables for use within your application and refer to it's characteristics (sub-types) using the dot (".") modifier, in the normal way:

Private Type Co_Employee
    Name As String
    JobTitle As String
    Pay As Single
End Type

Dim Dave As Co_Employee
Dim Cedric As Co_Employee

Private Sub Form_Load()
    Dave.Name = "Dave Smith"
    Dave.JobTitle = "Internal Affairs"
    Dave.Pay = 2015.12

    Cedric.Name = "Cedric Jones"
    Cedric.JobTitle = "Accounts"
    Cedric.Pay = 1756.52
End Sub
6.1.2 Variable Arrays
6.1.2.1 Declaration
As we saw earlier, an Array is a collection of items that are the same type with the same variable name. Arrays can be declared with their length or can have their length changed during the program execution.

For example:
Dim lngVals(10) As Long
Dim lngUnit() as Long
These lines declare two new variable Arrays. The "lngVals" array has 11 elements (0 to 10), whilst the "lngUnit" array length has not yet been determined. During program execution, the second array can be re-dimensioned (re-sized) using the ReDim statement as follows:

ReDim lngUnit(0 to 15) As Long
This statement would re-dimension the array to have 16 elements (0 to 15). If you needed to change this later in the program, just ReDim the array again. One problem with using ReDim is that each time it is done, the contents of the array are lost. It is possible to preserve the contents of an array using the Preserve keyword in the ReDim statement. There are limitations to the use of Preserve, so check before using it. In general, it is better to design your variable arrays efficiently before beginning coding, only using re-sizeable arrays if absolutely necessary. An example of a preserved re-dimension of an array:

ReDim Preserve lngUnit(0 to 20) As Long
This line would extend the previous array to 21 elements.

6.1.2.2 Multiple dimensions
A variable array can have several (up to 60) dimensions. For example, if you were developing a simple Chess game, you might want to store the board layout in a two-dimensional array of strings. Each string is either blank (indicating there is no piece on that square) or contains the name of a chess piece:

Dim strBoard (8, 8) As String
At the start of each game, the squares at each of the 'co-ordinates' can then be defined by referencing the elements and setting the values for the pieces:

strBoard(1, 1) = "White Rook"
strBoard(1, 2) = "White Knight"
--etc--
strBoard(8, 8) = "Black Rook"
6.1.2.3 Referencing Arrays
Array elements can be individually referenced in the code as follows:

strUser(4) = "Bob"
This line would set the fifth (since the array starts at 0) element in the Array to "Bob". The array element is selected by the index. Using Arrays with this index can be a useful way of storing similar data type variables for quicker referencing within the program. To continue our Chess example, let us say that we have created a Form with 64 Label controls in a 64 element Control Array (see earlier), arranged in an 8 x 8 grid. Each of the Labels is populated with the Chess board piece names above:

For lngBrdY = 1 To 8
    For lngBrdX = 1 To 8
        lngSquareNumber = (lngBrdY - 1) * 8 + lngBrdX
        Label1(lngSquareNumber).Caption = strBoard(lngBrdX, lngBrdY)
    Next lngBrdX
Next lngBrdX
The two For.Next loops are used to cycle through the elements of the variable array "strBoard" one at a time, but is also used to calculate the square number, which is used as the index to the Label control array.

6.1.3 Collections
A collection in Visual Basic works in a similar way to an array, except that a collection does not exist as a variable - it is an object. When you define a collection, remember that you are creating an object and therefore you can't simply assign a value to it, as you can with a variable. You have to use the object's methods and/or properties to manipulate the contents of the collection.

One of the main uses of collections is as a means of passing lists of data between methods. For example returning a list of names from a function.

6.1.3.1 Dimensioning the Collection
A collection is declared in a similar way to a variable; there is the "Dim" keyword, an identifier and a type assignment. One difference, however, is that a collection object is declared as an instance of the original object and as such has to be set to reference that original object. There are two ways of doing this:

1. Declare the identifier, then set the identifier to reference a new instance (copy of) of the collection object:

Dim colNames As Collection
Set colNames = New Collection
2. Generate a new instance of the collection object within the declaration:

Dim colNames As New Collection
Note:  The "New" keyword is only used in object declarations. This tells Visual Basic that you want to create a new instance of the object and set the name of the instance to the declared identifier.

6.1.3.2 Collection Type Functions
A function can be declared so as to return a collection, however the "New" keyword cannot be used in the declaration line of a function, therefore the returned collection must be assigned to another collection that has been allocated a new instance of the collection object:

Private Function GetNames() As Collection   ' Cannot use "New"
    Dim colN As New Collection                  ' Use a local collection to make a new instance of collection object
    colN.Add "John"                             ' Add a name to the "colN" collection
    colN.Add "Paul"                             ' Add a name to the "colN" collection
    colN.Add "George"                           ' Add a name to the "colN" collection
    colN.Add "Ringo"                            ' Add a name to the "colN" collection
    Set GetNames = colN                         ' Set the returned collection to the local collection
                                                ' This forces the same instance to exist as both "colN" and "GetNames"
End Function
Once the returned collection is "Set" to the local collection, they are considered to be one and the same. Any actions that are performed on one are also reflected in the other; they are like aliases for the same instance of the collection object.

In order to use this function, you would need a collection for the returned data to be stored in:

Dim colC As New Collection
Set colC = GetNames()
Notice again that the returned data collection has to be "Set" to the "colC" collection. This automatically assigns the "colC" identifier to the same collection instance as the one returned by the function.

6.1.3.3 Adding to and Clearing a Collection
As mentioned earlier, a collection is an object. It therefore has properties and methods that you can call. Once a collection has been initialised (by declaring it), it can then have entries added to it. This is done by invoking the "Add" method with a parameter as follows:

colC.Add "My new item"
When adding items to a collection, new entries are placed at the end of the list. If you want to govern the order that items are added, you can also specify a key. This key is a unique text String that can be used to reference entries later. As the collection is build up, you can also specify that new entries are inserted before or after a particular key:

' Format is: MyCollection.Add Item, Key, BeforeKey, AfterKey
colC.Add "First Entry", "#1"               ' Key is "#1"
colC.Add "Third Entry", "#3", ,  "#1"      ' Key is "#3", inserted after the item with key "#1"
colC.Add "Second Entry", "#2", "#3"        ' Key is "#2", inserted before the item with key "#3"
Note:  You can specify whether you want to insert the new entry before or after a particular key, but not both. Also, the keys that you make reference to must exist.

If you want to clear all entries within a collection, invoke the "Clear" method as follows:

colC.Clear
After clearing the collection all data will be lost and the collection object is effectively re-initialised.

6.1.3.4 Referencing Items in a Collection
Once you have your collection, items within it can be referenced by their index or their key. The index is equivalent to their numerical position within the collection and the key is the text String that you specified when the item was added to the collection:

strName = colC.Item(5)       ' Get the 6th item in the collection (items start at 0!)
strName = colC.Item("#1")    ' Get the item whose key is "#1"
The last of the collection object's methods is the Count. This method returns the total number of items in the collection. When using this method, remember that the items begin at position 0 and therefore the Count is always one more than the index number of the last item. This means that if the count method of a collection "colC" returns "25", the last item in the collection is colC.Item(24).

For n = 0 to colC.Count - 1
    If colC.Item(n) = "" Then strEmpty = "Empty entry found"
Next n
6.1.4 Scoping Variables
A variable is accessible at different levels of the code, depending on where and how it was declared. The extent to which the variable can be accessed is called it's Scope. There are three types of scope.

6.1.4.1 Procedure Level
When a variable is only required for the duration of a Method (such as a Sub or Function) it can be declared inside the Method. This variable is then only visible within this Method. Any attempt to access it in the rest of the code will either give an error or cause a new (and totally different) variable to be created, depending on your project settings (see "Option Explicit").

Example:

Private Sub Command1_Click()
    Dim strName As String
    strName = "Dave"
End Sub

Private Sub Command2_Click()
    Label1.Caption = strName
End Sub
In this example, the variable "strName" is declared inside the "click" Event Method of "Command1". This is a Procedure-Level or Local-Level declaration. In "Command2", a Label's Caption Property is being set to the value of "strName". Since "strName" does not exist within the scope of "Command2", it is either created with a default value of "" (nothing) or results in a compilation error (see "Option Explicit"). The Label control will therefore display blank.

Note that if "Command2" had declared a variable called "strName", this would be a totally different variable to the one in "Command1" and would still have been initialised as a blank string.

6.1.4.2 Module Level
In order for this code to work as intended, the Variable declaration for "strName" should be moved outside of any procedures, to the top of the code (in the Code View Window, this appears as "(General)" "(Declarations)" in the combo boxes at the top). This is now a Module-Level declaration. The variable is visible to all Methods within the same Module (a Module can be the code behind a Form or the code in a Code Module, Class Module etc). The code should now look like this:

Dim strName As String

Private Sub Command1_Click()
    strName = "Dave"
End Sub

Private Sub Command2_Click()
    Label1.Caption = strName
End Sub
6.1.4.3 Global Level
In the example we have developed so far, we have two Forms. If we had a variable in the first Form that we wanted to make available to the second Form, we could declare the variable as a Public-Level or Global variable. A Public-Level variable is visible to all Modules in the project. This type of declaration is not a secure one, as any of the associated modules can change the contents of the variable at any time. The code would look like this:

Public strName As String

Private Sub Command1_Click()
    strName = "Dave"
End Sub

Private Sub Command2_Click()
    Label1.Caption = strName
End Sub
Modules within the same project can reference this variable as a property of the form in which it was declared (the form's object model is altered). So, if the variable "strName" was declared on the Form "frmMain", it can be referenced from elsewhere as frmMain.strName. Since the variable is declared in a form, it is only available whilst that form is loaded. If the form is unloaded, a reference to the variable will cause errors. This is true of all variables declared on all objects, such as custom controls, instances of class modules etc.

If the variable is declared within a standard code module, it is always available and since the code module itself is not an object the variable can be referenced directly.

In a standard Code Module:

Public g_strPath As String
Elsewhere in the project:

Private Sub Command1_Click()
    Text1.Text = g_strPath
End Sub
6.1.4.4 Scope Naming Convention
In order to keep track of the scope of variables declared in a project, it is common practice to prefix the variable name with a letter indicating it's scope:

Public-Level, Global:g_VarName
Module-Level:m_VarName
Local-Level:VarName

Exercise vii:
  • Modify the existing project so that the user enters a name into a TextBox control on Form1. Remember to make a copy of the original project in a new folder.
  • Change the Event Method for Command1 so that the text in the TextBox control is passed into a Public-Level string variable called "strInputText", before showing Form2.
  • In Form2's Load Event Method, set the caption property of Form2 to the text held in "strInputText" on Form1. Remember that this variable is now a property of Form1.

Test the project when you have finished.


6.1.5 Converting Types
Although Visual Basic can do Type Conversion implicitly, it is recommended that a conversion function be used explicitly in order to make the code easier to read and to reduce Type Conversion errors.

Example:

Dim lngA As Long
Dim strA As String
lngA = 250*5
strA = lngA
This last line would work, however, it is good practice to convert as follows:

Dim lngA As Long
Dim strA As String
lngA = 250*5
strA = CStr(lngA)
You may also encounter Type Mismatch errors or unpredictable results when entering parameters directly into a procedure call. For example, the following code is supposed to display the result of an addition, but the variables are String and are therefore concatenated:

Dim strA As String
Dim strB As String
strA = Text1.Text      ' eg Text1 = "25"
strB = Text2.Text      ' eg Text2 = "13"
MsgBox strA + strB     ' displays "2513"
The correct response is achieved with type conversion:

MsgBox CLng(strA) + CLng(strB)			' displays "38"
The in-built Functions to convert between Data Types:

Convert to TypeFunction
BooleanCBool(expression)
ByteCByte(expression)
CurrencyCCur(expression)
Date (time)CDate(expression)
DoubleCDbl(expression)
DecimalCDec(expression)
IntegerCInt(expression)
LongCLng(expression)
SingleCSng(expression)
StringCStr(expression)
VariantCVar(expression)

6.1.6 Variables Hungarian Notation
In Visual Basic, you can give variables whatever names you like, provided it is not a reserved word (e.g. Dim, Long, As, Boolean would not work). As with variable naming according to Scope (see earlier), it is recommended that variables are named according to their Type.

The system of "Hungarian" notation is one that has been widely accepted as being the most suitable. This system consists of a lower-case prefix indicating the Data Type followed by the variable name with capitalised initial letters.

For example, an integer type that is used to store the count for a loop of code might be called:

intLoopCount
The generally accepted Hungarian prefixes for the standard Data Types are:

Data TypePrefixExample
BooleanblnblnMyVariable
BytebytbytMyVariable
CurrencycurcurMyVariable
Date (time)dtmdtmMyVariable
DoubledbldblMyVariable
IntegerintintMyVariable
LonglnglngMyVariable
SinglesngsngMyVariable
StringstrstrMyVariable
VariantvntvntMyVariable
User-defined typeudtudtMyVariable
ObjectobjobjMyObject

The Hungarian notation is generally used in conjunction with the scope prefix we saw earlier. This means that if the previous loop count example was a global variable, it might be called:

g_intLoopCount
6.1.7 Option Explicit
As mentioned earlier, if a variable doesn't exist in the current scope (possible because you have declared it in a scope that is invisible to the current procedure or have simply mis-spelled it), Visual Basic will create a new variable without you having to explicitly declare it. This is quite useful sometimes, but in general causes errors. If you aren't careful, you could end up with variables being used all over the place that have the same name, but are actually total different variables (see "Scoping Variables").

One of the options available with every module of code in Visual Basic is the Option Explicit option. When this is enabled, every variable used in your code must be declared before using it. If it is not, a "Variable not defined" error will occur during compilation, giving you the chance to correct the problem. During development of exercises on this course and on all future Visual Basic development, it is strongly recommended that the Option Explicit option be used.

To enable this option, simply type Option Explicit at the very top of the Code View window prior to any other lines of code.

<<Page 5.2  :   Top  :   Page 6.2>>

©vbtraining.co.uk