Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify if an object is a Collection or Dictionary?

I have a nested tree of nodes that are either Dictionaries or Collections (I don't have control over this structure - it is given to me). How can I seperate Dictionary nodes from Collections?

I observe there exists an IsArray() function, but no IsCollection or IsDict()

like image 497
mchen Avatar asked Jul 23 '13 22:07

mchen


People also ask

What is the difference between collection and dictionary in VBA?

You can assign a Key to an Item when you add the Item to the Collection, but you cannot retrieve the Key associated with an Item nor can you determine (directly) whether a key exists in a Collection. Dictionaries are much friendly and open with their keys. Dictionaries are also considerably faster than Collections.

What is a Dictionary in VBA?

A dictionary is an object in VBA (similar to a collection) that stores data like an array. It can be used to store data of any type except an array. A VBA dictionary has two parts: Key. Value.


2 Answers

Sub TestingType()
    Dim col As New Collection
    Dim dic As New Scripting.Dictionary

    Debug.Print TypeName(col)   'Collection
    Debug.Print TypeName(dic)   'Dictionary

End Sub
like image 197
Andy G Avatar answered Oct 08 '22 17:10

Andy G


Try something like this:

If TypeOf YourObjectVariable Is Dictionary Then
    ' ...
ElseIf TypeOf YourObjectVariable Is Collection Then
    ' ...
Else
    ' Handle empty/other types here.
End If

You could use something like this to control the flow of execution in your code, or make your own IsCollection() and IsDictionary() functions.

like image 32
Monty Wild Avatar answered Oct 08 '22 19:10

Monty Wild