2012-09-24 50 views

回答

4

我不認爲你可以用Collection這個對象來做到這一點。

但是,您可以使用替代Dictionary,您需要在VBA編輯器中包含在Excel項目中:單擊「工具」菜單,選擇「參考」並找到「Microsoft腳本運行時」應該可以這樣做:

Public Sub Test() 

Dim dict As New dictionary 
    dict.Add "a", 1  ' "Add" parameters are reversed compared to Collection 
    dict.Add "b", 2 
    dict.Add "c", 3 

    If KeyFromvalue(dict, 2) = "b" Then 
     Debug.Print "Success!" 
    Else 
     Debug.Print "fail..." 
    End If 

End Sub 

Public Function KeyFromvalue(dict As dictionary, ByVal target) 

Dim idx As Long 

    For idx = 0 To dict.Count - 1 
     If dict.Items(idx) = target Then 
      KeyFromvalue = dict.Keys(idx) 
      Exit Function 
     End If 
    Next 

End Function 
+0

VBA集合對象能夠維護鍵值。添加:'myCollection.Add值,[鍵],[之前],[之後]'和讀取:'myCollection(key)' –