If we declare a UDT first in a module, outside of any subroutine or function, it is available to all the modules in the workbook. Why Did We Declare UDT on Top of the Module? To access the structure's elements we use another for loop. Afterwards we use a for loop to initialize the array. Then we used Redim to define the size of arrays. The we just created an array using a dim keyword like we do for any variable in VBA. In the above code, first defined UDT structure before and the sub (I'll explain later why). When you run this code, this will be printed in the immediate window. Public Type Tstudentĭebug.Print (students(i).fName & " : " & students(i).rNo) You can even create an array of Tstudent type like any other data type. Similarly you can create as many as variables of Tstudent type you need. When you run the above sub it will print the result as shown below:Ĭreating an Array of UDTs and Accessing Elements 'Creating and initializing student type variable Subjects() As String 'For Subjects of student So we have a task to create a user defined data type that stores information related to students.Ī student has a first name, last name, roll number, date of birth, class, section, subjects.
Create A Student Variable that Stores Information Related to Student Sub UseUDTĮnough of the theory, let's jump into an example to see how it works. Use the name of the data type followed by a dot and name of variable within. Now to use the variables within this UDT we use dot operator. 'Declaring variable of user defined data type To use your UDT in the program declare its variable like any other variable. And Integer, String, Variant, another UDT, Arrays, collections, anything. It is convention to use T before the Name of Data Type so that you can differentiate between vba collections and UDTs. Then we write the name of our custom data type. So to define a custom data type in VBA we start with Type Keyword. Var1 as datatype 'datatype can be anything, int, array,or even UDT To define a structure or UDTs in VBA we use Type_End Type block. In this article, we will learn how you can create your own data type in VBA. For this we can use defined data types of VBA.
How about creating a data type of student, teacher, classes, etc that stores values related to them. Now having different variables for each entity in school will be messy work. Similarly, there will be many other objects like, librarian, classes, principle etc. A school also has teachers, so there will be teacher names, teacher subject, classes, etc. Here, you will have different types of variables like student name, student roll no, class, etc. Let's say you are trying to create a school management system.