MrGadget2000
New Member
- Joined
- Sep 29, 2021
- Messages
- 6
- Office Version
- 365
- Platform
- Windows
I'm trying to use a dictionary (new to these) and it appears to record the data correctly, however when I try to get the item for a particular key I get a blank result.
To show, I have the following in A1:C3;
And the code;
I was trying the same code with the addition of the CStr as another post indicated this as a potential solution, however it makes no difference to the outcome.
No matter what I try, I don't seem to be able to get the qty of a fruit.
I'm sure it's a simple resolution but by use of Dictionaries is just starting.
Cheers
To show, I have the following in A1:C3;
Apples | Red | 5 |
Bananas | Yellow | 2 |
Oranges | Orange | 3 |
And the code;
VBA Code:
Sub testdict()
Dim lastrow As Long
Dim cnt As Long, fruit As String
Dim dict As New Scripting.Dictionary
lastrow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
'Set dictionary Items
For n = 1 To lastrow
dict.Add Key:=Range("A" & n), Item:=Range("C" & n)
Next n
'Print Debug Items to immediate - this works;
'Apples 5
'Bananas 2
'Oranges 3
For i = 0 To dict.Count - 1
Debug.Print dict.Keys(i), ; dict.Items(i)
Next i
fruit = "Bananas"
cnt = dict(Bananas)
Debug.Print "Dict="; dict("Bananas") ' is blank result
Debug.Print "Dict 'fruit'="; dict(fruit) ' is blank result
Debug.Print "Dict CStr'fruit'="; dict(CStr(fruit)) ' is blank result
Debug.Print "Dict="; CStr(dict("Bananas")) ' is blank result
Debug.Print "cnt=", cnt ' is 0
Debug.Print "cnt (CStr)=", CStr(cnt) ' is 0
End Sub
I was trying the same code with the addition of the CStr as another post indicated this as a potential solution, however it makes no difference to the outcome.
No matter what I try, I don't seem to be able to get the qty of a fruit.
I'm sure it's a simple resolution but by use of Dictionaries is just starting.
Cheers