实例化表单对象

时间:2016-07-16 06:58:58

标签: forms class ms-access events access-vba

如何为手动实例化的表单对象捕获 onClose onUnload 事件?

我注意到,如果(在我的控制器类中),我使用 WithEvents 关键字标注 Access.Textbox Access.CommandButton 对象,然后Access VBA IDE将自动在代码窗口上方的组合框中显示该对象及其可用事件。

但是,如果我使用WithEvents关键字标注表单对象或自定义表单对象,则不会列出任何对象或可用事件。

Form_Popup_Credentials(表格代码):

Public Event CustomUnLoad()

Private Sub Form_Unload(Cancel As Integer)
  RaiseEvent CustomUnLoad
End Sub

FormController类:

Dim WithEvents Loginfrm As Form_Popup_Credentials
Dim WithEvents Loginbtn As Access.CommandButton

Public Sub GetCredentials()
  ' If the Popup Credential form is not instantiated,
  ' then bring it into existence
  If Loginfrm Is Nothing Then
    Set Loginfrm = New Form_Popup_Credentials
  End If

  ' Set up a reference to the "Login" button
  Set Loginbtn = Loginfrm.SignInButton

  ' Set up the Login Button Click() event
  Loginbtn.OnClick = "[Event Procedure]"

  ' Set up the Login Form's events
  Loginfrm.OnUnload = "[Event Procedure]"
  Loginfrm.OnClose = "[Event Procedure]"

  ' Show the form and give it focus
  Loginfrm.Visible = True
  Loginfrm.SetFocus
End Sub

' Fires Correctly
Private Sub Loginbtn_Click()
  MsgBox "Login Button was Clicked"

  ' If I uncomment this, then the CustomUnLoad() event fires
  ' DoCmd.Close acForm, Loginfrm.Name, acSavePrompt

  Set Loginbtn = Nothing
  Set Loginfrm = Nothing
End Sub

' Doesn't Fire
Private Sub Loginfrm_onClose()
  MsgBox "Login Form onClose() fired"
  Set Loginfrm = Nothing
  Set Loginbtn = Nothing
End Sub

' Doesn't Fire
Private Sub Loginfrm_Close()
  MsgBox "Login Form Close() fired"
  Set Loginfrm = Nothing
  Set Loginbtn = Nothing
End Sub

' Doesn't Fire
Private Sub Loginfrm_onUnload()
  MsgBox "Login Form onUnload() fired"
  Set Loginfrm = Nothing
  Set Loginbtn = Nothing
End Sub

' Doesn't Fire
Private Sub Loginfrm_Unload()
  MsgBox "Login Form Unload() fired"
  Set Loginfrm = Nothing
  Set Loginbtn = Nothing
End Sub

' This fires if the user clicks the X button to close the form,
' but not if the controller unloads the Loginfrm object
Private Sub Loginfrm_CustomUnLoad()
  MsgBox "Login Form CustomUnLoad() fired"
  Set Loginfrm = Nothing
  Set Loginbtn = Nothing
End Sub

1 个答案:

答案 0 :(得分:1)

您必须将类级别表单变量声明为Form(或更明确Access.Form)才能获取Access表单的标准事件:

Dim WithEvents Loginfrm As Access.Form

BTW,取决于Access版本,确保将控制器类中的引用设置为Nothing上的Class_Terminate至关重要。