Hi,
I have created some optionButtons on the fly by extracting some data from my database query. If I run through my dataset and output some of the optionButtons as controls they all appear but I am having some trouble trying to find a solution as to how I can validate them. As they have been created at runtime it is difficult to set up an Onclick event.
Here is my original code:
Do While Not rst.EOF
If n = 0 Then
questionsTop = 25
Else
questionsTop = questionsTop + 65
End If
'set the controls here
Set cFrame = Me.Controls.Add("Forms.Frame.1", "MyFrame", True)
With cFrame
.Width = 560
.Top = questionsTop
.Left = 20
.ZOrder (1)
.Caption = "Question " & (n + 1)
End With
Set qLab = cFrame.Controls.Add("Forms.label.1", "lab", True)
With qLab
.Width = 450
.Height = 10
.Top = 5
.Left = 10
.ZOrder (0)
.Caption = CStr(rst(2))
End With
Set cControl2 = cFrame.Controls.Add("Forms.OptionButton.1", "opt1", True)
With cControl2
.GroupName = "q_" + CStr(rst(0))
.Width = 150
.Height = 20
.Top = 0
.Left = 475
.ZOrder (0)
.Value = 1
End With
Set cControl2 = cFrame.Controls.Add("Forms.OptionButton.1", "opt2", True)
With cControl2
.GroupName = "q_" + CStr(rst(0))
.Width = 150
.Height = 20
.Top = 0
.Left = 500
.ZOrder (0)
.Value = 0
End With
questionsTop = questionsTop
n = n + 1
rst.movenext
Loop
This code creates my options buttons in my db loop.
I found some code on the web that seemed to work for dynamic controls but would only work on one instance of a new created optionButton and not within the loop. I think it is because it doesnt know the difference between each of the optionButtons created in the loop.
Code created on my UserForm1:
Dim OB_Coll As Collection
Dim Pos As Integer
Private Sub cmdEvent_Click()
'this works but need to apply to a my code
Dim o As MSForms.OptionButton
Dim OBE As New OptionButtonEvents
'
If OB_Coll Is Nothing Then Set OB_Coll = New Collection
Set o = Me.Controls.Add("Forms.OptionButton.1", , True)
o.Caption = "Dynamically Added Option Button" & CStr(Me.Controls.Count) - 2
o.AutoSize = True
o.Top = Pos
OB_Coll.Add OBE
Call OBE.WatchControl(o, Me)
Pos = Pos + o.Height + 4
End Sub
Friend Sub OptionButtonDblClick(o As MSForms.OptionButton)
MsgBox o.Name & " was just double-clicked..."
End Sub
Code created as Class Module OptionButtonEvents:
Option Explicit
Private WithEvents ob As MSForms.OptionButton
Private CallBackParent As UserForm1
Private Sub ob_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Call CallBackParent.OptionButtonDblClick(ob)
End Sub
Friend Sub WatchControl(oControl As MSForms.OptionButton, oParent As UserForm1)
Set ob = oControl
Set CallBackParent = oParent
End Sub
Is there an easier way to do this or should I try to modify this method to get it to work for me?