Home > Net >  Unique name for radio button in user form excel vba
Unique name for radio button in user form excel vba

Time:03-17

I would like to get a unique name for each option button so that I can call the selected option button, but couldn't seem to figure out. Here's my code:

    For i = 1 To rng.Columns.Count - 1
        For j = 1 To 4
            Set ctl2 = Me.Controls.Add("forms.optionbutton.1")
                With ctl2
                    .Name = "ct" & j   1 - 1
                    .Caption = ""
                    .GroupName = "ctgrp" & i   1 - 1
                    .Top = 15   (i * 35)
                    .Left = 111   (j * 66)
                    .Width = 12
                    .Height = 12
                End With
        Next j
    Next i

Any help would be appreciated, Thanks!

Edits: Outcome

I've tried selecting one of the option button and check the name but the above message came out saying there's no name for the option button, only selecting the 1st row of option button gave me name for example: Outcome2

CodePudding user response:

The easy why to solve the problem is to break it down. Here I wrote two helper functions handle the naming groups and the controls in the group.

    ' Missing Code Here
    Dim GroupIndex As Long, ControlIndex As Long

    For i = 1 To Rng.Columns.Count - 1
        For j = 1 To 4
            GroupIndex = i   1 - 1
            ControlIndex = j   1 - 1
            Set ctl2 = Me.Controls.Add("forms.optionbutton.1")
                With ctl2
                    .Name = OptionName(GroupIndex, ControlIndex)
                    .Caption = ""
                    .GroupName = GroupName(GroupIndex)
                    .Top = 15   (i * 35)
                    .Left = 111   (j * 66)
                    .Width = 12
                    .Height = 12
                End With
        Next j
    Next i
End Sub

Function OptionName(GroupIndex As Long, ControlIndex As Long) As String
    Const ControlPrefix As String = "_"
    OptionName = GroupName(GroupIndex) & ControlPrefix & ControlIndex
End Function

Function GroupName(GroupIndex As Long) As String
    Const GroupPrefix As String = "ctgrp"
    GroupName = GroupPrefix & GroupIndex
End Function

Testing

I changed some settings for testing:

       With ctl2
            .Name = OptionName(GroupIndex, ControlIndex)
            .Caption = .Name
            .GroupName = GroupName(GroupIndex)
            .Top = 15   (i * 35)
            .Left = 111   (j * 66)
            .Width = 120
            .Height = 24
        End With

Userform Image

  • Related