Skip to main content

Scripting.Dictionary

I recently saw this used in a script and thought it was pretty interesting.  It allows you to use a dictionary in IDEAScript which could be very useful.

'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 an integer or a string, but can be anything except an array.

'Source: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dictionary-object

Option Explicit

Sub Main
	'create the object
	Dim dict As Object
	Set dict = CreateObject("Scripting.Dictionary")
	
	'adding items to the dictionary
	'an error occurs if they key already exists
	dict.Add "1", "one"
	dict.Add "2", "two"
	dict.Add "3", "three"
	dict.Add "4", "four"
	
	'how to check if key exists
	If dict.exists("1") Then
		MsgBox "Key already exists"
	End If
	
	If Not dict.exists("5") Then
		MsgBox "Key does not exist"
	End If
	
	'how to create an array containing all the items in the dictionary object
	
	Dim items As Variant
	Dim i As Long
	items = dict.Items 'get the items from the dictionary
	For i = 0 To dict.count -1 'iterate through the array
		MsgBox items(i) 'print the item
	Next i
	
	'how to create an array containing all the keys in the dictionary object
	
	Dim keys As Variant
	keys = dict.keys 'get the keys from the dictionary
	For i = 0 To dict.count - 1 'iterate through the array
		MsgBox keys(i) 'print the key
	Next i
	
	'how to remove a key
	dict.remove "3"
	keys = dict.keys 'get the keys from the dictionary
	For i = 0 To dict.count - 1 'iterate through the array
		MsgBox keys(i) 'print the key
	Next i
	
	'how to clear the dictionary
	dict.RemoveAll
	For i = 0 To dict.count - 1 'iterate through the array
		MsgBox keys(i) 'print the key
	Next i

End Sub