VB6 Tutorial 56: User Defined Types

By | 2018-05-29

The user defined type in Visual Basic 6 is a compound data structure. It holds several variables of different data types. After defining a UDT, you can assign values to the member variables of the UDT.

Defining the user defined type

Before using the UDT in your code, you must first define it using the Type directive in the Declarations section of a module, for example, a form module. The following block of code is called the Type structure.

Example

Private Type BookDetails       'in Declarations section
    title As String
    author As String
    pages As Long
End Type

After defining the UDT variable, declare variables of that type.

Assigning values

Private Sub cmdSetValue_Click()
    Dim book1 As BookDetails   'Declaring book1 as the type BookDetails
    'Assigning values
    book1.author = "Balagurusamy" 
    book1.title = "C Programming"
    book1.pages = 600
End Sub

With…End with

Use “With…End with” structure for the better readability of your code. It eases up the structure.

Example

Dim book1 As BookDetails

With book1
    .author = "Balagurusamy"
    .title = "C Programming"
    .pages = 600
End With

With book1
    Print .author, .pages, .title
End With

Sub structure of a user defined type

The Type structure can also have sub structures. In this case, you have to access the nested structure using the nested “With…End With” structure.

Example

'Sub structure of UDT
Private Type AddressDetails
    city As String
    state As String
    pin As Long
    ph_no As String
End Type

Private Type StudentDetails
    name As String
    stream As String
    DepartmentId As String
    address As AddressDetails
End Type

Private Sub cmdSetDetails_Click()
    Dim student1 As StudentDetails

    'Nested With...End With structure
    With student1
        .name = "XYZ"
        .stream = "Computer Science"
        .DepartmentId = "C900"
        MsgBox .name & vbTab & .stream & vbTab & .DepartmentId
        With .address
            .city = "London"
            .state = "abc gdf"
            .pin = 77764
            .ph_no = "998765432"
            MsgBox .city & vbTab & .ph_no & vbTab & .pin & vbTab _
             & .state
        End With
    End With

End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.