2014-07-01 32 views
2

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

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个这样的组合框(下拉框),每个组合框的名称都有不同的数值。因此,不是指一个特定的下拉菜单,比如“Drop Down 2”,或者使用循环说(“Drop Down”& i),是否有一种通用的方式来引用特定工作表上的下拉菜单?我真的需要帮助..

回答

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) 

关于第二个问题,你可以使用形状集合对象
然后使用对于每个循环构造。

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 

但是,如果你需要做的具体的东西在特定组合框,请你在你的问题描述。 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) 
+0

嘿谢谢工程:)我试着用.LIST(.listindex)属性,它的工作很好,但下嵌套时,只“用”命令..任何想法为什么? –

+0

非常感谢你:) –

+1

仅供参考,工作表中有一个你可以使用的DropDowns集合,而不是去测试所有类型的房屋。 ;) – Rory

相关问题