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

时间:2013-04-04 10:46:14

标签: 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

3 个答案:

答案 0 :(得分:6)

在这种情况下,请勿使用UserForm_QueryClose。使用API​​ RemoveMenuGetSystemMenuFindWindow

This是我最喜欢的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

<强>截图

enter image description here

答案 1 :(得分:2)

不是给用户一条消息说他不能点击红色x,而是按照你的方式捕获它,并在卸载表单之前进行清理:

Sub UserForm_QueryClose(Cancel As Integer, ClsoeMode As Integer)
    If CloseMode = vbFormControlMenu Then
        ' run cleanup code here
    End If
End Sub

如果表单有一个关闭按钮来执行清理,那么请使用以下内容:

Sub UserForm_QueryClose(Cancel As Integer, ClsoeMode As Integer)
    If CloseMode = vbFormControlMenu Then
        ' click event code for Close button:
        btnClose_Click 
        Cancel = True
    End If
End Sub

无需过度使用Windows API,因为这都是内置的。

答案 2 :(得分:1)

我知道这是一个旧的Feed,但你拼写错误ClsoeMode。只需将其更改为CloseMode即可解决您的问题。