我试图从非模式用户表单中引发事件。我的出发点是this excellent example。当我显示表单无模式时,引发事件的代码将执行,但事件处理程序永远不会运行(单击Cancel按钮时不会得到预期的MsgBox )。当我显示表单modal时,事件是按需要处理的,但表单不再是所需的无模式的。
名为FormWithEvents的userform有一个OKButton和一个CancelButton;下面是代码:
Option Explicit
Public Event FormConfirmed()
Public Event FormCancelled(ByRef Cancel As Boolean)
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下面是显示表单的Presenter类的代码:
Option Explicit
Private WithEvents myModelessForm As FormWithEvents
Public Sub Show()
Set myModelessForm = New FormWithEvents
' COMMENT OUT ONE OF THE FOLLOWING TWO LINES TO TOGGLE MODELESS OR MODAL
myModelessForm.Show vbModeless ' Modeless, but events don't get handled (no msgbox on clicking cancel button)
' myModelessForm.Show vbModal ' Events get handled, but no longer modal
End Sub
Private Sub myModelessForm_FormCancelled(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下面是主模块中的代码:
Option Explicit
Public Sub RunForm()
With New Presenter
.Show
End With
End Sub对我哪里出了问题有什么想法吗?
发布于 2020-03-14 22:58:54
可能是这样做的,这样您就可以将Presenter实例保持在范围内:
Dim pres as Presenter
Public Sub RunForm()
Set pres = New Presenter
pres.Show
End Sub发布于 2020-03-15 02:18:58
避免使用RaiseEvent。在标准模块中声明Presenter类的公共实例。选项显式
Public Preter As New Presenter
Public Sub RunForm()
With New Presenter
.Show
End With
End Sub将事件过程转换为具有公共范围的子程序。
Sub FormCancelled(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 Function OnCancel() As Boolean
Dim cancelCancellation As Boolean
Preter.FormCancelled cancelCancellation
If Not cancelCancellation Then Me.Hide
OnCancel = cancelCancellation
End Function我不确定,但是类模块中的代码行Set myModelessForm = Nothing让我很困扰。我想知道是否应该隐藏表单,这样代码就可以继续到Show过程中,然后表单就可以停止了。
https://stackoverflow.com/questions/60687441
复制相似问题