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

标签 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

最佳答案

类似的东西似乎有效。我已将其放入 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

关于VBA从组中获取真实的单选按钮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22765341/

相关文章:

excel - 如何将 ArrayLists 添加到 ArrayList 中?

excel - 以编程方式安装加载项 VBA

javascript - 将 ExtJS 单选按钮分组为不同名称以保存在数据库中

vba - 用户窗体未触发初始化或激活事件

excel - 无模式表单上文本框输入的验证消息会中断文本选择

vba - 使用 VBA 复制和粘贴格式很慢。我怎样才能加快速度?

ms-access - 如何在函数中引用 Excel 工作表

Android:对话框中单选组的空指针异常

android - 如何在相对android布局中为单选按钮设置单选按钮

excel - 用户窗体中的月 View - 自动关闭