在 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/