UserForm mystery

P

Patrick C. Simonds

Within the UserForm2 Initialization routine I have the following code:

If ActiveDocument.CheckBox7.Value = True Then
OptionButton1.Value = True


Also within UserForm2 I have the following code:

Private Sub OptionButton1_Click()

If OptionButton1.Value = True Then
UserForm24.Show
End If

End Sub


Can anyone tell me
1. Why does the code in the UserForm Initialization routine causes
UserForm24 to open?
2. How can I stop it from doing so?
 
J

Jay Freedman

Within the UserForm2 Initialization routine I have the following code:

If ActiveDocument.CheckBox7.Value = True Then
OptionButton1.Value = True


Also within UserForm2 I have the following code:

Private Sub OptionButton1_Click()

If OptionButton1.Value = True Then
UserForm24.Show
End If

End Sub


Can anyone tell me
1. Why does the code in the UserForm Initialization routine causes
UserForm24 to open?
2. How can I stop it from doing so?

Any time you change the value of the option button programmatically,
it will fire the option button's click event, just as if the user had
done it. There's no way to prevent that, so you must do something to
make the Click procedure suppress its action when it isn't wanted.

There may be better ways, but one is to have a Boolean variable that
is a member of the UserForm (that is, declared at the top of the code
outside any procedure) to indicate the current state of the UserForm.
In the following example, the variable bActive is set to False in the
Initialize procedure (although that's redundant, because it defaults
to False when it's declared). It remains False until the Activate
procedure sets it to True; the Activate event occurs immediately
before the form appears on screen. The Deactivate procedure sets the
variable back to False, in case this UserForm will be hidden and shown
again; that's probably also not necessary.

Private bActive As Boolean

Private Sub UserForm_Initialize()
bActive = False
If ActiveDocument.CheckBox7.Value = True Then
OptionButton1.Value = True
End If
End Sub

Private Sub UserForm_Activate()
bActive = True
End Sub

Private Sub UserForm_Deactivate()
bActive = False
End Sub

Private Sub OptionButton1_Click()
If bActive And (OptionButton1.Value = True) Then
UserForm24.Show
End If
End Sub

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 
P

Perry

Set the default value of OptionButton1 to true in designtime!

Leave the code as is, and run again.

--
Krgrds,
Perry

System:
Vista/Office Ultimate
VS2005/VSTO2005 SE
 

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