Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Associative Arrays In VB

Status
Not open for further replies.

gharabed

Programmer
Joined
Sep 7, 2001
Messages
251
Location
US
Is there such an animal as an associative array in VB? In other words an index into an array with a value other than an integer...for example

myArr("Toyota") = "Red"
myArr("Nissan") = "Blue"
myArr("Ford") = "White"
myArr("Chevy") = "Purple"

you get the idea...is it possible to do this in VB?

Greg
 
Yes - it's called a collection.

But collections have a interesting "feature". If you try and access the contents with an index that just happens to be a number (even if you surround it with cstr()), it treats the number as an index, and you can get "Index out of range" errors.

A better way if you suspect your values might be numeric is to use the dictionary object from the scripting library (you'll have to set a reference to it). The dictionary object isn't perfect either -- if you try and find an object in it that isn't there, it will add your search term to it's list. You need to use the .Exists() method to see if an item is in there before retrieving it.

Chip H.
 
You can also use the Dictionary object. It has the advantage that you can change the value of an item without using REMOVE and ADD, check if an item exists with the EXISTS property, save the Dictionary in two paralell arrays using the KEYS amd ITEMS methods.

You can use the ADD method or just create a new item "on the fly" with
Code:
Dim myArr as New Scripting.Dictionary

myArr.CompareMode = vbTextCompare ' Key is Case insensitive
myArr("Toyota") = "Red" ' or myArr.Item("Toyota") = "Red" 
myArr("Nissan") = "Blue"
myArr("Ford") = "White"
myArr("Chevy") = "Purple"

myArr("Toyota") = "Maroon" ' My girlgriend says it isn't Red
if myarr(1) = "Maroon" then
    .....
End if
Dim aryItems as Variant ' must be variant, not () As Variant
Dim aryKeys as Variant
aryKeys = myarr.Keys
aryItems = myarr.Items
The disadvantage is that you must include the SCRRUN.DLL for those user who don't have it.

"Scripting.Dictionary

Remarks

A Dictionary object is the equivalent of a PERL associative array. Items, which can be any form of data, are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top