我怎样才能find在Excel中的组框中select的形状?
我有一个包含选项button的combobox,我需要找出哪一个在VBA中被选中。 我一直浏览MSDN几个小时,我找不到解决scheme。
必须有一种方法来find所选的选项button。 可能通过名字和每个通过每个选项buttonfind组?
这似乎是一个工作的解决scheme。
(点到KazJaw Dim ... As OptionButton
。这似乎是获得.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
如果你真的需要检查被分组的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
编辑记住下面的图片上面的代码将解决这个问题,如果我们有选项button,这是我们分组放置在工作表中的任何形状的组。
图片下面的代码会发现哪些选项button被选中,如果他们位于GroupBox内。 代码检查OptionButton所在组的名称。
重要的提示! 下面的代码不工作,直到我closuresExcel并再次运行它。
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
假设你有两个标准的选项button:
要检查它的“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
要获得其alternat文本使用:
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