0

I am trying to add an option button from the range in the Excel worksheet.

For Each Value In OptionList

    Set opt = UserForm3.Controls.Add("Forms.OptionButton.1", "radioBtn" & i, True)
    opt.Caption = Value
    opt.Top = opt.Height * i
    opt.GroupName = "Options"

    UserForm3.Width = opt.Width
    UserForm3.Height = opt.Height * (i + 2)

    i = i + 1

Next

I want to create an event handler so that if radiobtn1 is selected while running the code from the user. Alhough I got a lot of answers, those are meant for worksheet user form.

My intention is to work on the VBA user form. Please help me with your thoughts.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
sabarigiri
  • 57
  • 1
  • 5
  • 4
    Since it looks like you are adding the controls dynamically, I would check out this link: https://stackoverflow.com/a/10224992/9259306 – Mistella Mar 13 '18 at 14:18
  • There's a Worksheet user form and a VBA user form? I thought they were all just Excel user forms - the link given by @Mistella is the way to go. – Darren Bartrup-Cook Mar 13 '18 at 14:26
  • 1
    FWIW you're adding your dynamic controls to the form's default instance, which means if you do `Set frm = New UserForm3` and then `frm.Show`, that instance is NOT going to have them. If this code is in the form's code-behind, I warmly recommend you replace all `UserForm3` qualifiers with `Me`, so that the controls are added to whatever the *current instance* is. – Mathieu Guindon Mar 13 '18 at 16:08
  • If you need more specific assistance with your question after reading my answer (below), could you please double-check to confirm which type of control you are using and ensure you're using the appropriate syntax as per the combobox example? – ashleedawg Mar 13 '18 at 18:13
  • @Mat'sMug Thanks for your answer. Stil the event handler is not working. – sabarigiri Mar 14 '18 at 03:27
  • The link provided by @Mistella has your answer. You need to add a class module with a `WithEvents` private field of the control type you want to handle events for. Use the dropdowns at the top of the code pane to create the handlers you need. The code creating the controls needs to hold a reference to the class instances somewhere - the linked answer stores them in a module-scoped array. I will be marking your question as a duplicate; feel free to ask a new question if you run into any specific issue adapting the solution to your specific needs. – Mathieu Guindon Mar 14 '18 at 03:49
  • **I've added more detail** to my [answer (below)](https://stackoverflow.com/a/49263001/8112776) including **specifics about how to handle control events on userforms**. Let me know if you have any questions; At this point I might as well make the answer as clear as possible, and then **turn it into a [wiki](https://meta.stackexchange.com/a/11741/370758)** since this is an ongoing matter of confusion for many. – ashleedawg Mar 14 '18 at 15:27
  • @sabarigiri - I trust you eventually got this figured out... If it's okay with you, I would like to edit and re-phrase your question so it can get re-opened. Is is generating lots of traffic even while closed, so re-opening it will create more exposure. Let me know if you have any issue with this. – ashleedawg May 01 '18 at 13:06

1 Answers1

5

There is only one type of userform, however there is [eternal] confusion surrounding the two types of controls available to Excel — exacerbated by the contrasting terminology used by different online sources. (Only the sections about ActiveX controls apply to userforms.) Perhaps I can help shed some light by putting it in words that help me understand.


Overview:

  • There are two types of controls: Form controls and ActiveX controls:

    • Both types of controls can be used on worksheets but only ActiveX controls can be used on userforms.

    • Form controls are part of the Shapes collection (just like Drawing Objects), and thus are referred to like: *<code>worksheet</code>* **<code>.</code> <code>Shapes("</code>** *<code>controlname</code>* **<code>")</code>**

    • ActiveX controls are basically part of the worksheet and are therefore referred to like:
      *<code>worksheet</code>* **<code>.</code>** *<code>controlname</code>*

    • Both types of controls can be created, modified and deleted from either the worksheet, or programmatically with VBA, however, the 2 types of controls have slightly varying syntax when using VBA to refer to them.

  • Some sites discuss also discuss a Data Form. This is nothing more than a userform made specifically for data entry/manipulation of data, so it would've made more sense to call them (the more familiar sounding) "Data Entry Userform".

  • Office documentation also occasionally refers to a worksheet as a form. While this is technically correct, don't let this confuse you. Think of the word "form" as being used in a general sense:

    dictionary image: form


