Home > Mobile >  Excel VBA Dictionary - access item using variable
Excel VBA Dictionary - access item using variable

Time:11-30

I have a class called person and a dictionary of people. I want to loop through each person in the People dictionary and check for errors. Is there a way of referencing the item in the library using similar to the below example. e.g. looping through the errors array and appending it to the item name instead of having to write a check for each individual error in the array?

Example code:

errors = array("A", "B", "C")

for each theError in errors 
     for each person in people
         if person.error & theError > 0  then
            debug.print theError  'e.g. A, B or C
         end if
     next person
next theError

CodePudding user response:

Use CallByName:

If CallByName(person, "error" & theError, vbGet) > 0 Then

CodePudding user response:

Basically, we want to group the Person objects by their error codes. My approach is to create a dictionary of errors with a collection of people for each error code.

Dim Errors As Variant
Errors = Array("A", "B", "C")

Dim ErrorMap As New Scripting.Dictionary
Dim Item As Variant
For Each Item In Errors
    ErrorMap.Add Item, New Collection
Next

Dim Person1 As Person
For Each Item In People.Items
    Set Person1 = Item
    
    If ErrorMap.Exists(Person1.Error) Then
        ErrorMap(Person1.Error).Add Person1
    End If
Next
  • Related