Excel VBA - looping formula array and pass it into variables

i'm working on an exercise where i have the following columns

  • first column for primary key
  • second column for open date
  • third column for open price
  • fourth column for close date
  • fifth column for close price

The primary key will repeat multiple time due to different open date and close date through the year. So currently i'm able to use advance filtering function through vba and get an unique record of primary key, but i also need to find the min and max of open date and close date based on each primary key and identify the open price based on min of open date and closed price based on max of closed date.

can anyone help? because i can solve this with array formula within excel but no luck of converting each array formula into vba and pass it to variables.

sample list:

sample list

expected result:

expected result

array formulas used:

=MIN(IF(A1:A70926=J2,B1:B70926))

=INDEX(C:C,MATCH(1,(J2=$A:$A)*(M2=$B:$B),0))

=MAX(IF($A:$A=J2,$B:$B))

=INDEX(F:F,MATCH(1,(J2=$A:$A)*(O2=$B:$B),0))

1 answer

  • answered 2018-05-16 07:04 QHarr

    I am not entirely clear on which max and mins you want but provided you convert your date strings to actual dates, you can use a pivottable to get any combination of max, mins from the date e.g.

    Example

    With the above:

    Helper column F has the formula in F2, which autofills down as source is set up as Excel table.

    =DATE(LEFT(B2,4),MID(B2,5,2),RIGHT(B2,2))
    

    This generates an actual date.

    Pressing Ctrl+T, with a cell selected in the range, convertes the data into an Excel table, then Alt+N+V generates a pivottable from that table.

    Then arrange as you wish. For example, with date in the rows area you can easily then select max and min dates via filter. You can have ticker either as a page field filter or add to the rows in front of the converted date. And then add open and closed fields to the values area. You can add the same field more than once. Make sure to right click on the first time you add and do value > field settings > min

    value field settings

    Min

    Repeat for adding the same field and set as max.

    Close up on pivot:

    Pivot


    If you want the all time max and min value, simply remove the date field from the rows:

    Example


    If you want for a particular year, when date field is in the rows area, right click and use the date filters functionality:

    Date filters