First we have to add a class module to our project
- Right click anywhere in the Project Window
- Click Add
- Click Class Module
A new Folder containing our new class will be created.
Open the class and type the following code
Option Explicit
Private c_StudentID As IntegerPrivate c_FirstName As String
Public Property Get StudentID() As IntegerStudentID = c_StudentIDEnd Property
Public Property Let StudentID(ByVal args As Integer)c_StudentID = argsEnd Property
Public Property Get FirstName() As StringFirstName = c_FirstNameEnd Property
Public Property Let FirstName(ByVal args As String)c_FirstName = argsEnd Property
Public Function Combine(FirstName As String)
Combine = "Hello " + FirstName
End Function
Option explicit means you must explicitly declare all variables using the Dim or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.
Tip:
Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear
Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear
Well if you may notice, we declared two variables privately: c_StudentID and c_FirstName. These two variables will hold our data temporarily. We will use them to GET or SET value to our Property.
The next lines of code declare our Properties StudentID and FirstName..
This Property will Get the data that we put on the c_StudentID variable.Public Property Get StudentID() As IntegerStudentID = c_StudentIDEnd Property
While this code Set the value that we pass [args] to c_StudentID.Public Property Let StudentID(ByVal args As Integer)c_StudentID = argsEnd Property
How to Instantiate Our Objects
Dim myStudent As New StudentHow do we set values for our properties?
Dim myStudent2 As New Student
myStudent.FirstName = "Cawi"
myStudent.StudentID = 1
myStudent.FirstName = "Cornelio"How to put our objects in a collection
myStudent.StudentID = 2
First, add to our reference the Microsoft Scripting Runtime.
- Click Project in menu bar
- Click References
- Check the Microsoft Scripting Runtime
We will use this library to use the Dictionary class that Microsoft provide for us.
Dim myStudents As New Dictionary
Now we create our dictionary. This will hold all the students object that we created. To do this,
myStudents.Add myStudent.StudentID, myStudentmyStudents.Add myStudent2.StudentID, myStudent2
or we can loop through each objectsDim myStudent3 As New Student
Set myStudent3 = myStudents.Item(1)
For Each mystudent4 In myStudents.Items
MsgBox mystudent4.FirstName
Next