Thread: VBA Collections
View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Chip Pearson Chip Pearson is offline
external usenet poster
 
Posts: 7,247
Default VBA Collections

You can't read the key of a item in a Collection. It is write-only.
You could use a Dictionary instead.

Cordially,
Chip Pearson
Microsoft Most Valuable Professional
Excel Product Group, 1998 - 2009
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)

On Fri, 21 Aug 2009 16:31:35 +0200, "JP Ronse"
wrote:

Hi Rick,

Thanks for your reply.

Trying to assist someone over here with some VBA code (generating 1000
random numbers between 1 and 100 and take the top 20), I used the random
number as key, and as item the number of times the same random number was
generated.

My first thought was, if I take each item from the collection and if I
should read the key, I know - per key - the number of occurences.

Your answer: "... the assumption is that you *know* which Key ..." did me
think a bit further. You are completely right herein and I do know the keys:
they are between 1 and 100. So I can walk through to get the occurences.

A little bit ashamed to make such beginners fault, but thanks for your time
and to bring me back on the right track.

Wkr,

JP


"Rick Rothstein" wrote in message
...
The idea of assigning a Key is so that you can use it in place of knowing
or having to track the position number of your item within the collection
(especially since the position number can change with deletions of items
ahead of the item), so the assumption is that you *know* which Key you are
using to track any particular item. To the best of my knowledge, there is
no way to retrieve the Key assigned to an item in code... and, quite
frankly, I can't think of a scenario where being able to do so would be
needed. Can you explain why you think you would need to do what you have
asked (perhaps we can suggest an alternative to you)?

--
Rick (MVP - Excel)


"JP Ronse" wrote in message
...
Hi All,

Is there a method to get the used key back from a collection?

Suppose you have some (very stupid code) like this:

set c = new collection

c.add item:=1, key:="A"
c.add item:=2, key:="B"
c.add item:=3, key:="C"

How to know which key was used for c(1), c(2)...

TIA.

Wkr,

JP