【问题标题】:Return selected radiobutton from group in Excel userform从 Excel 用户窗体中的组中返回选定的单选按钮
【发布时间】:2017-01-03 11:49:10
【问题描述】:

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

是否可以参考单选按钮的 GroupName 来识别选择了哪个?

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

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

myVar = me.mygroup

这在 Excel 2013 中可行吗?

【问题讨论】:

    标签: excel vba radio-button userform groupname


    【解决方案1】:

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

    然后,您可以在控件的循环中引用该属性,以查看控件的 TypeNameOptionButton 并且 GroupName 是匹配项:

    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
    

    【讨论】:

    • 感谢这位罗宾,辛苦了!很遗憾,您必须遍历所有控件才能执行此操作,我认为简单地引用组并返回所选项目会很好,例如0,1,2,3等
    【解决方案2】:

    早上皮特,

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

    试试类似的东西

    Private Sub OptionButton1_Click()
    
    myVar = 1
    
    End Sub
    

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

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

    等等

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

    希望有帮助!

    【讨论】:

      【解决方案3】:

      这应该让你走上正轨。循环遍历您的控件并检查它们是否被选中(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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 2014-10-14
        相关资源
        最近更新 更多