Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserForm Close Event

Tags:

vba

userform

I have a UserForm which is opened and closed in a loop while a condition exists. The users can click several buttons which performs an action. The problem is the unpredictability of users. One of those problems is, users, instead of clicking one of the buttons, clicking the close window button on top of the UserForm which progresses the loop without performing an action.

--- edit---
Is there an event with that button with which I can execute code so that I can let it perform the same action as the cancel button on the form itself. I do not need to hide or disable it per se.

like image 404
SilentRevolution Avatar asked Jan 01 '16 13:01

SilentRevolution


People also ask

How do I close a UserForm?

We can also close UserForm using the “Hide” method in VBA. Once again, we will double-click the “Cancel” button to see the private subprocedure. Since we have already written the code to close the UserForm, we can see the existing code in VBA.

What does unload UserForm do?

Removes an object from memory.

When a UserForm gets ready which event is fired?

The userform is loaded by button on spreadsheet clicked (not an active-x button if that's relevant).


2 Answers

For example, you can add the macro below to the UserForms code module:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = vbFormControlMenu Then
        Cancel = True
        MsgBox "You can't close the dialog like this!"
    End If
End Sub
like image 180
Sam Gilbert Avatar answered Sep 20 '22 15:09

Sam Gilbert


Instead of a MsgBox, you can just focus a button:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = vbFormControlMenu Then
        Cancel = True
        Me.Close_Button.SetFocus
    End If
End Sub

EDITED: I discovered a better option:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)

    ' YOUR CODE HERE (Just copy whatever the close button does)

    If CloseMode = vbFormControlMenu Then
        Cancel = False
    End If

End Sub
like image 31
André Oliveira Avatar answered Sep 17 '22 15:09

André Oliveira