2

我有一个 Excel 用户表单,其中有许多单选(选项)按钮组合在一起。

是否可以参考单选按钮的 GroupName 来确定选择了哪一个?

我试过me.myGroup了,但 Excel 无法识别。

如果可能的话,我想写一些类似的东西;

myVar = me.mygroup

这在 Excel 2013 中可行吗?

4

3 回答 3

4

如果您GroupName在选项按钮上设置了属性,如下所示:

在此处输入图像描述

然后,您可以在控件的循环中引用该属性,以查看控件TypeName是否匹配:OptionButtonGroupName

Option Explicit

Private Sub CommandButton2_Click()
    Dim opt As MSforms.OptionButton

    Set opt = GetSelectedOptionByGroupName("MyGroup")

    If Not opt Is Nothing Then
        MsgBox opt.Name
    Else
        MsgBox "No option selected"
    End If

End Sub

Function GetSelectedOptionByGroupName(strGroupName As String) As MSforms.OptionButton

    Dim ctrl As Control
    Dim opt As MSforms.OptionButton

    'initialise
    Set ctrl = Nothing
    Set GetSelectedOptionByGroupName = Nothing

    'loop controls looking for option button that is
    'both true and part of input GroupName
    For Each ctrl In Me.Controls
        If TypeName(ctrl) = "OptionButton" Then
            If ctrl.GroupName = strGroupName Then 
                Set opt = ctrl
                If opt.Value Then
                    Set GetSelectedOptionByGroupName = opt
                    Exit For
                End If
            End If
        End If
    Next ctrl

End Function
于 2017-01-03T12:49:38.310 回答
1

早上皮特,

您需要为变量分配一个特定的值,以确定单击了哪个按钮。

尝试类似的东西

Private Sub OptionButton1_Click()

myVar = 1

End Sub

使用特定值。您可以通过双击用户表单编辑器中的单选按钮来自动访问此子例程。这样,稍后在您的代码中,您可以参考 myVar 来确定您的脚本接下来应该采取的操作,例如

If myVar = 1 Then
....
ElseIf myVar = 2 Then
....
End If

等等

如果不了解您的代码试图做什么,我真的无法提供更具体的建议。

希望有帮助!

于 2017-01-03T12:11:47.780 回答
0

这应该让你走上正确的轨道。循环遍历您的控件并检查它们是否被选中(TRUE在单选按钮的情况下)

Private Sub CommandButton1_Click()
    For Each Control In UserForm1.Controls
        If Control.Value = True Then
            MsgBox Control.Name
            'MsgBox Control.Tag
        End If
    Next Control
End Sub
于 2017-01-03T12:09:46.033 回答