Creating and Using a Class Module : Class « Data Type Functions « VBA / Excel / Access / Word






Creating and Using a Class Module

 

'Class Module: Employee
Public FirstName As String
Public LastName As String
Public Function Speak()
     Speak = FirstName & " " & LastName
End Function
'test Module
Sub SingleInstance()
    Dim oPerson As Employee
    Set oPerson = New Employee

    oPerson.FirstName = "A"
    oPerson.LastName = "Balter"

    msgBox oPerson.Speak
End Sub

''Property Let and Get Adding Properties the Right Way
Private mstrFirstName As String
Private mstrLastName As String
Public Property Get FirstName() As String
    FirstName = mstrFirstName
End Property

Public Property Let FirstName(ByVal strNewValue As String)
    mstrFirstName = UCase(strNewValue)
End Property

Public Property Get LastName() As String
    LastName = mstrLastName
End Property

Public Property Let LastName(ByVal strNewValue As String)
    mstrLastName = UCase(strNewValue)
End Property

'Setting Values with Property Set
Private mobjCustomer As Employee

Public Property Set GoodEmployee(objCustomer As Employee)
     Set mobjCustomer = objCustomer
End Property
'Class Module: Employee
Public FirstName As String
Public LastName As String
Public Function Speak()
     Speak = FirstName & " " & LastName
End Function
'test Module
Sub SingleInstance()
    Dim oPerson As Employee
    Set oPerson = New Employee

    oPerson.FirstName = "A"
    oPerson.LastName = "Balter"

    msgBox oPerson.Speak
End Sub
'Creating Multiple Class Instances
Sub MultipleInstance()
    Dim oPerson1 As Employee
    Dim oPerson2 As Employee

    Set oPerson1 = New Employee
    Set oPerson2 = New Employee

    oPerson1.FirstName = "A"
    oPerson1.LastName = "B"

    Debug.Print oPerson1.Speak

    oPerson2.FirstName = "Dan"
    oPerson2.LastName = "B"

    Debug.Print oPerson2.Speak

End Sub
'Define Class Initialize event method and Terminate event method
Public FirstName As String
Public LastName As String
Public Function Speak()
     Speak = FirstName & " " & LastName
End Function


'test Module
Sub SingleInstance()
    Dim oPerson As Employee
    Set oPerson = New Employee

    oPerson.FirstName = "A"
    oPerson.LastName = "Balter"

    msgBox oPerson.Speak
End Sub

'Use the Initialize event to perform tasks such as establishing a connection to a database and initializing variables.
Private Sub Class_Initialize()
    FirstName = "A"
    LastName = "Balter"
End Sub
'You generally use the Terminate event to perform the class's cleanup tasks.
Private Sub Class_Terminate()
    rstCustomer.Close
    Set rstCustomer = Nothing
End Sub

 








Related examples in the same category

1.Creating Custom Objects
2.Class Module: FileInformation
3.Class Module: FullName
4.The SimpleLoan Class
5.Loan Object Implementation Details
6.Rectangle class
7.Creating the MyRectangle Class
8.Abstraction