2017-08-17 60 views
1

如何创建excel VBA词典?Excel VBA词典存储和检索

说我有以下值:

enter image description here

我如何设置列A为重点,B列的值?

我是否循环每个值来存储?

如何去使用字典后获得的5实例(“键”)

+0

是的,循环,除非你更喜欢使用'WorksheetFunction.VLookup'并忘记Dictionary。 –

+0

你可以发布一个示例代码模板,做同样的事情:D(与查找) – Kagerjay

回答

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

1

在Excel:

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

返回20。 在VBA:

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

弹出20

+0

难道只是更容易使用vlookups的一切,而不是字典?或者我错过了什么? (例如,它不是计算效率高吗?) – Kagerjay

+0

真的取决于您的应用程序。有时我会使用VLookups,有时候会使用字典,有时候还会使用别的。 –

+0

你也可以使用散列表匹配...(只是在开玩笑!) –