3

重複の可能性:
VBA コレクション: キーのリスト

非常に単純な質問かもしれませんが、私は VBA の初心者です。コレクション(キー、値)として使用したいデータがあります。値でキーを取得するにはどうすればよいですか?

4

1 に答える 1

4

オブジェクトでこれを行うことはできないと思いますCollection

ただし、VBAエディターからExcelプロジェクトに含める必要のある代替手段を使用することもできDictionaryます。[ツール]メニューをクリックし、[参照]を選択して、[MicrosoftScriptingRuntime]を見つけます。このようなもの:

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 に答える