Userform Queryclose and Unload problem

D

Dave Ramage

Hello!

I have a user form with a single Cancel button on it. The code behind the
form is as follows:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
''' Redirect all non-code form closes through the Cancel button procedure.
If CloseMode <> vbFormCode Then
Cancel = True
Command_Cancel_Click
End If
End Sub

Private Sub Command_Cancel_Click()
gbCancel = True 'global flag
Me.Hide
Unload Me
End Sub

Private Sub UserForm_Initialize()
MsgBox "Initialize"
End Sub

Private Sub UserForm_Terminate()
MsgBox "Terminate"
End Sub

If the user clicks the Cancel button, the Command_Cancel sub runs and the
userform is unloaded and the UserForm_Terminate event fires. Next time the
form is displayed with:
Load Userform1
Userform1.Show
then the UserForm_Initialize event fires as expected.

If the user closes the form with the close button (top right cross), the
Userform_QueryClose event captures this and redirects to the
Command_Cancel_Click sub. This all works fine, however the userform never
gets unloaded this way- even though the Unload Me line gets run, the
_Terminate event doesn't run, and next time there is a
Load Userform1
Userform1.Show
then the _Initialise event does not run as the form is already loaded.

Can anyone tell me why there is this difference in behaviour between closing
with the Cancel button, and closing with form's close button?

Thanks,
Dave
 
V

Vergel Adriano

Dave,

You don't need this line:

Cancel = True

Because you set Cancel=True the form doesn't unload when you close it with
the cross button.
 
J

Jon Peltier

Dave -

Not sure if this is it, but I use this IF in the QueryClose procedure:

If CloseMode = vbFormControlMenu Then

- Jon
 
D

Dave Ramage

Thanks Vergel, removing this solves the problem.

Vergel Adriano said:
Dave,

You don't need this line:

Cancel = True

Because you set Cancel=True the form doesn't unload when you close it with
the cross button.
 

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