在 VBA (Excel 2007) 中关闭表单时执行代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3511903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute code when form is closed in VBA (Excel 2007)
提问by Pixotic
I would like to execute some code when a user closes a form using the x button in the top right corner of the window (I have the form load when the excel spreadsheet is opened, and it hides Excel. I want to exit excel once the form is closed, or at least show excel again so the user may exit it manually)
当用户使用窗口右上角的 x 按钮关闭表单时,我想执行一些代码(我在打开 excel 电子表格时加载了表单,它隐藏了 Excel。我想退出 excel 一次表单已关闭,或至少再次显示 excel 以便用户可以手动退出)
Looking at the form properties, the Unload property is not present, nor am I able to figure out how to make a function which executes when the form is closed.
查看表单属性, Unload 属性不存在,我也无法弄清楚如何创建在表单关闭时执行的函数。
Unfortunately, coding this in VB is not an option, it must be VBA.
不幸的是,在 VB 中编码不是一种选择,它必须是 VBA。
I'm aware of the code needed to unhide Excel or quit it outright, just not how to tie it to the unload event.
我知道取消隐藏 Excel 或完全退出所需的代码,只是不知道如何将其与卸载事件联系起来。
回答by Pixotic
A colleague was able to provide the answer, including example here for everybody else
一位同事能够提供答案,包括此处为其他人提供的示例
Private Sub userform_terminate()
'Code goes here
End Sub
回答by MRS1367
You can use QueryCloseevent of the UserForm as follows:
您可以使用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
You can also use vbFormControlMenu like this:
您还可以像这样使用 vbFormControlMenu:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
'Your code goes here
End If
End Sub
回答by Michael
You can use Unload Mein VBA to close a form. Just put the code to close Excel immediately following that.
您可以Unload Me在 VBA中使用来关闭表单。只需输入代码即可立即关闭 Excel。
回答by Lotfiction
Private Sub Form_Unload(Cancel As Integer)
Dim msgRes As VbMsgBoxResult
msgRes = MsgBox("Exit form ?", vbYesNo)
If msgRes = vbYes Then
'optional code
ElseIf msgRes = vbNo Then
Cancel = True
End If
End Sub
回答by Jrosado
I was able to prevent the form from closing when the X button was click using the following:
当 X 按钮被单击时,我能够使用以下方法阻止表单关闭:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Cancel = MsgBox("Please confirm cancellation", vbOKCancel + vbQuestion) = vbCancel
End Sub
回答by Daniel
try something like this:-
尝试这样的事情:-
Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) _
Handles Form1.FormClosing
//Code you want to execute
End Sub

