VBA-正确销毁无模式的UserForm实例 [英] VBA - destroy a modeless UserForm instance properly

查看:74
本文介绍了VBA-正确销毁无模式的UserForm实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介:

我知道-显示用户窗体-最佳实践

I am aware that - showing UserForms - it's best practice to

  • 在用户表单代码(If CloseMode = vbFormControlMenu ...)中处理QueryClose
  • 其中没有Unload Me,只是胆小的Me.Hide指令 (在通过[c4>防止[x]上陷和最终自我毁灭之后)
  • 在[class]代码(例如.IsCancelled=True)中设置相关变量/[属性]
  • 以便能够通过呼叫代码卸载UF.
  • handle QueryClose within the userform code (If CloseMode = vbFormControlMenu ...)
  • doing no Unload Me therein, just a timid Me.Hide instruction (after preventing [x]-itting and eventual self-destruction via Cancel = True )
  • setting a related variable/[property] within the [class] code (e.g. .IsCancelled=True)
  • in order to be able to have the UF unloaded by the calling code.

有用的链接

出色的概述"UserForm1.Show?" 可在 https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/ 以及许多示例性的SO答案(Mathieu Guindon又名"Mat's Mug "和"RubberDuck").

An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/ as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).

更多选择(►截至5/1 2019的编辑)

  • Disadvantages in putting code into userforms instead of modules
  • Passing variable from form to module
  • Apply logic for userform dialog (Rubberduck)
  • The perfect userform (Vitosh academy)

1)模态用户窗体的工作示例

据我了解-并且我确实尝试学习-,以下代码对于UF的 modal 来说应该可以:

As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:

案例1a) ..对于UF实例具有局部变量,如常看到的那样:

Case 1a) .. with a local variable for the UF instance, as often seen:

Public Sub ShowFormA
  Dim ufA As UserForm1
  Set ufA = New UserForm1
' show userform 
  ufA.Show          ' equivalent to: ufA.Show vbModal

' handle data after user okay
  If Not ufA.IsCancelled Then
      '  do something ...
  End If

' >> object reference destroyed expressly (as seen in some examples)
  unload ufA
End Sub

案例1b) ..没有局部变量,但使用了With New代码块:

Case 1b) .. without a local variable, but using a With New codeblock:

' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
'    as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
  With New UserForm1
      .Show         ' equivalent to: ufA.Show vbModal

    ' handle data after user okay
      If Not .IsCancelled Then
      '  do something ...
      End If
  End With


2)问题

使用 MODELESS UserForm实例出现问题.

Problems arise using a MODELESS UserForm instance.

好的,with块方法(参见1b)应该足以在对它进行x-it之后销毁任何对象引用:

Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:

  With New UserForm1
      .Show vbModeless  ' << show modeless uf
  End With

如果我尝试的话

  • a)获取有关可能的用户取消以及
  • 的信息
  • b)到Unload一种形式,如果在Show指令后使用局部变量(例如"ufA")进行洗礼,
  • a) get information about a possible user cancelling as well as
  • b) to Unload a form if baptized using a local variable (e.g. "ufA") after the Show instruction,

所有代码行都将立即执行,原因恰恰是表格为MODELESS:

all code lines will be executed at once for precisely the reason that the form is MODELESS:

  • 代码显示表单,下一刻..
  • 代码找不到用户取消,因为没有时间在下一个时刻进行任何用户操作.
  • [如果用户表单使用本地变量,代码将卸载表单]

3)问题

我该如何处理a)通过MODELESS表单的调用代码正确报告的UserForm取消,以及b)如果使用局部变量,则要卸载(必要吗?)?

How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?

推荐答案

实际上,我一直非常关注模式形式-因为这是最常用的形式.感谢您对该文章的反馈!

Indeed, I've been focusing quite a lot on modal forms - because that's what's most commonly used. Thanks for the feedback on that article!

但是,非模态形式的原理是相同的:只需在链接的文章和Model-View-Presenter 模式上进行扩展. com/a/47291028/1188513>此处.

The principles are the same for non-modal forms though: simply expand on the Model-View-Presenter pattern roughly outlined in the linked article and here.

区别在于,非模态形式需要进行范式转换:您不再响应预设的事件序列-而是需要响应可能发生的一些异步事件在任何给定时间都可以.

