Excel VBA Constants And User Defined Types
Sometimes, in your Excel VBA code, you need to have a variable which always returns the same value. For example, if your application makes reference to a tax rate, having the rate in a variable will offer you a mechanism for changing the rate wherever you have used it in your application. Thus, instead of entering code like “TaxAmount = SubTototal * 0.15″, you would use statements like “TaxAmount = SubTototal * TaxRate”, where tax rate would be a constant.
In VBA, constants must be declared and initialised in one statement: for example “Const TaxRate as Currency = 0.15″. This is the only time that a value can be placed in the constant and herein lies one of its key benefits; the value it contains cannot later be accidentally overwritten because the programmer confuses this variable with another. The other key benefit is the ease with which constants allow us to update our applications. Thus, in the tax rate example, when the tax rate changes, we only need to modify one line of code and that change will update our entire application.
VBA offers us another variable technique which allows us to “tighten up” the values which may be entered into a variable is to use User Defined Types (UDTs) which, essentially, allow you to define your own variable types. You can then declare as many variables of this given type as you need. Type definitions must be placed at the top of a module; they cannot be placed inside sub routines or functions. The definition consists of a code block inside which the various elements of the type are detailed as well as the data type associated with it. Here is an example of a type definition.
Type Employee
Name As String
Department As String
JobTitle As String
DateOfBirth As Date
StartDate As Date
Salary As Long
End Type
To use create and initialise variables of this type in our code, we use statements like the following:
Dim empNew As Employee
With empNew
.Name = “Gillian Spencer”
.Department = “Information Technology”
.JobTitle = “Web Developer”
.DateOfBirth = 12/05/1982
.StartDate = 25/03/2010
.Salary = 27500
End With
UDTs provide a very useful way of storing related variables in one place. In this regard, they resemble arrays; but, unlike arrays, the elements they contain are named rather than simply referred to by a numerical index.
You can find out more about Excel VBA training courses, visit Macresource Computer Training, an independent computer training company offering Excel VBA Classes in London and throughout the UK.


