Search notes:

VBA: dictionaries and objects

Here are two examples that try to demonstrate how objects can be used as values or keys in dictionaries.

Values are objects

option explicit

public num as long
public txt as string

sub init(n as long, t as string) ' {

    num = n
    txt = t

end sub ' }
Github repository about-VBA, path: /object-libraries/microsoft-scripting-runtime/dictionary/dict-of-obj/obj.cls
option explicit

sub main() ' {

    dim dict as new dictionary

    dim ob as obj

    set ob = new obj : ob.init 42, "Hello world" : dict.add "one"  , ob
    set ob = new obj : ob.init 99, "ninety-nine" : dict.add "two"  , ob
    set ob = new obj : ob.init 21, "1+2+3+4+5+6" : dict.add "three", ob

    iterateOverKeys dict

end sub ' }

sub iterateOverKeys(d as dictionary) ' {

    dim k as variant
    for each k in d ' {
        debug.print k & " -> " & d(k).num & ": " & d(k).txt
    next k ' }

end sub ' }
Github repository about-VBA, path: /object-libraries/microsoft-scripting-runtime/dictionary/dict-of-obj/prog.bas

Keys are objects

This example uses the same object than the previous example, but uses the object to index strings rather than using strings to index objects:
option explicit

sub main() ' {

    dim dict as new dictionary

    dim ob as obj

    set ob = new obj : ob.init 42, "Hello world" : dict.add ob, "foo"
    set ob = new obj : ob.init 99, "ninety-nine" : dict.add ob, "bar"
    set ob = new obj : ob.init 21, "1+2+3+4+5+6" : dict.add ob, "baz"

    iterateOverKeys dict

end sub ' }

sub iterateOverKeys(d as dictionary) ' {

    dim k as variant
    for each k in d ' {
        debug.print k.num & ": " & k.txt & " -> " & d(k)
    next k ' }

end sub ' }
Github repository about-VBA, path: /object-libraries/microsoft-scripting-runtime/dictionary/dict-of-obj/obj-in-key.bas

Index