Home » excel » excel – Attempt retrieval of value from VBA dictionary and raise error if key not in use?

excel – Attempt retrieval of value from VBA dictionary and raise error if key not in use?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’ve used dictionaries (Whether they were called that or not) in a number of other languages, but there’s always been a method that can be called with on parameter that either:

A) Returns the associated value if the parameter is in use as a key, or
B) Indicates in some way that the parameter is not used as a key

I’ve been forced into a position where I have to learn excel/VBA and used the collections class for all of about five minutes before the lack of an .exists method led me to look for something else. The general consensus seems to be that the scripting.Dictionary class is the VBA equivalent of associative arrays/dictionaries/hashtables in other languages.

The one thing I don’t like the look of though is that the only way I can see of retrieving the value associated with a given key is to use the .items property (either explicitly, or via scripting.Dictionary(“key”)). But rather than doing anything to indicate the issue if key is not in use in the dictionary, it adds it.

I know I can use a if structure with .exists being the test to achieve the same functionality, and can write my own function that raises an error if the exists test fails, but it seems a lot of stuffing around to achieve what is core functionality in Python (raises KeyError), PHP (raises a Notice), Java (Maps return null – although that is not necessarily ideal in the case of HashMaps where null actually is a valid value – but it does work as an indicator for HashTables).

So is there any way of attempting to retrieve a value by key that will do something (ideally throw an error) if the key is not in use, rather than silently adding it? Google hasn’t provided any answers – but maybe I’m just not phrasing the search well.

How to&Answers:

I find it inconvenient too that Dictionary adds the key when you access a non-existing key.

Just use Collection and write the missing Exist function yourself, e.g.

Function ExistsInCollection(ByVal c As Collection, ByVal key As Variant) As Boolean
  On Error GoTo not_exists
  c.Item key
  ExistsInCollection = True
not_exists:
End Function