Variables

User-defined Types

In Visual Basic, you can declare you own types or classes in a module or form. This will then behave as any other object in Visual Basic, except it only has properties. For example, the Screen object in Visual Basic exposes a number of properties, including FontCount and ActiveControl. These can be accessed by entering Screen.FontCount. You can create a custom version of this, that will allow you to define various elements that can store values. For example:

Type EmployeeRecord    ' Create user-defined type.
    ID As Integer    ' Define elements of data type.
    Name As String * 20 ' Fill with 20 spaces
    Address As String * 30 ' Fill with 30 spaces
    Phone As Long
    HireDate As Date
End Type

This user-defined type has 5 properties. At the moment you cannot access them, as Visual Basic requires that you declare another variable that is referenced to this user-defined type:

Dim MyRecord As EmployeeRecord

Note that if you want to declare a Type in a form, it must be declared as private. So, the following code fills a few values into this user-defined type:

Private Type EmployeeRecord    ' Create user-defined type.
    ID As Integer    ' Define elements of data type.
    Name As String * 20 ' Fill with 20 spaces
    Address As String * 30 ' Fill with 30 spaces
    Phone As Long
    HireDate As Date
Private End Type

' Reference variable to user-defined type
Dim MyRecord As EmployeeRecord    ' Declare variable.

' Comment1_Click event.
Sub Command1_Click()
    ' Assignment to EmployeeRecord variable must occur in a procedure.
   
    MyRecord.ID = 12003    ' Assign a value to an element.
    MyRecord.Phone = 1813670690
End Sub

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“C++: an octopus made by nailing extra legs onto a dog.” - Steve Taylor