Monday, January 16, 2023

Data type - User defined

User defined data type can be any data type using a Type statement which is more related to groups of variables. Declaration must be done at module level above the sub procedure, otherwise compile error: Invalid inside procedure as below.

Syntax : 

Type MyType
    Field1 as Any Data type
    Field2 as Any Data type
    .
    .
End Type

The above syntax must be declare at module level and below statement is inside sub procedure.

Dim MyVar as MyType

From here we can access Field1,Field2,... and etc.

Refer below for example:

VBA Vode:

Option Explicit
Type MyDetails
    Myname As String
    MyAge As Integer
    MyBirthDate As Date
    MyMarried As Boolean
End Type
Sub DataTypeExample_UserDefined()

    Dim MyBio As MyDetails
    
    MyBio.Myname = "Nazri"
    MyBio.MyAge = 50
    MyBio.MyBirthDate = "05/06/1978"
    MyBio.MyMarried = True
    
    MsgBox ("My name is " & MyBio.Myname & " my age is " & _
            MyBio.MyAge & " and married is " & MyBio.MyMarried)
    
End Sub

Note:
This User defined data type is more to static, we can't changed this inside our code only at design stage.

Read more about User defined data type, macro enabled excel, excel macro,
vba coding, vba code at below links.

Microsoft Reference-User-defined-data-type
Other Reference-User-defined-types.htm

Leave your comments if you have any request.
Practice makes perfect.
Thank You.

No comments:

Post a Comment