VBA for Access 2010:动态创建控件并链接事件处理程序

时间:2015-11-05 21:38:00

标签: vba ms-access

在Microsoft Access 2010中,我尝试动态创建表单,然后向其添加命令按钮。但是,我无法弄清楚如何为该按钮的click(或onclick)事件分配事件处理程序?

通过阅读互联网上的摘录,我创建了以下vba模块代码:

Option Compare Database
Option Explicit

Public Sub ProduceForm()
  Dim aForm As Form
  Dim aButton As CustomButton
  Set aForm = CreateAForm("Table1")
  Set aButton = CreateAButton(aForm, "Click me!")
  DoCmd.Restore
End Sub

Private Function CreateAForm(table As String) As Form
  Set CreateAForm = CreateForm(, table)
  With CreateAForm
    .Caption = CreateAForm.Name
  End With
End Function

Private Function CreateAButton(aForm As Form, text As String) As CustomButton
  Set CreateAButton = New CustomButton
  Set CreateAButton.btn = CreateControl(aForm.Name, acCommandButton)
  CreateAButton.SetupButton text
End Function

根据互联网建议,我已经添加了以下类模块(我称之为“CustomButton”,并在上面提到):

Option Compare Database

Public WithEvents btn As CommandButton

Public Sub SetupButton(text As String)
 If IsNull(btn) = False Then
    With btn
        .Caption = text
        .OnClick = "[Event Procedure]"
    End With
 End If
End Sub

Public Sub btn_OnClick() ' or should this method just be called btn_Click()?
  MsgBox "Happy days"
End Sub

但是,当我运行此代码然后单击按钮时(在窗体视图中)没有任何反应?

我注意到针对类似问题的解释,但是对于excel 2010,通过在“CodeModule”中将代码编写为字符串来提供替代解决方案,我认为这与“vbComponents”对象相关联。这个解决方案对我有用,但我在Access 2010中找不到这个功能吗?

无论如何,对此问题的任何帮助将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

编辑 - 我的原始答案假设Access的行为与excel类似,但似乎并非如此......

您不需要自定义类来处理事件 - 您只需将字符串传递给按钮的OnClick属性。

这对我有用 - 可能需要整理一下。

Public Sub ProduceForm()
  Dim aForm As Form, strName As String
  Dim btn As CommandButton

  Set aForm = CreateAForm("Table1")

  Set btn = CreateAButton(aForm, "Click me!", "=SayHello()")
  btn.Top = 100
  btn.Left = 100

  Set btn = CreateAButton(aForm, "Click me too!", "=SayHello('World')")
  btn.Top = 1000
  btn.Left = 100

  DoCmd.OpenForm aForm.Name, , , , , acDialog

  DoCmd.Restore
End Sub

Private Function CreateAForm(table As String) As Form
  Set CreateAForm = CreateForm(, table)
  With CreateAForm
    .Caption = CreateAForm.Name
  End With
End Function

Private Function CreateAButton(aForm As Form, txt As String, proc As String) As CommandButton
  Dim btn As CommandButton
  Set btn = CreateControl(aForm.Name, acCommandButton)
  btn.OnClick = proc
  btn.Caption = txt
  Set CreateAButton = btn
End Function

'has to be a Function not a Sub
Public Function SayHello(Optional arg As String = "")
    MsgBox "Hello " & arg
End Function