Table of contents
Collapse the table of content
Expand the table of content

QueryClose Event

office 365 dev account|Last Updated: 6/12/2017
1 Contributor

Occurs before a UserForm closes. SyntaxPrivate Sub UserForm_QueryClose(cancelAs Integer, closemodeAs Integer) The QueryClose event syntax has these parts:

cancelAn integer. Setting this argument to any value other than 0 stops the QueryClose event in all loaded user forms and prevents the UserForm and application from closing.
closemodeA value or constant indicating the cause of the QueryClose event.

Return Values The closemode argument returns the following values:

vbFormControlMenu0The user has chosen the Close command from the Control menu on the UserForm.
vbFormCode1The Unload statement is invoked from code.
vbAppWindows2The current Windows operating environment session is ending.
vbAppTaskManager3The Windows Task Manager is closing the application.

These constants are listed in the Visual Basic for Applications object library in theObject Browser. Note that vbFormMDIForm is also specified in the Object Browser, but is not yet supported. Remarks This event is typically used to make sure there are no unfinished tasks in the user forms included in an application before that application closes. For example, if a user hasn't saved new data in any UserForm, the application can prompt the user to save the data. When an application closes, you can use the QueryClose event procedure to set the Cancel property to True, stopping the closing process.


The following code forces the user to click the UserForm's client area to close it. If the user tries to use the Close box in the title bar, the Cancel parameter is set to a nonzero value, preventing termination. However, if the user has clicked the client area, CloseMode has the value 1 and Unload Me is executed.

Private Sub UserForm_Activate()
    UserForm1.Caption = "You must Click me to kill me!"
End Sub

Private Sub UserForm_Click()
  Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    'Prevent user from closing with the Close box in the title bar.
    If CloseMode <> 1 Then Cancel = 1
    UserForm1.Caption = "The Close box won't work! Click me!"
End Sub
© 2018 Microsoft