You would use the UserForm's QueryClose event to control that. There are
lots of ways to structure the code you place there; here is a very simple
setup you can use as a guide...
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
If vbYes = MsgBox("Are you sure you want to close me?", vbYesNo) Then
' Perform any code cleanup here before letting the program close
Cancel = False
Else
Cancel = True
End If
End If
End Sub
Look up the QueryClose Event in the help files to see what else you can
check for with the CloseMode parameter. Note that while I put the
Cancel=False statement in, it is not technically needed as that is the
default for the Cancel parameter if not specifically specified (I think
including it makes the code "more complete").
Personally, I wouldn't disable the button as the code to handle the user
pressing the "X" is too easy to implement (see my direct posting to the OP
in this thread) and leaving that option available to the user will make your
interface feel more natural to him/her. You can, of course, provide an
Exit/Close/Quit type button as well, I just would not go out of my way to
disable the "X" in favor of it.
As a user, I like to click on the X button to close any dialog.
If you have special code built into your "Cancel" button, why not just call that
same code.
Option Explicit
Private Sub CommandButton1_Click()
MsgBox "Ok was clicked"
End Sub
Private Sub CommandButton2_Click()
MsgBox "Cancel was clicked"
Unload Me
End Sub
Private Sub UserForm_Initialize()
With Me.CommandButton1
.Caption = "Ok"
.Default = True
End With
With Me.CommandButton2
.Caption = "Cancel"
.Cancel = True
End With
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Call CommandButton2_Click
End If
End Sub
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.