Excel VBA字典存储和检索

时间:2017-08-17 14:52:25

标签: excel vba excel-vba dictionary

如何创建excel VBA词典?

说我有以下值:

enter image description here

如何将列A设置为键,将列B设置为值?

我是否遍历要存储的每个值?

如何使用字典后来获取值5(例如“Key A”)

2 个答案:

答案 0 :(得分:1)

在Excel中:

=VLOOKUP("D", A:B, 2,FALSE)

返回20。 在VBA:

MsgBox WorksheetFunction.VLookup("D", Sheet1.Range("A:B"), 2, False)

弹出20

答案 1 :(得分:0)

在reddit用户MRMCMLXXXV

中将答案放在此处用于文档目的

来源https://www.reddit.com/r/excel/comments/6u4swi/how_do_you_create_a_dictionary_in_excel_vba_and/

Public Sub DictionaryExamples()

    Dim exampleValues As Variant
    Dim i As Long
    Dim aKey As String
    Dim aValue As Integer
    Dim exampleDict As Object

    'Load values into a variant array
    exampleValues = Range("A1:B10").Value

    'Instantiate a dictionary
    Set exampleDict = CreateObject("scripting.dictionary")

    'Read all keys and values, and add them to the dictionary

    For i = 1 To UBound(exampleValues)
        aKey = CStr(exampleValues(i, 1))
        aValue = CInt(exampleValues(i, 2))
        exampleDict.Add aKey, aValue
    Next i

    'Output the value associated with key A

    MsgBox exampleDict.Item("A")

End Sub

结果在excel中看起来像这样

enter image description here