Public Sub Product_Margin()
Columns("AA:AF").ClearContents
startTime = Timer
Application.Calculation = xlCalculationManual
Dim sum1 As Double
Dim sum2 As Double
Dim sum3 As Double
Dim counter As Double
LCol = ActiveSheet.Cells(3, Columns.Count).End(xlToLeft).Column
LRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
'INSERT NEW COLUMN TITLE
Cells(3, LCol + 1).Value = "PRODUCT_MARGIN"
'LOOP THROUGH TRANSACTIONS CALCLATING PRODUCT MARGIN
Dim ord_Arr, com_Arr, fis_Arr
Dim sum_1 As Range, sum_2 As Range
ord_Arr = Range("A4:A" & LRow).Value
com_Arr = Range("T4:T" & LRow).Value
fis_Arr = Range("R4:R" & LRow).Value
Set sum_1 = Range("F4:F" & LRow)
Set sum_2 = Range("Y4:Y" & LRow)
With CreateObject("Scripting.Dictionary")
For i = 1 To UBound(ord_Arr)
x = Join(Array(ord_Arr(i, 1), com_Arr(i, 1), fis_Arr(i, 1)), ",")
If Not .Exists(x) Then
sum1 = Application.SumIfs(sum_1, Range("A4:A" & LRow), ord_Arr(i, 1), Range("T4:T" & LRow), com_Arr(i, 1), Range("R4:R" & LRow), fis_Arr(i, 1))
sum2 = Application.SumIfs(sum_2, Range("A4:A" & LRow), ord_Arr(i, 1), Range("T4:T" & LRow), com_Arr(i, 1), Range("R4:R" & LRow), fis_Arr(i, 1))
sum3 = sum1
If sum3 = 0 Then
.Item(x) = 0
Else
.Item(x) = (sum1 - sum2) / sum3
End If
End If
Next
Dim pm_Arr As Variant
ReDim pm_Arr(1 To UBound(ord_Arr), 1 To 1)
For i = 1 To UBound(ord_Arr)
x = Join(Array(ord_Arr(i, 1), com_Arr(i, 1), fis_Arr(i, 1)), ",")
pm_Arr(i, 1) = .Item(x)
Next
End With
' Save results
Cells(4, LCol + 1).Resize(UBound(pm_Arr), 1) = pm_Arr
Range(Cells(4, LCol + 1), Cells(LRow, LCol + 1)).NumberFormat = "0.00%"
Debug.Print "New Time = ", Timer - startTime
Application.Calculation = xlCalculationAutomatic
End Sub