禁用VBA UserForm'x',但仍允许卸载我
我有一个用户表单,closures时需要运行清理步骤。 我想为X
button被禁用和/或不可见,但我仍然需要能够卸载的forms。 我已经使用下面的代码,但是它也阻止了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
在这种情况下不要使用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
截图 :
而不是给用户一个消息,说他不能点击红色的x,按照你所做的方式进行陷阱,并在卸载表单之前进行清理:
Sub UserForm_QueryClose(Cancel As Integer, ClsoeMode As Integer) If CloseMode = vbFormControlMenu Then ' run cleanup code here End If End Sub
如果表单有一个closuresbutton来执行清理,那么使用如下所示:
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。
我知道这是一个老饲料,但你拼写ClsoeMode
错了。 只需将其更改为CloseMode
解决您的问题。