Excel – 返回所选选项button的标题

可能是一个简单的答案愚蠢的问题,但我是一个真正的新手,当涉及到用户forms。

我有带有5个不同选项button(Dest1,Dest2,Dest3,Dest4,Dest5)的“Frame 3”。select一个选项后,所选选项的标题值在哪里存储? 我怎样才能访问与vba。

谢谢,乔希

这里只是一些您可以使用的示例代码。 将你的选项button添加到组,然后你可以从那里去。 我使用了多个组,因为您有多个框架,您可以根据组进行检查,并有多个组,并检查为每个组select哪一个。

 Private Sub CommandButton1_Click() Dim x As Control ' Loop through ALL the controls on the UserForm. For Each x In Me.Controls ' Check to see if "Option" is in the Name of each control. If InStr(x.Name, "Option") Then ' Check Group name. If x.GroupName = "Grp1" Then ' Check the status of the OptionButton. If x.Value = True Then MsgBox x.Caption Exit For End If End If End If Next End Sub 

你也可以通过frame-ojbect来访问选项button(如果你有其他的框架和控件你不想通过):

 Option Explicit Sub Test() Dim oCtrl As Control '***** Try only controls in Frame3 For Each oCtrl In Frame3.Controls '***** Try only option buttons If TypeName(oCtrl) = "OptionButton" Then '***** Which one is checked? If oCtrl.Value = True Then '***** What's the caption? Debug.Print "You have checked option " & oCtrl.Caption Exit For End If End If Next End Sub 

与选项button关联的标签文本可以通过使用OptionButton1.Caption获得

如果您正在使用循环,只需将OptionButton1replace为选项button的variables,并在条件满足时通过所需的variables。 例如:

 For xitem = 1 To 5 xFrm = "OptionButton" & xitem For Each fItem In Me.Controls If fItem.Name Like xFrm Then If fItem.Value Then k = fitem.Caption End If End If Next fItem Next xitem 

在我的情况下,我希望将在选项组中select的切换的标题传递给子窗体filter。 例如select切换“黑色”filter子窗体的所有汽车strColour =“黑色”。

我结束了这个:

 Private Sub OptionGroupName_Click() Dim Caption As String Caption = OptionGroupName.Controls.Item(OptionGroupName.Value - 1).Caption Me.SubformName.Form.Filter = "[SubformField] = """ & Caption & """" Me.SubformName.Form.FilterOn = True End Sub 

不要在其他人的select上堆积如山,但我创build了一个采用无线电组名称并吐出所选收音机相应标签标题的function。 在Access中使用它而不是Excel。 只有您提供的名称与您的控件类似…. ie(lblRadioButton1&optRadioButton1)

 Function GetSelectedRadioButtonCaption(ByVal optionGroupName As OptionGroup) As String Dim oCtrl As Control Dim oCtrl2 As Control Dim optionLabelName As String Dim optionLabelObject As Label Dim optionButtonObject As OptionButton For Each oCtrl In optionGroupName.Controls '***** Try only option buttons If TypeOf oCtrl Is OptionButton Then '***** Which one is checked? Set optionButtonObject = oCtrl If optionButtonObject.OptionValue = optionGroupName.Value Then '***** What's the caption? optionLabelName = Replace(oCtrl.Name, "opt", "lbl") For Each oCtrl2 In optionGroupName.Controls If oCtrl2.Name = optionLabelName Then Set optionLabelObject = oCtrl2 GetSelectedRadioButtonCaption = optionLabelObject.caption Exit For End If Next End If If GetSelectedRadioButtonCaption <> "" Then Exit For End If End If Next Exit_GetSelectedRadioButtonCaption: End Function