3

可能重复:
VBA 集合:键列表

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

4

1 回答 1

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
于 2012-09-24T09:08:25.767 回答