当用户使用窗口右上角的x按钮关闭表单时,我想执行一些代码(当打开excel电子表格时,我有表单加载,并且它隐藏了Excel。我想要退出表格关闭后excel,或者至少再次显示excel,以便用户可以手动退出)
查看表单属性,Unload属性不存在,我也无法弄清楚如何创建一个在表单关闭时执行的函数。
不幸的是,在VB中编码不是一个选项,它必须是VBA。
我知道取消隐藏Excel或彻底退出Excel所需的代码,而不是如何将其与卸载事件联系起来。
答案 0 :(得分:15)
一位同事能够提供答案,包括其他人的例子
Private Sub userform_terminate()
'Code goes here
End Sub
答案 1 :(得分:13)
您可以使用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
你也可以像这样使用vbFormControlMenu:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
'Your code goes here
End If
End Sub
答案 2 :(得分:1)
您可以在VBA中使用Unload Me
来关闭表单。只需将代码紧随其后关闭Excel即可。
答案 3 :(得分:1)
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
答案 4 :(得分:1)
使用以下内容单击X按钮时,我能够阻止表单关闭:
USE mydatabase
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CreateUser]
@USERNAME AS VARCHAR(MAX) = ''
AS
BEGIN
declare @sql nvarchar(MAX)
If NOT EXISTS(select loginname from master.dbo.syslogins where name = @USERNAME)
BEGIN
set @sql = 'CREATE LOGIN ' + @USERNAME +
' WITH
PASSWORD = ''something'',
CHECK_POLICY = OFF'
exec(@sql)
set @sql = 'ALTER SERVER ROLE sysadmin ADD MEMBER ' + @username
exec(@sql)
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = @USERNAME)
BEGIN
-- Creates a database user for the login created above.
set @sql = 'CREATE USER [' + @USERNAME + '] FOR LOGIN [' + @USERNAME + ']'
exec(@sql)
EXEC sp_addrolemember 'db_owner', @USERNAME
END
END
END
答案 5 :(得分:0)
尝试这样的事情: -
Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) _
Handles Form1.FormClosing
//Code you want to execute
End Sub