I cannot find out how to store and access an array in a VBA dictionary.
I have a key with multiple items, say "Apple" with value "3" and quantity "5".
A single item would not be a problem, ie: dict("Apples") = 3
But how do I store and retrieve multiple values? Lets say I want to add "Apples, 3, 5" and then move to cell C4 and automatically paste Apples there, 3 in C5 and 5 in C6.
So far I've tried:
Dim last_row As Long
last_row = Cells(Rows.Count, 1).End(xlUp).Row
Dim last_col As Long
last_col = ActiveSheet.UsedRange.Columns.Count
Dim strVal As String
Dim Item(0 To 99) As String
Dim header As Range
Dim rng As Range
For Each rngCell In Range(Cells(1 + i, 1), Cells(last_row, 1))
i = i + 1
strVal = rngCell.Text
If Not dict.Exists(strVal) Then
n = 0
For Each headerCell In Range(Cells(i, 2), Cells(i, last_col))
n = n + 1
Item(n) = headerCell.Text
'MsgBox headerCell.Text
Next headerCell
dict(strVal) = Item
Else
MsgBox "already exists"
End If
Next rngCell
Dim Items(0 To 99) As String
sFruit = InputBox("Check value of key")
Items = dict(sFruit)
MsgBox "The value of " & sFruit & " is " & Items(2)
It's the last part that isn't working. Whether I declare Items as Variant or String or Object or even if I put Item = Items(2) above the message box and refer to that. I can't get extract any kind of information out of an array retrieved from the dictionary.
dict("Apples") = 3usedict.Add "Apples", Array(3, 5)to store an array. To get this into a cell you need to write a code with the desired logic. For a good resource on dictionaries look at Excel VBA Dictionary – A Complete Guide. Note that SO is not a free code writing service, so give it a try yourself and if you get stuck or errors come back with your code or a minimal reproducible example.