VBA:WithEvents 谜题

2024-01-04

我有一个用户表单,xForm,正在类模块中实例化(假设测试类) as:

'TestClass
Dim Form as New xForm
Private WithEvents EvForm as MSForms.UserForm
Set EvForm = Form

在 xForm 本身的类模块中,我有一些必须在表单关闭时执行的代码,仅当表单实际关闭时:

'xForm class module
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    'Do some cleanup, otherwise the app would hang
    'If not closing, don't cleanup anything, otherwise the app would hang
End Sub

QueryClose 事件也在 TestClass 中处理,并且可以避免表单关闭:

'TestClass
Private Sub EvForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    'Verify if closing is allowed based on User Control values
    Cancel = Not ClosingIsAllowed '<-- Pseudocode on the right side of "="
End Sub

如何测试在 xForm 类模块中的 TestClass 中设置的 Cancel = True? 让我们重新表述一下:如果 TestClass 中的 Cancel 设置为 True,则我不能在 xForm 类模块中执行清理代码。我怎样才能做到这一点?

到目前为止,我一直在考虑在 xForm 类中实现另一个事件(My_QueryClose?)并在 QueryClose 事件上引发它。在代码隐藏表单之外,我将只处理 My_QueryClose 事件,因此可以完全控制正在发生的事情。这是一种可行/更好的方法吗?


无法弄清楚您的自定义事件想法,但让一个班级与另一个班级交谈(形式或其他任何东西,并不重要)的方法是将它们链接起来;这是一个干净的例子:

基本 TestClass 保存表单对象(这里不需要事件,让表单处理)

'TestClass code
Private MyForm          As UserForm
Private mbleCanClose    As Boolean

Public Property Get CanClose() As Boolean
    CanClose = mbleCanClose
End Property
Public Property Let CanClose(pbleCanClose As Boolean)
    mbleCanClose = pbleCanClose
End Property

Public Property Get MyFormProp() As UserForm1
    Set MyFormProp = MyForm
End Property

将自定义对象和属性添加到表单本身

'UserForm1 code
Private mParent As TestClass

Public Property Get Parent() As TestClass
    Set Parent = mParent
End Property
Public Property Set Parent(pParent As TestClass)
    Set mParent = pParent
End Property

在创建 TestClass 时调用表单如下所示:

'TestClass code
Private Sub Class_Initialize()
    Set MyForm = New UserForm1
    Load MyForm
    Set MyForm.Parent = Me
End Sub

然后,当需要关闭表单时,您检查是否可以:

'UserForm1 code
Public Function WillMyParentLetMeClose() As Boolean
    If Not (mParent Is Nothing) Then
        WillMyParentLetMeClose = mParent.CanClose
    End If
End Function

Private Sub CommandButton1_Click()
    If WillMyParentLetMeClose = True Then
        Unload Me
    End If
End Sub

这是它想要调用的内容

'standard module code
Public Sub Test_TestClass()
    Dim myclass As TestClass
    Set myclass = New TestClass
    myclass.MyFormProp.Show
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VBA:WithEvents 谜题 的相关文章

随机推荐