3.6. User -Defined Types

One major limitation of the multidimensional array is that all the dimensions within the array must be of the same data type. The user-defined type (UDT), which combines multiple data types into a single new data type, overcomes this limitation.

Since VB 4.0, UDTs have gone out of fashion somewhat, this fall from favor having resulted from the introduction of the Collection object, which on the surface operates like an infinitely flexible UDT. However, VB6 has given the humble UDT a new lease on life by allowing UDTs to be passed as property values and to be used in public function declarations. This is good news, as the UDT is far more efficient than a Collection object.

So what is a user-defined type? Simply put, it's a pseudo-data type constructed from other data types. One of its common applications is the replication of a data record in memory. For example, let's say you want to create a local array to hold the data of your customer records. Because each of the fields within the record is of a different data type, a multidimensional array can't be used. A UDT, on the other hand, is ideal in this situation. The following snippet defines a simple UDT:

Private Type custRecord
    custAccNo As Long
    custName As String
    RenewalDate As Date
End Type

Private custArray(10) As custRecord

The last line of code creates a local array of the UDT.

You can also use other UDTs within a UDT, as the following example demonstrates:

Private Type custOrders OrderNo As Long ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.