I have a user form that, when closed, needs to run cleanup steps. I would like for the X
button to be disabled and/or not visible, but I still need to be able to unload the form. I've used code like the below, but it also blocks Unload Me
.
'Disables closing via x button
Sub UserForm_QueryClose(Cancel As Integer, ClsoeMode As Integer)
If CloseMode = vbFormControlMenu Then
MsgBox ("BLOCKED")
Cancel = True
End If
End Sub
Do not use the UserForm_QueryClose
in such a case. Use the API RemoveMenu
, GetSystemMenu
and FindWindow
This is my fav site for APIs
RemoveMenu : http://allapi.mentalis.org/apilist/RemoveMenu.shtml
GetSystemMenu : http://allapi.mentalis.org/apilist/GetSystemMenu.shtml
FindWindow : http://allapi.mentalis.org/apilist/FindWindow.shtml
See this example
Option Explicit
Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, _
ByVal wFlags As Long) As Long
Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long
Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Const MF_BYPOSITION = &H400&
Private Sub UserForm_Initialize()
Dim Ret As Long
'~~> Change UserForm1 to match your userform's caption
Ret = FindWindow("ThunderDFrame", "UserForm1")
Do While Ret = 0
'~~> Change UserForm1 to match your userform's caption
Ret = FindWindow("ThunderDFrame", "UserForm1")
DoEvents
Loop
RemoveMenu GetSystemMenu(Ret, 0), 6, MF_BYPOSITION
End Sub
Private Sub CommandButton1_Click()
Unload Me
End Sub
Screenshot: