VBA从组中获取真实的单选按钮值

Ami*_*hli 5 vba radio-group userform radio-button

在 Excel VBA 中:

我正在创建一个表格。该表单有多个单选按钮组,其中一些有多个选项(但每组只能有一个单选按钮)。我希望能够获取每个组“true”的单选按钮的名称,而不必检查每个单选按钮的条件。

例如:

家庭A

  • 选项1-F
  • 选项2-T

家庭B

  • 选项 11 - F
  • 选项12-F
  • 选项 13 - F
  • 选项 14 - F
  • 选项 15 - T

我必须做什么

  • 选项1正确吗?
  • 选项2正确吗?(是的...所以A家庭的选项2)
  • 选项11正确吗?
  • 选项12正确吗?
  • 选项13正确吗?
  • 选项14正确吗?
  • 选项15正确吗?(是的...所以 B 族的选项 15)

我想做的

  • 对于家庭 A 来说,哪个按钮是正确的?(选项2)
  • 对于 B 族来说,哪个按钮是正确的?(选项15)

这可能吗?

感谢您的关注!

编辑: 解决方案!根据大卫的以下建议:

Dim ctrl As MSForms.Control
Dim dict(5, 1)
Dim i

'## Iterate the controls, and associates the GroupName to the Button.Name that's true.

For Each ctrl In Me.Controls
    If TypeName(ctrl) = "OptionButton" Then
        If ctrl.Value = True Then
            dict(i, 0) = ctrl.GroupName
            dict(i, 1) = ctrl.Name
            i = i + 1
        End If
    End If
Run Code Online (Sandbox Code Playgroud)

Dav*_*ens 2

像这样的东西似乎有效。我已将其放入 CommandButton 单击事件处理程序中,但您可以将其放在任何位置。

Sub CommandButton1_Click()

Dim ctrl As MSForms.Control
Dim dict As Object

Set dict = CreateObject("Scripting.Dictionary")


'## Iterate the controls, and add the GroupName and Button.Name
'  to a Dictionary object if the button is True.
'  use the GroupName as the unique identifier/key, and control name as the value

For Each ctrl In Me.Controls
    If TypeName(ctrl) = "OptionButton" And ctrl.Value = True Then
        dict(ctrl.GroupName) = ctrl.Name
    End If
Next

'## Now, to call on the values you simply refer to the dictionary by the GroupName, so:

Debug.Print dict("Family A")
Debug.Print dict("Family B")

Set dict = Nothing

End Sub
Run Code Online (Sandbox Code Playgroud)