在VBA中关闭表单时执行代码(Excel 2007)

Pix*_*tic 13 forms excel vba excel-vba

当用户使用窗口右上角的x按钮关闭表单时,我想执行一些代码(当打开excel电子表格时我有表单加载,并且它隐藏了Excel.我想退出excel一次窗体关闭,或至少再显示excel,以便用户可以手动退出)

查看表单属性,Unload属性不存在,我也无法弄清楚如何创建一个在表单关闭时执行的函数.

不幸的是,在VB中编码不是一个选项,它必须是VBA.

我知道取消隐藏Excel或直接退出所需的代码,而不是如何将其与卸载事件联系起来.

Pix*_*tic 17

一位同事能够提供答案,其中包括其他人的例子

Private Sub userform_terminate()

    'Code goes here

End Sub
Run Code Online (Sandbox Code Playgroud)

  • 请注意,隐藏表单时也会触发此操作。如果您只想捕获右上角的关闭按钮 (x),请使用 MRS1367 的答案! (3认同)

MRS*_*367 14

您可以使用UserForm的QueryClose事件,如下所示:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = 0 Then
        ' Your codes
        ' Tip: If you want to prevent closing UserForm by Close (×) button in the right-top corner of the UserForm, just uncomment the following line:
        ' Cancel = True
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

你也可以像这样使用vbFormControlMenu:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = vbFormControlMenu Then
        'Your code goes here
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 1

您可以在 VBA 中使用Unload Me来关闭窗体。只需紧接着输入关闭​​ Excel 的代码即可。

  • 谢谢,但是当用户单击 x 按钮时,这如何允许我执行代码?可能是我没把问题说清楚,我现在编辑一下。 (2认同)