A frequently asked question is “How do I hide the red X close button on the corner of a VBA user form?”
My answer is that you shouldn’t hide the red button, since the user knows what it does, or at least what it’s supposed to do. Leave the button in place as an obvious way to escape the running procedure. It’s your job as programmer to make the escape route work both for the user and for the program.
This userform has code behind the OK and Cancel buttons to hide the form, which keeps it resident in memory. This way, the calling code can interact with the form after it has been dismissed.
The default behavior of the red X in the top right corner is to unload the form, that is, clear it from memory. This is not good, because the calling code will be unable to communicate with the form.
This form has code that repurposes the red X, turning a click on that button to a click on the form’s Close button. This is what the user wanted to do anyway.
There are more detailed methods which rely on Windows API calls that will actually disable or hide the red X button, but I don’t like to take away a piece of the interface that the user understands.
The code in the userform is shown below. The variable mbCancel is true if the dialog is dismissed with the Cancel button, or false if it is dismissed with the OK button.
Option Explicit Dim mbCancel As Boolean Private Sub btnCancel_Click() mbCancel = True Me.Hide End Sub Private Sub btnOK_Click() mbCancel = False Me.Hide End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) ' how was the form closed? ' vbFormControlMenu = X in corner of title bar If CloseMode = vbFormControlMenu Then ' cancel normal X button behavior Cancel = True ' run code for click of Cancel button btnCancel_Click End If End Sub