Introduction.
Last week’s introduction to Dictionary Object was, I hope, a good start and informative for this week's topics and to learn the fundamentals of this Object’s usage in Programs. The sample VBA Code presented there demonstrates the usage of a few Properties and Methods in the simplest form and I presume that you have already tried them out.
If not, visit last week’s page by following this link: Dictionary Object Basics before continuing.
The list of Properties and Methods given below was familiarized through last week’s demonstration programs. You may click the above link for a review if needed, or for a fresh look at it before continuing with this page.
The list of Properties and Methods we tried out in last week's VBA programs.
1. Property
- CompareMode
2. Methods
- Add
- RemoveAll
- Exists
- Keys
- Items
Now, let us try out the following Properties and Method, which remains to try out and find out how they work in the programs:
1. Properties
- Item - Retrieve/Replace/Add Item Value of the specified Key.
- Key - Replaces the Item Key with the new Key-Value specified.
- Count – Returns Item Count
2. Method
- Remove – Removes the specific Dictionary Item that matches the Key.
There are some similarities in the property names and methods: Key and Keys, Item and Items, Remove and RemoveAll. They do different things but are easier to remember because of their similarities in names.
The Item Property.
First, we will take the Item Property to try out. Item is a multipurpose Property Procedure and works for more than one function.
- It retrieves the Item value for output purposes. Key-Value is Item Parameter.
Example:
- It replaces an Item value, matching the specified Item Key.
Example:
- If the specified Key is not found, then add the given Key and Value pair to the Dictionary Object, as a new Item. It works like the d.Add the statement, if the Key provided doesn’t match with any Key in Dictionary Object.
Example:
Debug.Print d.Item("Canada")OR
x = d.Item("Canada") Result: x = "Ottawa"
d.Item("Canada") = "Alberta" ‘ Ottawa replaced with Alberta
d.Item("Kanada") = "Ottawa" ‘the Key misspelled as Kanada
We will bring the sample code, we used earlier for demo runs, here.
The Sample Code with Item Property Procedure.
Public Sub Dict_Test0_3() Dim d As Dictionary Dim mkey, j As Long Dim strheader As String Set d = New Dictionary 'Set Key-Text Compare Mode d.CompareMode = 1 'Text Compare(nancy = NANCY = Nancy = NaNCy) 'Syntax: obj.Add "Key", "Content" 'Countries and Capitals d.Add "Australia", "Canberra" d.Add "Belgium", "Brussels" d.Add "CANADA", "ALBERTA" d.Add "Denmark", "Copenhagen" d.Add "France", "Paris" d.Add "Italy", "Rome" d.Add "Saudi Arabia", "Riyadh" d.Add "USA", "Washington D.C." strheader = "*** LISTING BEFORE CHANGE ***" GoSub print_section 'Replace ALBERTA with Ottawa d.item("Canada") = "Ottawa" 'Trying to replace Item Value of 'non-existend Key: India 'This action will ADD a new Item to Dictionary. d.item("India") = "New Delhi" strheader = "*** LISTING AFTER CHANGE ***" GoSub print_section d.RemoveAll 'clear Dictionary Object from memory Exit Sub print_section: Debug.Print Debug.Print strheader Debug.Print "S.No.", "Country", "Capitals" Debug.Print "-----", "-------", "---------" j = 1 For Each mkey In d.Keys Debug.Print j, mkey, d.item(mkey) 'RETRIEVES Value j = j + 1 Next Return End Sub
All three actions: Retrieval, Replace & Add demonstrates in the above Code.
We have added eight Items to the Dictionary Object. I have changed the Capital City of Canada to ALBERTA, in place of the actual Capital, Ottawa, to try out the Replace action.
Immediately after the series of eight Add statements we are called the print_section sub-routine to take a listing of the unchanged items in Debug Window, from Dictionary Object d.
In the print_section sub-routine, within the For. . . Next Loop, find the expression d.item(mkey) that calls the Item Property Procedure with the Key parameter (Country Name) to retrieve the Capital name of each country and print it, along with the serial number and Country Name, in the Debug Window.
The next executable statement d.Item(“Canada”) = “Ottawa” searches through the list of Keys, for Canada, finds the item, and replaces the wrong capital Alberta with Ottawa. When we call the print_section again the change will appear in the listing of Countries and Capitals.
The next executable statement d.Item(“India”) = “New Delhi” is to watch for its effect. This statement is similar to the replacement statement, we have used for replacing Canada’s capital Ottawa. When the search for Key India fails, it will not generate any error, indicating that the search for the Key failed, but it silently adds unmatched Key India and Item value New Delhi to the Dictionary Object as a new item.
In the next step, we call the print_section sub-routine again to take the changed listing of items in the Debug Window. The d.RemoveAll statement deletes the Dictionary Object from memory before stopping the program.
Look for the following changes in the new listing of items in the Debug Window:
- Canada’s Capital is changed from Alberta to Ottawa.
- India and the New Delhi pair are added as a new Item, in Dictionary Object, as Key and Item Value respectively.
Note: The negative aspect of this particular behavior is that if you make a spelling mistake in the Key value you can easily add a wrong item to the list and you will not know about it either.
A workaround is that run a validation check on the Key-Value before attempting to run the value replacement statement, like the sample code below:
strKey="India" If d.Exists(strKey) Then d.Item(strKey)="New Delhi" Else MsgBox "Key: " & strKey & " Not Found!" End If
Remove, Key, and Count Property Procedures.
In the next Program, we will try out the usage of Remove Method, Key, and Count Property Procedures.
The Remove method deletes an Item from Dictionary Object. Searches for the Key finds it and deletes the Item from Dictionary.
Usage Example: d.Remove "Canada"
The Key Property procedure is good for editing a Key, accepts a key value as Parameter, finds, and replaces the old key with the new one.
Usage Example: d.Key("Kanada")="Canada"
The Count Property Procedure returns a count of the total number of items in the Dictionary Object.
Usage example: i = d.Count
Let us make a copy of the first VBA Code and try out the above method and property procedures in the VBA Code.
Modified Code.
Public Sub Dict_Test0_4() Dim d As Dictionary Dim mkey, j As Long Dim strheader As String Set d = New Dictionary 'Set Key-Text Compare Mode d.CompareMode = 1 'Text Compare(nancy = NANCY = Nancy = NaNCy) 'Syntax: obj.Add "Key", "Content" 'Countries and Capitals d.Add "Australia", "Canberra" d.Add "Belgium", "Brussels" d.Add "KANADA", "Ottawa" d.Add "Denmark", "Copenhagen" d.Add "France", "Paris" d.Add "Italy", "Rome" d.Add "Saudi Arabia", "Riyadh" d.Add "USA", "Washington D.C." 'the d.Count statement adds Item count to the header strheader = "BEFORE CHANGE - " & "TOTAL ITEMS: " & d.Count GoSub print_section 'Correction to Key value Kanada changes to Canada d.key("Kanada") = "Canada" 'With the following two statement 'an Item is replaced with a new Key. 'This has the same effect as deleting an Item 'and Adding another item in the same place mkey = "France" If d.Exists(mkey) Then d.key(mkey) = "India" d.item("India") = "New Delhi" Else MsgBox "Key: " & mkey & " Not Found!" End If 'Remove the Item Denmark from Dictionary Object mkey = "Denmark" If d.Exists(mkey) Then d.Remove mkey Else MsgBox "Remove Key: '" & mkey & "' Invalid." & vbCr & "Item not Removed!" End If 'the d.Count statement adds Item count to the header strheader = "AFTER CHANGE - " & "TOTAL ITEMS: " & d.Count GoSub print_section d.RemoveAll 'clear Dictionary Object from memory Exit Sub print_section: Debug.Print Debug.Print strheader Debug.Print "S.No.", "Country", "Capitals" Debug.Print "-----", "-------", "---------" j = 1 For Each mkey In d.Keys Debug.Print j, mkey, d.item(mkey) 'RETRIEVES Value syntax: d.item(mkey) j = j + 1 Next Return End Sub
The d.Remove Property Procedure requires a valid Key parameter with/without brackets. If not found among a list of Keys then it will end up with Errors. We perform a validation check, to ensure that the Key exists in the Dictionary Object, before attempting to delete the Item.
The d.Key statement also needs a valid Key-value, otherwise, it will end up with errors. So, we perform a validation check in the following Code segment to ensure that the key exists in the Dictionary before attempting to replace the Key with another value. If the specified key is not found, then gives a message to that effect, to safeguard against the crash of the program.
mkey = "France" If d.Exists(mkey) Then d.key(mkey) = "India" d.item("India") = "New Delhi" Else MsgBox "Key: " & mkey & " Not Found!" End If
With the combination of d.Key() and d.Item() statements, in the above code snippet, we can completely replace an unwanted item, by overwriting its Key and Item Value.
Unlike the Collection Object, the power lies in the Keys of the dictionary Object. The Key enables us to retrieve an Item randomly and quickly from Dictionary Object. Besides that, the Dictionary Object has a rich collection of Methods and Property Procedures to manage its contents.
MS-ACCESS CLASS MODULE
- MS-Access Class Module and VBA
- MS-Access VBA Class Object Arrays
- MS-Access Base Class and Derived Objects
- VBA Base Class and Derived Objects-2
- Base Class and Derived Object Variants
- Ms-Access Recordset and Class Module
- Access Class Module and Wrapper Classes
COLLECTION OBJECT
- Ms-Access and Collection Object Basics
- Ms-Access Class Module and Collection Object
- Table Records in Collection Object and Form
DICTIONARY OBJECT
- Dictionary Object Basics
- Dictionary Object Basics-2
- Sorting Dictionary Object Keys and Items
- Display Records from Dictionary to Form
- Add Class Objects as Dictionary Items
- Update Class Object Dictionary Item on Form
No comments:
Post a Comment
Comments subject to moderation before publishing.