Inatialize or Activate ??

S

samanco

Can anyone tell me the difference betwen the constants :
UserForm.Initialize and UserForm.Activate both seem to offer the same
event handling ?
 
S

Shauna Kelly

Hi

You can see the difference if you do this. Create a form and name it
frmTest. Put a label on it named labTest and a button named cbOK.

Add the following code to the form:
Option Explicit

Public TestString As String

Private Sub cbOK_Click()
TestString = "I clicked the OK button on the form"
Me.Hide
End Sub

Private Sub UserForm_Activate()

Me.labTest.Caption = TestString

MsgBox "Activate" & vbCrLf & "TestString = " & TestString

End Sub

Private Sub UserForm_Initialize()

Me.labTest.Caption = TestString

MsgBox "Initialize" & vbCrLf & "TestString = " & TestString

End Sub




Add the following code to an ordinary module:

Option Explicit

Public Sub TestUserForms()

Dim frm As frmTest

'Create a new instance of the form
Set frm = New frmTest

'Give the form some information
frm.TestString = "Hello world"

'Display the form
frm.Show

'When the user closes the form, you come back here
MsgBox "Back in the main module" _
& vbCrLf & "TestString = " & frm.TestString

'Must always unload a form or it stays
'in memory
Unload frm


End Sub


Now, use F8 to step through the code and all will be revealed.

For the very simplest of forms, it probably doesn't matter whether you use
the Activate or Initialize events, although I'd generally use Initialize. If
you need to set up stuff on your form before it's shown, then use
Initialize. If you have a form that gets hidden and re-activated, and you
want code to run when it's activated, then use the Activate event.

Hope this helps.

Shauna Kelly. Microsoft MVP.
http://www.shaunakelly.com/word
 
T

Tony Strazzeri

I have one small addition to Shauna's excellent and clear advice. That
is If you need to move the position of the form you need to do this in
the activate event because the Form's position properties (.top .left)
arn't defined at Initialize.

Cheers
TonyS.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top