从combobox(表单控件)中检索选定的选项excel VBA

嘿,我似乎不明白为什么我的代码不工作,因为我看到这是在SO的另一个问题的答案。 我想从combobox中检索选定的项目,因为我随后必须在匹配索引函数中使用它。 这是我的代码

Option Explicit Dim ws As Sheets Sub test2() Set ws = Sheets(Array("Sheet1", "Sheet2")) With ws(1).Shapes("Drop Down 2").ControlFormat .List(.ControlFormat.ListIndex) = ws(1).Range("I8").Value End With End Sub 

另外,我想知道如何参考一般的下拉菜单? 因为我有10个这样的combobox(下拉列表),每个combobox都以数字为基础进行不同的命名。 所以,而不是提到一个特定的下拉,如“下拉2”,或通过使用循环说(“下拉”我),是否有一种通用的方式来引用特定工作表下拉? 我真的需要帮助

这是如何检索选定的项目值:

 Dim myindex As Long, myitem As String Dim ws As Worksheet Set ws = Sheets("Sheet1") '~~> Currently selected item index at runtime myindex = ws.Shapes("Drop Down 1").ControlFormat.Value '~~> Currently selected item value at runtime myitem = ws.Shapes("Drop Down 1").ControlFormat.List(myindex) 

对于你的第二个问题,你可以使用形状集合对象
然后使用For Each循环结构。

 Dim shp As Shape, ws As Worksheet: Set ws = Sheets("Sheet1") Dim myindex As Long, myitem As String '~~> Iterate the shapes collection object For Each shp In ws.Shapes '~~> Check the type If shp.Type = msoFormControl Then myindex = shp.ControlFormat.Value myitem = shp.ControlFormat.List(myindex) '~~> additional codes here End If Next 

但是,如果您需要在特定的ComboBox中执行特定的操作,请使用您在问题中描述的内容。 HTH

EDIT1:

 For Each shp In ws.Shapes '~~> Check the type If shp.Type = msoFormControl Then With shp.ControlFormat myvalue = .List(.ListIndex) End With End If Next 

以上的作品以及你评论。
至于为什么它只在With子句下工作是因为这基本上就是你用的。
以某种方式缩短代码。 如果你想在没有使用 ,使用下面:

 myvalue = shp.ControlFormat.List(shp.ControlFormat.ListIndex)