我有一个带有选项按钮的分组框,我需要找出在VBA中选择了其中的哪一个。我已经浏览了几个小时的MSDN,但我找不到解决方案。
必须有一种方法来找到所选的选项按钮。是否可以通过每个选项按钮找到group by name和for-each?
发布于 2013-05-07 16:29:59
这似乎是一个可行的解决方案。
(向Dim ... As OptionButton
的KazJaw点头。这似乎是让.GroupBox
正常工作的关键)
Function WhichOption(shpGroupBox As Shape) As OptionButton
Dim shp As OptionButton
Dim shpOptionGB As GroupBox
Dim gb As GroupBox
If shpGroupBox.FormControlType <> xlGroupBox Then Exit Function
Set gb = shpGroupBox.DrawingObject
For Each shp In shpGroupBox.Parent.OptionButtons
Set shpOptionGB = shp.GroupBox
If Not shpOptionGB Is Nothing Then
If shpOptionGB.Name = gb.Name Then
If shp.Value = 1 Then
Set WhichOption = shp
Exit Function
End If
End If
End If
Next
End Function
像这样使用它
Sub test()
Dim shpOpt As OptionButton
Set shpOpt = WhichOption(Worksheets("Sheet1").Shapes("Group Box 1"))
Debug.Print shpOpt.Name
End Sub
发布于 2013-05-07 13:58:26
如果你确实需要检查分组的OptionButton (以我们分组任何类型的形状的方式分组),你可以使用下面的代码:
Sub Grouped_into_UnitType()
Dim i!
'grouped into 'UnitType' Shape
For i = 1 To ActiveSheet.Shapes("UnitType").GroupItems.Count
With ActiveSheet.Shapes("UnitType").GroupItems(i).ControlFormat
If .Value = 1 Then
MsgBox "Chosen item: " & i
End If
End With
Next i
End Sub
编辑记住下面的图片上面的代码将解决这个问题,如果我们有选项按钮,这些按钮以我们对工作表中的任何形状进行分组的方式进行分组。
图片下的代码将查找选择了哪个选项按钮(如果它们位于GroupBox中)。Code检查OptionButton所在组的名称。
重要提示!下面的代码直到我关闭并再次运行它时才起作用。
Sub Grouped_into_GroupBox_UnitType()
Dim OB As OptionButton
For Each OB In ActiveSheet.OptionButtons
'check if grouped into 'UnitType' Shape
If OB.GroupBox.Name = "UnitType" Then
If OB.Value = 1 Then
MsgBox "Chosen item: " & OB.Name & _
vbNewLine & _
"Alt text: " & OB.ShapeRange.AlternativeText
End If
End If
Next
End Sub
发布于 2013-05-07 13:50:50
假设您有两个标准选项按钮:
要检查它是否处于"on“状态,请使用:
Dim opt As Shape
Set opt = Worksheets("Sheet1").Shapes("Option Button 1")
If opt.ControlFormat.Value = xlOn Then
Debug.Print "option is ""on"" value of 1"
Else
Debug.Print "option is ""off"" value of -4146"
End If
要获取其替代文本,请使用:
Debug.Print "Alternate Text is: " & opt.AlternativeText
对于大量的选项,可以使用 "FormControlType“属性:
Dim s as Shape
For Each s In Worksheets("Sheet1").Shapes
If s.FormControlType = xlOptionButton Then
If s.ControlFormat.Value = xlOn Then
Debug.Print "option is ""on"" value of 1"
Else
Debug.Print "option is ""off"" value of -4146"
End If
Debug.Print "Alternate Text is: " & s.AlternativeText
End If
Next
如果你想要一个特定的组:
Dim s As Shape, o
For Each s In Worksheets("Sheet1").Shapes
If s.FormControlType = xlOptionButton Then
Set o = s.OLEFormat.Object
If o.GroupBox.Name = "Group Box 3" Then
If s.ControlFormat.Value = xlOn Then
Debug.Print "Option is ""on"" value of 1"
Else
Debug.Print "Option is ""off"" value of -4146"
End If
Debug.Print "Alternate Text is: " & s.AlternativeText
Debug.Print "Group: " & o.GroupBox.Name
End If
Set o = Nothing
End If
Next
https://stackoverflow.com/questions/16411457
复制相似问题