2014-07-01 29 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

相關問題