I want to dynamically add a radio button on a form, using VBA.
I tried writing this code, but it crashes with ‘Type Mismatch’
Dim optionBtn As OptionButton
Set optionBtn = UserForm1.Controls.Add("Forms.OptionButton.1", "name", True)
optionBtn.Left = 10
optionBtn.Top = 10
optionBtn.Width = 30
optionBtn.Group = "q1"
I also tried doing this:
Dim optionBtn As Control
Set optionBtn = UserForm1.Controls.Add("Forms.OptionButton.1", "name", True)
optionBtn.Left = 10
optionBtn.Top = 10
optionBtn.Width = 30
optionBtn.Group = "q1"
but I get a Control, not a OptionButton – how can I cast it to a OptionButton ? (sorry, I’m new to VB)
I was able to get it work with this (Excel 2003):
Update to reflect your change from a Label to an OptionButton
Again, the key is use a Variant type for the variable that you are assigning the returned control to:
Keep in mind that autocomplete won’t work on the variables that are defined as Variants. However you can still refer to properties and methods of those variables by typing them manually.