在Excel用户窗体中从组返回选定的单选button

早上好,新年快乐!

我有一个Excel用户窗体,有一些无线电(选项)button已被分组在一起。

是否可以引用单选button的GroupName来标识哪一个被选中?

我试过使用me.myGroup ,但Excel不能识别它。

如果可能的话,我希望能够写下类似的东西;

 myVar = me.mygroup 

这可能在Excel 2013中吗?

非常感谢

皮特

如果您在选项button上设置了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 Set opt = ctrl If opt.Value Then Set GetSelectedOptionByGroupName = opt Exit For End If End If Next ctrl End Function 

这应该让你走上正轨。 循环你的控件,并检查它们是否被选中(在单选button的情况下为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 

早晨皮特,

您需要为您的variables分配一个特定的值,以确定哪个button已被点击。

尝试类似

 Private Sub OptionButton1_Click() myVar = 1 End Sub 

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

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

等等

我不能不知道更多关于你的代码试图做什么的更具体的build议。

希望有所帮助!

Interesting Posts