Dear John, How Do I... Create User-Defined Type (UDT) Structures?

The Type keyword is used to declare the framework of a UDT data structure. Notice that the Type command doesn't actually create a data structure; it only provides a detailed definition of the structure. You use a Dim statement to actually create variables of the new type.

You can declare a Public UDT structure in a standard module or a public class module. Within a form or a private class module, you must declare the UDT structure as Private. When combined with Variants, amazingly dynamic and adjustable data structures can result. The following code demonstrates a few of these details:

Option Explicit

Private Type typX
    a() As Integer
    b As String
    c As Variant
End Type
Private Sub Form_Click()
    `Create a variable of type typX
    Dim X As typX
    `Resize dynamic array within the structure
    ReDim X.a(22 To 33)
    `Assign values into the structure
    X.a(27) = 29
    X.b = "abc"
    `Insert entire array into the structure
    Dim y(100) As Double
    y(33) = 4 * Atn(1)
    X.c = y()
    `Verify a few elements of the structure   
    Print X.a(27)    `29
    Print X.b        `abc
    Print X.c(33)    `3.14159265358979
End Sub

Notice the third element of the typX data structure, which is declared as a Variant. Recall that we can store just about anything in a Variant, which means that at runtime we can create an array and insert it into the UDT data structure by assigning the array to the Variant.

Memory Alignment

32-bit Visual Basic, in its attempt to mesh well with 32-bit operating system standards, performs alignment of UDT structure elements on 4-byte boundaries in memory (known as DWORD alignment). This means that the amount of memory your UDT structures actually use is probably more than you'd expect. More important, it means that the old trick of using LSet to transfer binary data from one UDT structure to another might not work as you expect it to.

Again, your best bet is to experiment carefully and remain aware of this potential trouble spot. It could cause the kind of bugs that are hard to track down unless you're fully aware of the potential for trouble.