【发布时间】:2015-11-05 21:37:59
【问题描述】:
在 Microsoft Access 2010 中,我尝试动态创建一个表单,然后向其中添加一个命令按钮。但是,我不知道如何将事件处理程序分配给该按钮的单击(或 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 中找不到这个功能?
无论如何,对于这个问题的任何帮助将不胜感激。
谢谢
【问题讨论】: