In Microsoft Access 2010, I am trying to dynamically create a form and then add a commandbutton to it. However, I can't figure out how to assign an event handler to that button's click (or onclick) event?
From reading extracts on the internet, I have created the following vba module code:
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
In accordance with the internet advice, I have then added the following class module (that I've called "CustomButton" and is referred to above):
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
However, when I run this code and then click the button (when in form view) nothing happens?
I notice that explanations given for similar problems, but for excel 2010, give an alternative solution by writing code as a string in a "CodeModule", which I think is linked to the "vbComponents" object. This solution should work for me but I can't find this functionality in Access 2010?
Anyway, any help on this issue would be greatly appreciated.
Thanks