2017-08-17 59 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

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