Is it possible to raise events on a subform's form, when that subform is bound to a table?
It's because the subform object isn't a form having a code module. Thus, nowhere is the event procedure to run.
So, create a form in datasheetview using the table as source, having no code module, and use that as the subform:
- Your code is ignored.
Now, adjust the form to have a code module:
- Your code runs as expected.
Anyway, that's how it works for me in Access 2016.
As Gustav pointed out to me, a form needs a module to raise events.
This means you can't use the auto-created temporary datasheet form. But you can create your own form to take its place.
To work around the limitation, I created a form named frmDynDS, and set it's default view to datasheet view. Then, I opened the form in design view and added 255 text boxes to the form using the following code:
Public Sub DynDsPopulateControls()
Dim i As Long
Dim myCtl As Control
For i = 0 To 254
Set myCtl = Application.CreateControl("frmDynDS", acTextBox, acDetail)
myCtl.Name = "Text" & i
Next i
End Sub
I added a module, and added the following code to dynamically load a table into the form:
Public Sub LoadTable(TableName As String)
Dim fld As DAO.Field
Dim l As Long
Me.RecordSource = TableName
For Each fld In Me.Recordset.Fields
With Me.Controls("Text" & l)
.Properties("DatasheetCaption").Value = fld.Name
.ControlSource = fld.Name
.ColumnHidden = False
.columnWidth = -2
End With
l = l + 1
Next
For l = l To 254
Me.Controls("Text" & l).ColumnHidden = True
Next
End Sub
Then, I could adjust Class1 to the following:
Private WithEvents subformForm As Access.Form
Public Sub Init(subformControl As Access.SubForm, TableName As String)
subformControl.SourceObject = "Form.frmDynDS"
Set subformForm = subformControl.Form
subformForm.LoadTable TableName
subformForm.OnCurrent = "[Event Procedure]"
End Sub
Private Sub subformForm_Current()
MsgBox "Current!"
End Sub
And Form1 to the following:
Private c1 As Class1
Private Sub Form_Load()
Set c1 = New Class1
c1.Init sub1, "Table1"
End Sub
Using this approach, you can have a subform that can display tables created on the fly in datasheet view, and handle events for that subform.
You can have multiple subforms bound to frmDynDS displaying different tables, and handle events in different event handlers, on a single form.