|
|
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
|
6. Code6.1 VariablesA 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 + cIf 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 + 150Therefore, 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 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 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:
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 Boolean6.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 Arrays6.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 LongThese 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 LongThis 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 LongThis line would extend the previous array to 21 elements.
6.1.2.2 Multiple dimensions
Dim strBoard (8, 8) As StringAt 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 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 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 Collection2. 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
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.ClearAfter 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
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 VariablesA 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 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
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 LevelIn 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 StringElsewhere in the project:
Private Sub Command1_Click()
Text1.Text = g_strPath
End Sub
6.1.4.4 Scope Naming ConventionIn 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:
Exercise vii:
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 = lngAThis 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:
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:
intLoopCountThe generally accepted Hungarian prefixes for the standard Data Types are:
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_intLoopCount6.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>> | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||