Home » excel » excel – VBA: creating pivotTable from a collection or use a better algorithm?

excel – VBA: creating pivotTable from a collection or use a better algorithm?

Posted by: admin April 23, 2020 Leave a comment


I was wondering how, or if at all possible, to create a pivotTable using VBA given a collection. Or improve on the current algorithm for my code.

Currently, I have a collection with about 28000 items. Each item has an unique Id, item number, and price. I want to generate a new collection with the unique Id, part number that has the lowest price. So I was thinking generating the pivotTable will aggregate all the item numbers, and find minimum price. Then based on that table, I can generate a new collection, or should I improve on the algorithm I have?

For example:

item[unique_id]: item number, price

Item[1]: 11111, 10
Item[2]: 22222, 2
Item[3]: 11111, 3
Item[4]: 11111, 15
Item[5]: 22222, 1
Item[6]: 33333, 2

and then the result collection would be something like:

Item[3]: 11111, 3
Item[5]: 22222, 1
Item[6]: 33333, 2

Currently, I have code that does the following to create that new collection

For Each Item in OriginalCollection

    ' Temp item holder for comparison
    Set minItem = item
    i = 1

    Do While (i <= OriginalCollection.Count)
      if OriginalCollection(i).itemNumber = minItem.itemNumber And OriginalCollection(i).price < minItem.price Then
        Set minItem = OriginalCollection(i)

        ' reduce the size of collection, so fewer iterations
        OriginalCollection.Remove (i)
        OriginalCollection.Remove (minItem.Id)
      End if
      i = i + 1

    If Not InCollection (MinCollection, minItem.Id) Then
        MinCollection.Add minItem, minItem.Id
    End If
Next item

Thank you in advance.

How to&Answers:

Anytime I need to accomplish what you’re seeking, I just sort the table by item number, then price. I’m assuming your data are in cells A1:C28000. In a neighboring column’s cell, starting with D2, I enter the formula: =if(b2=b1,"",1). This tells me when there’s a change in item number. And every time there’s a change in item number, I know I’ve found the cheapest price for the new item (because each group of item numbers is sorted by ascending price). Copy that formula in column D down the length of your item list.

Turn on your auto-filter and filter for where values in column D=1. Those are all of your lowest prices for each item. (adjust for if your very first item doesn’t have a duplicate; i.e., just add column headers)

This approach doesn’t use pivot tables, but based on your problem description, I’m not sure you need them.