Article ID: 154651
Article Last Modified on 7/1/2004
Option Explicit
Public g_SomeGlobalFlag as integer
Option Explicit
Public SomeFlag as integer
Public Sub Test()
MsgBox "Test was called"
End Sub
Private Sub Class_Initialize()
MsgBox "Class was initialized"
'This Class_Initialize is used to set Class level and
'Global Flags. The former is fine and always works;
'The latter is a Bad idea as we shall see.
SomeFlag = 42
g_SomeGlobalFlag = 451
End Sub
Option Explicit
Private Sub Command1_Click()
Dim oClass As Class1
Set oClass = New Class1
'The following lines display the flags
'Both are set correctly.
Msgbox g_SomeGlobalFlag 'Should be 451
Msgbox oClass.Someflag 'Should be 42
End Sub
Private Sub Command1_Click()
Private Sub Command1_Click()
Dim oClass As New Class1
'The following lines display the flags; the global flag is wrong
'because the object doesn't exist yet!
MsgBox g_someflag 'Should be 451 - Oops !
'When you hit this line, the first thing you see is the message box
'from the Initialize Event, as the object is created by using the
'oClass in code. By the time SomeFlag is evaluated for display in the
'Message Box, Initialize has set the value correctly. Initialize
'always happens before any other event or method call.
MsgBox oClass.SomeFlag
End Sub
'Class module code
Option Explicit
Public NowYouSeeIt As String
Private Sub Class_Initialize()
MsgBox NowYouSeeIt
End Sub
'Form1 code
Private Sub Form_Load()
Dim c1 As New Class1
c1.NowYouSeeIt = "This won't appear in the MsgBox."
End Sub
In other words, Class_Initialize must occur even before a public variable
is set. Therefore, in the example above, the Class_Initialize event is
fired before the value of "NowYouSeeIt" is assigned to the class variable
and the message box comes up with no text in the box.
138065 How to Enforce Initialization of a VB OLE Class Object
129449 Object Created w/ NEW Instantiated When Passed as Argument
Additional query words: kbVBp400 kbVBp500 kbVBp600 kbVBp kbdsd kbDSupport
Keywords: kbhowto KB154651