new to vba, and wonder how to address elements within a range.
I add range of cells (rows) indexed with an id to a dictionary
Set spRange = import.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
dict.Add cell.Offset(0, 2).Text, cell.Row
Next cell
later on, I retrieve the row, and need to access value of first element.
For Each x In dict
Set spRange = dict.Item(x)
'how to get value of first element of spRange
Next
It could be very easy for u, but i am not familiar with api 🙂
thanks
bsreekanth
The Dictionary object, if I am not wrong first came out way back in 1996 as part of VB Script 2 and was later added to the VB Scripting run-time library (scrrun.dll). To work with the Dictionary object, you have to add a reference to Microsoft Scripting Runtime.
The syntax of adding item to dictionary is
The key has to be unique else you will get an error. Let’s cover different scenarios to understand how it works.
Let’s take an example
We store the row (and not the cell text) and then retrieve the row number
If you noticed that I am using the variable “j” to create unique keys and then storing the row values.
To retrieve the stored row values, I am then looping through the Dictionary Objects.
Now back to your question.
This is the part where I am kind of confused. Reason being, if you wanted just to get the value of a particular row in range spRange then why are you using a dictionary object?
You can directly get the value using this code
If you still would like to use a dictionary object then you can use the below code
And If your intention is to store the range values in the dictionary and then retrieve the value based on a particular key (Row Number) then you can use this code
Now one last point. If you are not going to loop through the Dictionary object to retrieve the values but are planning to use something like “Debug.Print Dict(2)” then I would suggest using an extra piece of code which first checks if the element is present or not and then shows it. For example
HTH
Let me know if you have any questions.
Sid