Excel VBA词典存储和检索
你如何创buildExcel VBA字典?
说我有以下值:
如何设置列A作为键,列B作为值?
我是否循环每个值来存储?
我怎么去用字典来获取5的值(“Key A”)
在Excel中:
=VLOOKUP("D", A:B, 2,FALSE)
返回20
。 在VBA中:
MsgBox WorksheetFunction.VLookup("D", Sheet1.Range("A:B"), 2, False)
stream行20
。
从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中看起来像这样