3
也許這是一個很簡單的問題,但我在VBA很新。我有一些我想用作Collection的數據(鍵,值)。我如何通過價值獲得關鍵?
也許這是一個很簡單的問題,但我在VBA很新。我有一些我想用作Collection的數據(鍵,值)。我如何通過價值獲得關鍵?
我不認爲你可以用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
VBA集合對象能夠維護鍵值。添加:'myCollection.Add值,[鍵],[之前],[之後]'和讀取:'myCollection(key)' –