Same code with comments. Hopefully this helps explain what is going on and why:
Sub tgr()
'Declare variables
Dim rngB As Range 'The cells in column B to be looped through
Dim rngE As Range 'The cells in column E to find the max E value
Dim BCell As Range 'Variable used to loop through rngB
Dim ECell As Range 'Variable used to identify the cell containing the max value in rngE
Dim arrData(1 To 65000, 1 To 6) As Variant 'Array to build subtraction history
Dim DataIndex As Long 'Variable used to determine location in arrData
Dim dMax As Double 'Variable used to find the max value in rngE
Dim bNewMax As Boolean 'Boolean value used to determine if a new max value in rngE is necessary
'Define rngB and rngE
Set rngB = Range("B3", Range("B2").End(xlDown))
Set rngE = Range("E2", Range("E2").End(xlDown))
'Initiate loop for rngB
For Each BCell In rngB.Cells
'Initiate loop for while BCell is greater than 0
Do While BCell.Value > 0
'Check if a max value has been identified yet (necessary for first iteration)
bNewMax = (ECell Is Nothing)
'If a max value has already been identified, make sure that cell is not yet 0
If bNewMax = False Then bNewMax = (ECell.Value2 = 0)
'Max value has either not been identified, or that max value is now 0
'So a new max value is needed
If bNewMax = True Then
dMax = 0 'Reset dMax variable
'Use dMax to find the max value remaining in rngE
dMax = Evaluate("Max(If(" & rngE.Address & "<>0," & rngE.Address & "))")
If dMax = 0 Then Exit Do 'If the max value in rngE is 0, there are no more values to subtract
'Assign ECell to the location of dMax, because that cell is the new max value in rngE
Set ECell = rngE.Find(dMax, , xlFormulas, xlWhole)
End If
'Determine if ECell or BCell is larger
dMax = WorksheetFunction.Min(ECell.Value2, BCell.Value2)
'Increase position in array
DataIndex = DataIndex + 1
'Create array of subtraction history
arrData(DataIndex, 1) = BCell.Offset(, -1).Text 'Get the BCell Category
arrData(DataIndex, 2) = BCell.Value2 'Get the BCell Current Value
arrData(DataIndex, 3) = BCell.Value2 - dMax 'Get the BCell value after subtraction
arrData(DataIndex, 4) = ECell.Offset(, -1).Text 'Get the ECell Category
arrData(DataIndex, 5) = ECell.Value2 'Get the ECell Current Value
arrData(DataIndex, 6) = ECell.Value2 - dMax 'Get the ECell value after subtraction
'Update dMax and cell values
dMax = arrData(DataIndex, 6)
BCell.Value = arrData(DataIndex, 3)
ECell.Value = arrData(DataIndex, 6)
Loop 'Advance loop to bring current BCell to 0
Next BCell 'Advance loop to next BCell
'If there is data in the array, output that data starting in cell G2
If DataIndex > 0 Then Range("G2").Resize(DataIndex, UBound(arrData, 2)).Value = arrData
'Cleanup
Set rngB = Nothing
Set rngE = Nothing
Set BCell = Nothing
Set ECell = Nothing
Erase arrData
End Sub
Bookmarks