Tuesday, 27 August 2013

Remove Duplicates from VBA Array With Condition

Remove Duplicates from VBA Array With Condition

At the request of a user, I have rewritten this question with more
information and tried to clarify it as much as I possibly can.
I have code that reads a range into an array. Many calculations are
performed. The resulting array contains an ID and two values:
ID Seq Value
a 1 100
a 2 150
a 3 200
b 1 10
b 2 10
b 3 10
However, the calculation step uses Redim Preserve so I have to store the
array as TestArray(1 To 3, 1 To 6).
I need to filter the array for duplicate ID's.
If there is no duplicate, I need to store ID, seq and value.
If there is a duplicate ID, I need to store the ID, seq and value where
value is the maximum value for a given ID.
If there is a duplicate ID and there are multiple instances of a maximum
value, I want to keep the ID, date and value where the value is the
maximum value for a given ID and seq is the minimum seq for a given ID.
Basically, for each ID I want the maximum value and if there are multiple
maximums, default to the earliest sequence number.
This is a sample of code that shows how the array is structured and what I
need the results to look like.
Sub TestArray()
Dim TestArray() As Variant
Dim DesiredResults() As Variant
TestArray = Array(Array("a", "a", "a", "b", "b", "b"), _
Array(1, 2, 3, 1, 2, 3), _
Array(100, 150, 200, 10, 10, 10))
DesiredResults = Array(Array("a", "b"), Array(3, 1), Array(200, 10))
End Sub
Is there some way to loop through the array and find duplicates and then
compare them? I could do this easily in SQL but I am struggling in VBA.

No comments:

Post a Comment