VBA在Collection中按值获取密钥

时间:2012-09-24 08:44:12

标签: excel vba excel-2003

  

可能重复:
  VBA collection: list of keys

也许这是一个非常简单的问题,但我是VBA的新手。我有一些数据,我想用作Collection(键,值)。如何通过值得到密钥?

1 个答案:

答案 0 :(得分:4)

我认为您无法使用Collection对象执行此操作。

但是,您可以使用替代Dictionary,您需要在VBA编辑器中包含在Excel项目中:单击“工具”菜单,选择“参考”并找到“Microsoft Scripting Runtime”,之后你应该可以做这样的事情:

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