Friday 25 October 2013

How to create and use dictionary object in excel macro


Sub createDictionary()
'Please note that to use dictionary in your project, you will have to add reference of microsoft script runtime

Dim d1 As Scripting.Dictionary
'Dictionary object allows you to store the elements in dynamic way using keys.
'Unlike arrays where values are stored using index, dictionary uses keys to store values

'To add key in dictionary, use below code
Set d1 = New Scripting.Dictionary
d1.Add "sachin", 41
d1.Add "dhoni", 32

'To get the value at particular key
MsgBox d1.Item("sachin")

'to remove key from dictionary
d1.Remove "dhoni"

'To get all keys from the dictionary, use below code
keyArray = d1.Keys


'to check if given key exists in the dictionary
If d1.Exists("sachin") Then
    MsgBox "Key sachin exists"
Else
    MsgBox "Key sachin does not exist"
End If

'To remove all keys from dictionary, use below code
d1.RemoveAll


'this is how you can use dictionary object in excel macro
'You can store the values from 2 columns as key value pair in dictionary
End Sub

What do you think on above excel macro topic? Please provide your input, comments, questions on excel macro. I will try to reply as soon as possible. I value your opinion on Excel Macros.

1 comment:

  1. Good one, I want to know more about dictionary object

    ReplyDelete

Popular Posts

Search This Blog