You are on page 1of 1

A4

A variable declared as type Variant can contain any type of data. Unlike a variable that declared on a specific
type, say, String or Integer, which can only contain a text string or a specific range of integers respectively, a
variant can contain any data—text or an integer value or a real, i.e., a floating point, value. It can even behave
like an array or refer to an object, either built into Excel or a user defined type. Essentially, there are almost no
rules on what a developer can do with a variant. For example, with aVar declared as a variant each of the
assignment statements is legitimate.
Dim aVar as Variant
aVar = “a”
aVar = 1
aVar = Array (1,22,333)
set aVar = ActiveSheet
aVar = 3.1415927
The common wisdom is that one should stay away from variants. By and
large, that is true. If one knows the data type of a variable it is best to declare it
correctly. There are many benefits to doing so, the most significant being that
the VBA compiler can ensure data and program integrity. With a variant one
could accidentally assign a text string to what might be intended to be a number.
Essentially, the developer gets the flexibility of a variable that can take any
type of data together with the responsibility of ensuring proper data type use.
That’s a steep burden and one best avoided whenever possible. Consequently,
in those cases where the data type is pre-determined and will not change, it is
indeed best to declare the variable of the particular type.
However, there are many instances where a variant allows one to do things
that otherwise would be impossible. The power of a variant comes from the
fact that it is a simple data element and yet can contain any—and that means
any—type of data. It can be a string or a Boolean or an integer or a real number.
Hence, when the data type returned by a function can vary, one is obligated
to use a variant for the returned value.
As we will see in a later section of this chapter, the ability to create an
array in a variant makes it possible to create functions that would otherwise
be impossible. For example, a function can return either an error condition or
an array of values. It also allows a developer to write a User Defined Function
(UDF) that returns multiple values in a single call to the function. A variant
is also one way to pass an array as a ‘by value’ argument to a procedure. One
Excel-specific reason to use a variant is that it provides a very efficient way to
exchange information between Excel and VBA.
Finally, in the advanced section of the chapter, we will use the variant data
type to create an array of arrays. This makes it possible to create, and work
with, data structures that would otherwise be impossible. It also allows one to
operate on an entire row of an array.
In the hands of a creative—and defensive—developer, the power of a variant
can be nearly limitless.

You might also like