禁用VBA UserForm'x',但仍允许卸载我

ste*_*ris 1 excel vba excel-vba userform

我有一个用户表单,当关闭时,需要运行清理步骤.我希望X禁用该按钮和/或不可见,但我仍然需要能够卸载该表单.我使用了类似下面的代码,但它也阻止了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
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 6

不要UserForm_QueryClose在这种情况下使用.使用API RemoveMenu,GetSystemMenu和FindWindow

这是我最喜欢的API网站

RemoveMenu:http://allapi.mentalis.org/apilist/RemoveMenu.shtml

GetSystemMenu:http://allapi.mentalis.org/apilist/GetSystemMenu.shtml

FindWindow:http://allapi.mentalis.org/apilist/FindWindow.shtml

看这个例子

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
Run Code Online (Sandbox Code Playgroud)

截图:

在此输入图像描述