I am trying to build a userform in real time. (in Excel VBA) Just to try-out, I started with 2 labels, a textbox, a combobox and a commandbutton. I list the code below + the resulting form.
My question is: How can I get events linked to the controls, specifically the combobox and commandbutton? Normally (with manually created forms), this would be done by the routines called: cmbTabel_change() and cmdExit_click(). But this doesn't seem to work, when they are dynamically created. Who can help me?
Code:
Private Sub UserForm_Initialize()
Dim cCont As Control
Call Add_Control(cCont, "Label", "lblDatabase", "Database", 30, 23, 60, 18)
Call Add_Control(cCont, "Textbox", "txtDatabase", "Database", 110, 20, 60, 18)
Call Add_Control(cCont, "Label", "lblTabel", "Tabel", 30, 47, 90, 18)
Call Add_Control(cCont, "Combobox", "cmbTabel", "Tabel", 110, 44, 90, 18)
Call Add_Control(cCont, "CommandButton", "cmdExit", "Afsluiten", 210, 140, 54, 18)
End Sub
Private Sub Add_Control(ctrl, ctp, cnm, cap, l, t, w, h)
Set ctrl = Me.controls.Add("Forms." & ctp & ".1", cnm)
With ctrl
.Left = l
.Top = t
.Width = w
.Height = h
End With
Select Case ctp
Case "Combobox"
controls(cnm).Clear
For j = 1 To 5
controls(cnm).AddItem "ListItem" & j
Next j
controls(cnm).ListIndex = 0
Case "Label", "CommandButton"
With controls(cnm)
.Caption = cap
End With
Case "Textbox"
controls(cnm).Text = cap
End Select
End Sub
Resulting form: