Setting the Item property of a Collection in VBA - vba

I'm surprised at how hard this has been to do but I imagine it's a quick fix so I will ask here (searched google and documentation but neither helped). I have some code that adds items to a collection using keys. When I come across a key that already exists in the collection, I simply want to set it by adding a number to the current value.
Here is the code:
If CollectionItemExists(aKey, aColl) Then 'If key already has a value
'add value to existing item
aColl(aKey).Item = aColl(aKey) + someValue
Else
'add a new item to the collection (aka a new key/value pair)
mwTable_ISO_DA.Add someValue, aKey
End If
The first time I add the key/value pair into the collection, I am adding an integer as the value. When I come across the key again, I try to add another integer to the value, but this doesn't work. I don't think the problem lies in any kind of object mis-match or something similar. The error message I currently get is
Runtime Error 424: Object Required

You can't edit values once they've been added to a collection. So this is not possible:
aColl.Item(aKey) = aColl.Item(aKey) + someValue
Instead, you can take the object out of the collection, edit its value, and add it back.
temp = aColl.Item(aKey)
aColl.Remove aKey
aColl.Add temp + someValue, aKey
This is a bit tedious, but place these three lines in a Sub and you're all set.
Collections are more friendly when they are used as containers for objects (as opposed to containers for "primitive" variables like integer, double, etc.). You can't change the object reference contained in the collection, but you can manipulate the object attached to that reference.
On a side note, I think you've misunderstood the syntax related to Item. You can't say: aColl(aKey).Item. The right syntax is aColl.Item(aKey), or, for short, aColl(aKey) since Item is the default method of the Collection object. However, I prefer to use the full, explicit form...

Dictionaries are more versatile and more time efficient than Collections. If you went this route you could run an simple Exists test on the Dictionary directly below, and then update the key value
Patrick Matthews has written an excellent article on dictionaries v collections
Sub Test()
Dim MyDict
Set MyDict = CreateObject("scripting.dictionary")
MyDict.Add "apples", 10
If MyDict.exists("apples") Then MyDict.Item("apples") = MyDict.Item("apples") + 20
MsgBox MyDict.Item("apples")
End Sub

I think you need to remove the existing key-value pair and then add the key to the collection again but with the new value

Related

Is this an incorrect way of iterating over a dictionary?

Are there any problems with iterating over a dictionary in the following manner?
Dim dict As New Dictionary(Of String, Integer) From {{"One", 1}, {"Two", 2}, {"Three", 3}}
For i = 0 To dict.Count - 1
Dim Key = dict.Keys(i)
Dim Value = dict.Item(Key)
'Do more work
dict.Item(Key) = NewValue
Next
I have used it a lot without any problems. But I recently read that the best way to iterate over a dictionary was using a ForEach loop. This led me to question the method that I've used.
Update: Note I am not asking how to iterate over a dictionary, but rather if the method that I've used successfully in the past is wrong and if so why.
Are there any problems with iterating over a dictionary in the following manner?
Yes and no. Technically there's nothing inherently wrong with the way you're doing it as it does what you need it to do, BUT it requires unnecessary computations and is therefore slower than simply using a For Each loop and iterating the key/value-pairs.
Iterating keys, then fetching value
The Keys property is not a separate collection of keys, but is actually just a thin wrapper around the dictionary itself which contains an enumerator for enumerating the keys only. For this reason it also doesn't have an indexer that lets you access the key at a specific index like you are right now.
What's actually happening is that VB.NET is utilizing the extension method ElementAtOrDefault(), which works by stepping through the enumeration until the wanted index has been reached. This means that for every iteration of your main loop, ElementAtOrDefault() also performs a similar step-through iteration until it gets to the index you've specified. You now have two loops, resulting in an O(N * N) = O(N2) operation.
What's more, when you access the value via Item(Key) it has to calculate the hash of the key and determine the respective value to fetch. While this operation is close to O(1), it's still an unnecessary additional operation compared to what I'm talking about below.
Iterating key/value-pairs
The dictionary already has an internal list (array) holding the keys and their respective values, so when iterating the dictionary using a For Each loop all it does is fetch each pair and put them into a KeyValuePair. Since it is fetching directly by index this time (at a specific memory location) you only have one loop, thus the fetch operation is O(1), making your entire loop O(N * 1) = O(N).
Based on this we see that iterating the key/value-pairs is actually faster.
This kind of loop would look like (where kvp is a KeyValuePair(Of String, Integer)):
For Each kvp In dict
Dim Key = kvp.Key
Dim Value = kvp.Value
Next
See here:
https://www.dotnetperls.com/dictionary-vbnet
Keys. You can get a List of the Dictionary keys. Dictionary has a get accessor property with the identifier Keys. You can pass the Keys to a List constructor to obtain a List of the keys.
It cites an example similar to yours:
Module Module1
Sub Main()
' Put four keys and values in the Dictionary.
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add("please", 12)
dictionary.Add("help", 11)
dictionary.Add("poor", 10)
dictionary.Add("people", -11)
' Put keys into List Of String.
Dim list As New List(Of String)(dictionary.Keys)
' Loop over each string.
Dim str As String
For Each str In list
' Print string and also Item(string), which is the value.
Console.WriteLine("{0}, {1}", str, dictionary.Item(str))
Next
End Sub
End Module

A null reference could result in runtime

Dim policy_key() As RenewalClaim.PolicyKeyType
policy_key(0).policyEffectiveDt = date_format_string(ld_EffectiveDate)
Getting error at Line2.
An Error occured - Object reference not set to an instance of an object.
Each element of object arrays also needs to be declared as a new object too.
Dim policy_key() As RenewalClaim.PolicyKeyType
Redim policy_key(0)
policy_Key(0) = new RenewalClaim.PolicyKeyType
policy_key(0).policyEffectiveDt = date_format_string(ld_EffectiveDate)
QUICK TIP: When declaring classes structures etc, it is useful to name them so you can see what type they are....
e.g.
cls_Policy_Key for a class
str_Policy_Key for a structure etc.
When you come back to your code after a year.. you will thank yourself for doing so.
Dim policy_key() As RenewalClaim.PolicyKeyType
is part of your problem. When you are declaring policy_key() you are actually declaring it as an array with no elements. If you don't particularly need to use an array, for example, if you don't need to add objects to a particular element number, you might be better using a list and declaring it like this
Dim policy_key As New List(Of RenewalClaim.PolicyKeyType)
This way, you can add items easily without having to resize your array each time - The code is a little longer than Trevor's answer, but less prone to errors when you extend your code -
dim newPolicy_Key as RenewalClaim.PolicyKeyType
newPolicy_Key.policyEffectiveDt = date_format_string(ld_EffectiveDate)
policy_Key.add(newPolicyKey)

Scope issue in Access VBA Dictionary?

I'm having a strange problem. I'm new to Access and VBA, so it may be a stupid mistake.
Private backColorCycle As Integer
Private doneRows As New Dictionary
Private Sub AlternateGroupColor()
If Not doneRows.Exists(Me.JCH_Shape) Then
'... some stuff that assigns a value to backColorCycle
Else
'... some stuff that assigns a value to backColorCycle
End If
doneRows.Item(Me.JCH_Shape) = backColorCycle
Detail.BackColor = QBColor(doneRows.Item(Me.JCH_Shape))
GroupHeader0.BackColor = QBColor(doneRows.Item(Me.JCH_Shape))
End Sub
AlternateGroupColor() is an event handler that is called repeatedly (by the OnFormat event in Access). Me.JCH_Shape, a string, cycles through a set of values twice: it might be A, B, C, A, B, C as the function is called, so I want to know when a value has been encountered already. I hoped to determine this by storing the value in doneRows and checking to see if the value already exists. However, even though I've checked that Me.JCH_Shape does indeed have different values and doneRows.Item(Me.JCH_Shape) does return the value I expect at the end of the function, doneRows.Count is never greater than 1. It seems as if the changes I make to the dictionary in the sub are reset every time it is called, and I'm not sure why. It feels like a scope problem, but I can't understand why this would happen to a variable that is a member of the class and not just the function.
Any help would be appreciated. Thanks.
A Dictionary allows objects to serve as its key. Me.JCH_Shape is an object on your report, so when you do
doneRows.Item(Me.JCH_Shape) = backColorCycle
you are repeatedly re-assigning the value to the Dictionary entry whose key is the Me.JCH_Shape object itself. If you want to store Dictionary items based on the current value of the Me.JCH_Shape object you need to use
doneRows.Item(Me.JCH_Shape.Value) = backColorCycle

Dynamically create variables in VB.NET

I have been trying to figure this out for some time now and can't seem to figure out an answer to it. I don't see why this would be impossible. I am coding in VB.NET.
Here is my problem:
I need to dynamically create variables and be able to reference them later on in the code.
More Details:
The number of variables comes from some math run against user defined values. In this specific case I would like to just create integers, although I foresee down the road needing to be able to do this with any type of variable. It seems that my biggest problem is being able to name them in a unique way so that I would be able to reference them later on.
Simple Example:
Let's say I have a value of 10, of which I need to make variables for. I would like to run a loop to create these 10 integers. Later on in the code I will be referencing these 10 integers.
It seems simple to me, and yet I can't figure it out. Any help would be greatly appreciated. Thanks in advance.
The best way to do something like this is with the Dictionary(T) class. It is generic, so you can use it to store any type of objects. It allows you to easily store and retrieve code/value pairs. In your case, the "key" would be the variable name and the "value" would be the variable value. So for instance:
Dim variables As New Dictionary(Of String, Integer)()
variables("MyDynamicVariable") = 10 ' Set the value of the "variable"
Dim value As Integer = variables("MyDynamicVariable") ' Retrieve the value of the variable
You want to use a List
Dim Numbers As New List(Of Integer)
For i As Integer = 0 To 9
Numbers.Add(0)
Next
The idea of creating a bunch of named variables on the fly is not something you are likely to see in any VB.Net program. If you have multiple items, you just store them in a list, array, or some other type of collection.
'Dim an Array
Dim xCount as Integer
Dim myVar(xCount) as String
AddButton Event . . .
xCount += 1
myVar(xCount) = "String Value"
'You will have to keep Track of what xCount Value is equal to to use.
'Typically could be an ID in A DataTable, with a string Meaning

Dictionary object adding items before .add() is called

I am using a dictionary object from the MS Scripting Runtime library to store a series of arrays and perform operations on the array cells as necessary. There is a for loop to go through the process of creating all of these entries. My issue is that when using the .exists property, it is returning True even before the item has been added.
Closer debugging indicates that the key is being added to the dictionary at the beginning of the for loop, even though no .add command is used and will not be used until the end of the loop.
I have tried a few different configurations, but here is a simple example that fails:
Dim dTotals As Dictionary
Set dTotals = New Dictionary
dTotals.CompareMode = BinaryCompare
For Each cell In rAppID
If Not dTotals.Exists(cell) Then
Set rAppIDCells = Find_Range(cell, rAppID)
Set rAppIDValues = rAppIDCells.Offset(0, 6)
dAppIDTotal = WorksheetFunction.Sum(rAppIDValues)
dTotals.Add Key:=cell.Value, Item:=dAppIDTotal
End If
Next cell
Where each cell contains a string / unique id. At the If statement, the code is returning false, even on the first iteration.
In the official documentation‌​ for the scripting runtime it says "If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty."
...and yea, when you're debugging in a loop, it appears to pop right out of the sky before the '.exists' function is even called. All is well...
Instead of attempting to add the item that just got added, as in:
dTotals.Add Key:=cell.Value, Item:=dAppIDTotal
...just set the empty object currently at your key to your new one:
dTotals(cell.Value) = dAppIDTotal
So your code block becomes:
If Not dTotals.Exists(cell) Then
Set rAppIDCells = Find_Range(cell, rAppID)
Set rAppIDValues = rAppIDCells.Offset(0, 6)
dAppIDTotal = WorksheetFunction.Sum(rAppIDValues)
dTotals(cell.Value) = dAppIDTotal
End If
Voila. I tend to rediscover this "feature" on every revisit to VBA. You may also notice the effects of it if you are having a memory leak caused by adding new keys that you do not intend to store.
I had this problem manifest itself while debugging when I had a watch that attempted to return the "missing" key's item. Actually, further frustrated debugging had the same problem when I literally had a watch for the [scriptingdictonaryObject].exists() condtional); I suggest that the "missing" key is added because of the watch. When I removed the watch and instead created a temporary worksheet to copy the array to while running, the unwanted keys were no longer added.