如果有人点击右上角的红色x,我试图关闭UserForm。到目前为止,这是我的代码。
Public Sub Worksheet_BeforeDoubleClick(ByVal target As Range, Cancel As Boolean)
If target.Column = 10 Then
UserForm2.Show
etc...
现在,表单打开,我运行此代码......
Public Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
If Not ExitAsk = vbYes Then Cancel = True
End If
End Sub
Public Function ExitAsk() As VbMsgBoxResult
Dim Smsg As String
Smsg = "Are you really want to exit? Click Yes to terminate or No to Continue."
ExitAsk = MsgBox(Smsg, vbYesNo + vbDefaultButton2 + vbQuestion, "Exit!")
End Function
然后,焦点返回到Sub,代码继续贯穿所有内容,这会给我带来一些问题。我想单击红色x并关闭UserForm并退出Sub。似乎Sub和UserForm没有进行通信,即使两者都被声明为Public。我必须遗漏一些简单的东西,但我不确定是什么。任何想法,任何人?
谢谢!
答案 0 :(得分:8)
看起来Sub和UserForm不通信,即使两者都被声明为公共
辅助功能与过程是否与表单进行通信无关。表单是一个对象,与Range
或Collection
没有什么不同 - 除了它有一个设计器和一个默认实例:它赢了没有你告诉它如何做到这一点,“与”你的程序进行沟通。
首先,停止使用默认实例并像处理任何其他对象一样处理表单:New
它!
With New UserForm2 'object instance starts existing here...
.Show 'vbModal is implicit
End With '...and dies here
现在,如果您希望调用代码知道 表单是如何关闭的,那么您需要公开调用代码可以访问的某些以了解该内容。
最好用属性完成。您还可以公开一个公共字段,但是调用代码将能够篡改并且您不希望 - 这就是封装所做的:
Private isCancelled As Boolean
Public Property Get Cancelled() As Boolean
Cancelled = isCancelled
End Property
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
isCancelled = True
End If
Cancel = True
Me.Hide
End Sub
注意Cancel = True
和Me.Hide
:在不取消关闭的情况下,对象会立即被销毁并且您将失去其状态。所以你想要Hide
表单而不是卸载/销毁它。
只有表单的代码隐藏可以访问isCancelled
,但调用代码可以读取Cancelled
属性(但不能写入它)。
With New UserForm2 'object instance starts existing here...
.Show vbModal 'execution in this procedure will resume after form is closed
If .Cancelled Then
'form was X'd out
End If
End With '...and dies here
所以...不确定你想要达到的目标,但是你会想要这些内容。
答案 1 :(得分:3)
在UserForm
中,您可以定义自己的public
Get-property,例如CloseModeInfo
,它将返回私有成员的值,可以在UserForm_QueryClose
中设置。之后可以测试该公共财产的价值。根据此属性中的值,调用代码将决定要执行的操作。 HTH
用户窗体
Private m_closeModeInfo As Integer
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
m_closeModeInfo = CloseMode
If CloseMode = vbFormControlMenu Then
If Not ExitAsk = vbYes Then Cancel = True
End If
End Sub
Private Function ExitAsk() As VbMsgBoxResult
Dim Smsg As String
Smsg = "Are you really want to exit? Click Yes to terminate or No to Continue."
ExitAsk = MsgBox(Smsg, vbYesNo + vbDefaultButton2 + vbQuestion, "Exit!")
End Function
Public Property Get CloseModeInfo() As Integer
CloseModeInfo = m_closeModeInfo
End Property
工作表代码
Private Sub Worksheet_BeforeDoubleClick(ByVal target As Range, Cancel As Boolean)
If target.Column = 10 Then
Dim frm As UserForm2
Set frm = New UserForm2
UserForm2.Show
If frm.CloseModeInfo = vbFormControlMenu Then
Unload frm
' I want to click the red x and close the UserForm and exit the Sub:
Exit Sub
End If
End If
End Sub