Article ID: 160012
Article Last Modified on 1/19/2007
Private This_ClassID As String
Private This_frm As New Form_frmTest
Private Sub Class_Initialize()
On Local Error GoTo Class_Initialize_Err
Dim Msg As String
This_frm.Visible = True
This_ClassID = "Initialized"
This_frm.Caption = This_ClassID
MsgBox "Class Initialized", vbInformation, "Class Example"
Class_Initialize_End:
Exit Sub
Class_Initialize_Err:
Msg = "Error #: " & Format$(Err.Number) & vbCrLf
Msg = Msg & Err.Description
Err.Raise vbObjectError, "clsTest.Initialize (Private)", Msg
Resume Class_Initialize_End
End Sub
Public Property Get ClassID() As Variant
ClassID = This_ClassID
End Property
Public Property Let ClassID(ByVal vNewValue As Variant)
This_ClassID = vNewValue
This_frm.ClassID = This_ClassID
This_frm.Caption = This_ClassID
End Property
Form: frmTest
-----------------
Caption: TestForm
Dim This_ClassID As String
Private Sub Form_Unload(Cancel As Integer)
col.Remove This_ClassID
End Sub
Public Property Get ClassID() As String
ClassID = This_ClassID
End Property
Public Property Let ClassID(ByVal vNewValue As String)
This_ClassID = vNewValue
End Property
Public col As New Collection
Function CreateClassTest() As String
' Create an instance of the clsTest class module, which creates
' an instance of the frmTest form.
Dim cls As New clsTest
' Create a unique identifier string and set it to the upper index
' of the Public col Collection plus one.
Dim varClassId As String
varClassId = "Key_" & CStr(col.Count + 1)
' Set the clsTest class module's ClassID property to the value of
' varClassId, which in turn sets the frmTest.ClassId property to
' the same value. This is so the form has a method to track its
' relationship to the collection.
cls.ClassID = varClassId
' Add the instance of the class object to the collection passing
' varClassId as the Key argument.
col.Add cls, varClassId
MsgBox "Created New Collection Item: " & varClassId, _
vbInformation, "Class Example"
' Unload the cls object variable.
Set cls = Nothing
' Return the varClassId.
CreateClassTest = varClassId
End Function
Function CreateThreeItems() As Boolean
Dim strKeys(1 To 3) As String
Dim i As Integer
For i = LBound(strKeys) To UBound(strKeys)
strKeys(i) = CreateClassTest()
Next i
For i = LBound(strKeys) To UBound(strKeys)
MsgBox col.Item(strKeys(i)).ClassID, vbInformation, _
"Class Test"
Next i
End Function
?CreateThreeItems()
Note that messages boxes are displayed each time the clsTest class
module initializes, when each of three instances of the frmTest form is
created, and again after all three instances of the form are open.Keywords: kbhowto kbprogramming KB160012