Link to home
Start Free TrialLog in
Avatar of joyacv2
joyacv2Flag for Puerto Rico

asked on

how to verify if an item exists in a array using excel vba?

Hi,

I need a code to verify if an item exists in an array. Then if exists do nothing, if doesn't exists then add to the array. Any idea?
Avatar of Martin Liss
Martin Liss
Flag of United States of America image

You can use a collection instead, Keys in a collection must be unique and you get error 457 if you try to add a duplicate. So you wouldn't do it this way but here's an example.


Dim MyCollection As New Collection

On Error Resume Next
MyCollection.Add "value 1", "Key 1"
MyCollection.Add "value 2", "Key 1"
If Err.Number = 457 Then
    MsgBox "Key already in collevtion"
End If

Open in new window

MyCollection.Count will be 1 at the end of the code.
Avatar of joyacv2

ASKER

Hi,

How a collection works, how i refer to an item later? How I know the dimension of the collection? How is different from an array? Thank You
Collections start at index 1 so this would return "Value 1" using the above code.

MsgBox MyCollection(1)
Avatar of joyacv2

ASKER

But how is differs from an array?

My problem is that all my codes are in arrays
Avatar of joyacv2

ASKER

In the code why value 2 gives an error if it's not equal to value 1?
ASKER CERTIFIED SOLUTION
Avatar of Martin Liss
Martin Liss
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of joyacv2

ASKER

EXCELLENT, THANK YOU FOR YOUR RESPONSE
In the code why value 2 gives an error if it's not equal to value 1?
Because it checks the keys and not the values, so if you want to check for duplicate values make the key the same as the value. In other words

Dim MyCollection As New Collection

On Error Resume Next
MyCollection.Add "value 99", "value 99"
MyCollection.Add "value 1", "value 1"
MyCollection.Add "value 1", "value 1"
If Err.Number = 457 Then
    MsgBox "Key already in collection"
End If

Open in new window


In case it's not clear, the generalized code is

MyCollection.Add <some value>,<some key that must be a string>
You're welcome and I'm glad I was able to help.

Marty - MVP 2009 to 2013
BTW one more example. You don't have to use a key so this is perfectly valid and you wind up with 2 items in the collection.

Dim MyCollection As New Collection

On Error Resume Next

MyCollection.Add "value 1"
MyCollection.Add "value 1"

Open in new window

Avatar of joyacv2

ASKER

PERFECT, SO USING THE SAME SOLVE MY PROBLEM!
There's also a more advanced type of collection called a Dictionary but I don't have much experience with them.
Avatar of joyacv2

ASKER

for me, collection is new, i am working right with it, and works perfect!