Two Types of Controls

  1. Form Controls

  2. ActiveX Controls

The two look, behave, and are controlled similarly, but not identically. (List here.)

For example, let's compare the two types of Combo Boxes. In some programming languages, comparable controls are referred to as a "drop-down menu" or "drop-down list". In Excel, we have a "Form Control Combo Box", and an "ActiveX Control Combo Box":

compare control types (Click image to enlarge.)

"Default name" applies to controls created manually. Controls created programmatically do not have (or require) a default name and therefore should have one assigned immediately upon creation.


differences between controls

(Source: my answer)


About ActiveX controls and related security concerns

An ActiveX control is an extension to the VBA Toolbox. You use ActiveX controls just as you would any of the standard built-in controls, such as the CheckBox control. When you add an ActiveX control to an application, it becomes part of the development and run-time environment and provides new functionality for your application.

  • An ActiveX control is implemented as an in-process server (typically a small object) that can be used in any OLE container. Note that the full functionality of an ActiveX control is available only when used within an OLE container designed to be aware of ActiveX controls.

  • This container type, called a control container or control object, can operate an ActiveX control by using the control’s properties and methods, and receives notifications from the ActiveX control in the form of events. The following figure demonstrates this interaction:

    example
    (Source: this and this)

See also:


Option Buttons (Radio Buttons)

In Excel, the two types of radio buttons are actually called Option Buttons. To further confuse matters:

  • the default name for the form control is OptionButton1.

  • the default name for the ActiveX control is Option Button 1.

A good way to distinguish them is by opening the control's Properties list (on the ribbon under the Development tab, or by right-clicking the control and choosing Properties, or hitting F4), because the ActiveX control has many more options that the simpler form control.

Option buttons and checkboxes can be bound together (so only one option at a time can be selected from the group) by placing them in a shared Group Box.

Select the group box control and then hold Ctrl while selecting each of the other controls that you want to group. Right-click the group box control and choose GroupingGroup.

The first two links below are separate sets of instructions for handling each type of option button.


HANDLING CONTROL EVENTS:

Form control events (Click event only)

Form control events are only able to respond to one event: the Click event. (More info here.) Note that this section doesn't apply to userforms since they use only ActiveX controls.

To add a procedure for the Click event:

  • Right-click the control and choose Assign Macro...

  • In the 'Assign Macro` Dialog:

    • Select an existing procedure, and click OK, or,

    • Create a new procedure in the VBE by clicking New..., or,

    • Record a new macro by clicking Record..., or,

    • to Remove the assigned event, delete its name from Macro Name field and click OK.

    assign events (Click image to enlarge.)

To rename, edit or delete existing macros, hit Alt+F8 to open the Macro interface:

Macros dialog


ActiveX control events

ActiveX controls have a more extensive list of events to which they can be set up to respond.

To assign events to ActiveX controls, right-click the control and choose View Code. In the VBE, you can paste in code, or choose specific events from the drop-down list at the top-right of the VBE window.

activeX events (Click image to enlarge.)

Control event handling on a userform:

Events can also be used in controls on userforms. Since only ActiveX controls can be placed a userform, you'll have the "more coding + more functionality" trade-off.

ActiveX controls are added to userforms the same way as they are added to a worksheet. Keep in mind that any events assigned to the userform itself (ie., background) will be "blocked" in any areas covered up by a control, so you may need to assign the same events to the controls as well as the userform.

For example, in order to make this userform respond to MouseMove anywhere on the form, the same event code was applied to the userform, textboxes, option buttons and the frame:

A userform with controls responding to events


