< Previous lesson | Table of Content | Content of this Chapter | Next lesson >

User Defined Type (UDT)

In this tutorial, you will learn about User Defined Type (UDT).

Visual Basic has many data type such as Integer, String, Double, Single, etc. Aside from those intrinsic data type that has been provided by VB, you can create your own data type by combining several different types. This UDT is useful to create single variable contain several useful information. It is usually useful for database record. You define the UDT using syntax:

Type VariableType
Variable1 as varType1
Variable2 as varType2
VariableN as varTypeN
End Type

After that you can declare any name as this new variable type and use it as ordinary variable.

Note: Special for this project, please do not copy and paste from this tutorial. Type the code manually so that you may understand the different between UDT and normal variable.

  1. Create new Standard Exe project
  2. In the general declaration section, type:
    Private Type City
    Name As String
    Population As Long
    Diameter As Double ' in km
    Year As Integer
    End Type
  3. Add one Frame control; change the Caption property to City. User Defined Type
  4. Add 6 label, 4 textboxes and one command button into the Frame1 . Change the Caption of the labels respectively into: Name , Population , Year , Diameter , million , km . Change the Name property of the textboxes respectively into txtCityName , txtPopulationNumber , txtYearOfRecording , txtCityDiameter . Change the Caption of command button to Enter , and the Name property to cmdEnter .
  5. Arrange the controls so that it looks nice.
  6. Double click the command button and type the following code:
    Private Sub cmdEnter_Click()
    Dim myRecord As City
    myRecord.Name = txtCityName.Text
    myRecord.Population = txtPopulationNumber.Text
    myRecord.Year = txtYearOfRecording.Text
    myRecord.Diameter = txtCityDiameter.Text
    MsgBox myRecord.Name & " city has population of " & _ myRecord.Population & " million people " & vbCr & _
    " and diameter of " & myRecord.Diameter & " km in year " & _ myRecord.Year
    End Sub
  7. Run the program and try the data for some real city.

You see that UDT combine several data type into single unit. in the next lesson, you will learn how to combine several data type plus several sub procedures and functions into a single unit.

< Previous lesson | Table of Content | Content of this Chapter | Next lesson >