Friday, February 25, 2011

How To Create Class in VB6

So how do we create a class in VB6?
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.
Select our class and rename it to Student

Open the class and type the following code
Option Explicit

Private c_StudentID As Integer
Private c_FirstName As String

Public Property Get StudentID() As Integer
    StudentID = c_StudentID
End Property

Public Property Let StudentID(ByVal args As Integer)
    c_StudentID = args
End Property


Public Property Get FirstName() As String
    FirstName = c_FirstName
End Property

Public Property Let FirstName(ByVal args As String)
    c_FirstName = args
End 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


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.. 
Public Property Get StudentID() As Integer
    StudentID = c_StudentID
End Property
This Property will Get the data that we put on the c_StudentID variable. 
Public Property Let StudentID(ByVal args As Integer)
    c_StudentID = args
End Property
While this code Set the value that we pass [args] to c_StudentID.

How to Instantiate Our Objects
Dim myStudent As New Student
Dim myStudent2 As New Student
How do we set values for our properties?

myStudent.FirstName = "Cawi"
myStudent.StudentID = 1 
myStudent.FirstName = "Cornelio"
myStudent.StudentID = 2
How to put our objects in a collection
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, myStudent
myStudents.Add myStudent2.StudentID, myStudent2
To access them:
Dim myStudent3 As New Student
Set myStudent3 = myStudents.Item(1)
or we can loop through each objects
 For Each mystudent4 In myStudents.Items
    MsgBox mystudent4.FirstName
Next