VBA EXAMPLES

Add/Modify/Delete a form control option button using VBA:

Sub formControl_add()
    'create form control
    Dim ws As Worksheet: Set ws = ActiveSheet
    With ws.Shapes.AddFormControl(xlOptionButton, 25, 25, 100, 100)
        .Name = "cOptionButton1"  'name control immediately (so we can find it later)
    End With
End Sub

Sub formControl_modify()
    'modify form control's properties
    Dim ws As Worksheet: Set ws = ActiveSheet
    ws.Shapes("cOptionButton1").Select
    With Selection 'shapes must be Selected before changing
        .Characters.Text = "wxyzabcd"
   End With
End Sub

Sub formControl_delete()
    'delete form control
    Dim ws As Worksheet: Set ws = ActiveSheet
    ws.Shapes("cOptionButton1").Delete
End Sub

Add/Modify/Delete an ActiveX command button using VBA:

Sub activexControl_add()
    'create ActiveX control
    Dim ws As Worksheet: Set ws = ActiveSheet
    With ws.OLEObjects.Add("Forms.CommandButton.1")
        .Left = 25
        .Top = 25
        .Width = 75
        .Height = 75
        .Name = "xCommandButton1" 'name control immediately (so we can find it later)
    End With
End Sub

Sub activexControl_modify()
    ' modify activeX control's properties
    Dim ws As Worksheet: Set ws = ActiveSheet
    With ws.OLEObjects("xCommandButton1").Object
        .Caption = "abcxyz"
        .BackColor = vbGreen
    End With
End Sub

Sub activexControl_delete()
    ' delete activeX control
    Dim ws As Worksheet: Set ws = ActiveSheet
    ws.OLEObjects("xCommandButton1").Delete
End Sub

Add/Remove items from a form control combo box:

Sub ComboBox_addRemoveItems_FormControl()

    Dim ws As Worksheet: Set ws = ActiveSheet

    'add item to form control combo box
    ActiveWorkbook.Sheets("Sheet1").Shapes("Drop Down 1").ControlFormat.AddItem "abcd"

    'remove all items from from form control combo bo
    ActiveWorkbook.Sheets("Sheet1").Shapes("Drop Down 1").ControlFormat.RemoveAllItems

End Sub  

Add/Remove items from an ActiveX combo box:

Sub ComboBox_addRemoveItems_ActiveXControl()

    Dim ws As Worksheet: Set ws = ActiveSheet

    'add items to ActiveX combo box
    ActiveWorkbook.Sheets("Sheet1").ComboBox1.AddItem "abcd"

    'remove all items from ActiveX combo box
    ActiveWorkbook.Sheets("Sheet1").ComboBox1.Clear

End Sub  

More Information:

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
  • thanks for your detailed explanation. But this is what My problem needs to add an event handler for option button which is dynamically added to the VBA user form and those option buttons are not available when the user form initialize – sabarigiri Mar 14 '18 at 03:18
  • @sabarigiri - I added a bunch of info and examples of how to use events with both types of controls. Userforms use ActiveX controls, and have access to the **complete list of events** with the same method described above for ActiveX control events. Let me know if you have any questions. :) – ashleedawg Mar 14 '18 at 14:30
  • Plus one from me. Now I can refer people here! – QHarr Apr 01 '18 at 14:26
  • So your text says useform is ActiveX but the comparison chart has a tick against both for on userform... Did I misunderstand something? And the other thing...could there be more info about security concerns of ActiveX? What is the key concern? – QHarr Apr 01 '18 at 14:31
  • @QHarr - I must have missed this a month ago. You're right about the comparison chart; it's been corrected, thanks. I added a link to a Symantec discussion re: ActiveX security and will expand on that as I find out more. I'm considering moving this answer to a separate Q&A since it's popular even though the Question is *closed* (and I refer people here too for control overviews). – ashleedawg May 01 '18 at 13:10
  • Thanks for updating – QHarr May 01 '18 at 13:11