The difference is that a non-modal form needs a paradigm shift: you're no longer responding to a preset sequence of events - rather, you need to respond to some asynchronous events that may happen at any given time, or not.

  • 在处理模式表单时,先存在显示前",然后有隐藏后",在隐藏表单后立即运行.您可以使用事件来处理显示时"发生的任何事情.
  • 在处理非模式形式时,需要先通过事件处理,然后再进行显示前",显示时"和显示后".

让您的演示者类模块负责在模块级别和WithEvents处保存UserForm实例:

Make your presenter class module responsible for holding the UserForm instance, at module-level and WithEvents:

Option Explicit
Private WithEvents myModelessForm As UserForm1

演示者的Show方法将Set表单实例并显示:

The presenter's Show method will Set the form instance and display it:

Public Sub Show()
    'If Not myModelessForm Is Nothing Then
    '    myModelessForm.Visible = True 'just to ensure visibility & honor the .Show call
    '    Exit Sub
    'End If
    Set myModelessForm = New UserForm1
    '...
    myModelessForm.Show vbModeless
End Sub

希望表单实例在此过程中是本地的,因此本地变量 With块不起作用:对象将超出您的预期范围.这就是为什么将实例存储在模块级别的私有字段中的原因:现在,表单的存在时间与presenter实例的寿命一样.

You don't want the form instance to be local to the procedure here, so a local variable or a With block can't work: the object will be out of scope before you mean it to. That's why you store the instance in a private field, at module level: now the form lives as long as the presenter instance does.

现在,您需要与演示者进行交谈"形式-最简单的方法是在UserForm1代码隐藏中显示事件-例如,如果我们希望用户确认取消,我们将添加一个ByRef事件的参数,因此演示者中的处理程序可以将信息传递回事件源(即,返回到表单代码):

Now, you need to make the form "talk" to the presenter - the easiest way is to expose events in the UserForm1 code-behind - for example if we want the user to confirm cancellation, we'll add a ByRef parameter to the event, so the handler in the presenter can pass the information back to the event source (i.e. back to the form code):

Option Explicit
'...private fields, model, etc...
Public Event FormConfirmed()
Public Event FormCancelled(ByRef Cancel as Boolean)

'returns True if cancellation was cancelled by handler
Private Function OnCancel() As Boolean
    Dim cancelCancellation As Boolean
    RaiseEvent FormCancelled(cancelCancellation)
    If Not cancelCancellation Then Me.Hide
    OnCancel = cancelCancellation
End Function

Private Sub CancelButton_Click()
    OnCancel
End Sub

Private Sub OkButton_Click()
    Me.Hide
    RaiseEvent FormConfirmed
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = Not OnCancel
    End If
End Sub

现在演示者可以处理该FormCancelled事件:

Now the presenter can handle that FormCancelled event:

Private Sub myModelessForm_FormCancelled(ByRef Cancel As Boolean)
    'setting Cancel to True will leave the form open
    Cancel = MsgBox("Cancel this operation?", vbYesNo + vbExclamation) = vbNo
    If Not Cancel Then
        ' modeless form was cancelled and is now hidden.
        ' ...
        Set myModelessForm = Nothing
    End If
End Sub

Private Sub myModelessForm_FormConfirmed()
    'form was okayed and is now hidden.
    '...
    Set myModelessForm = Nothing
End Sub

非模态表单通常不会 具有确定"和取消"按钮.相反,您将拥有许多功能,例如,其中一个功能会弹出一个模态对话框UserForm2,它会执行其他操作-再次,您只公开一个事件,并在演示者中处理它:

A non-modal form wouldn't typically have "ok" and "cancel" buttons though. Rather, you'd have a number of functionalities exposed, for example one that brings up some modal dialog UserForm2 that does something else - again, you just expose an event for it, and handle it in the presenter:

Public Event ShowGizmo()

Private Sub ShowGizmoButton_Click()
    RaiseEvent ShowGizmo
End Sub

演示者去:

Private Sub myModelessForm_ShowGizmo()
    With New GizmoPresenter
        .Show
    End With
End Sub

请注意,模式UserForm2是单独的演示者类的关注点.

Note that the modal UserForm2 is a concern of a separate presenter class.

这篇关于VBA-正确销毁无模式的UserForm实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