Dear Villalobos
It would all depend on what behaviour you would want the calculation to adopt for each of the different materials.
The last formula I wrote basically sets the behaviour of material A and B to be the default if it is not the first instance of that material, and the behaviour of material D to be the default if it is the first instance of that material.
However, this can all be modified however you would like it, but you'd've to explain the logic you want for the default behaviour and give all the special cases you want to behave differently.
To help you out I'll attempt to explain the formula in more detail
=IFERROR(OFFSET($C$1,LARGE(($D2=$D$1:$D1)*ROW($D$1:D1),1)-1,0)-OFFSET(E2,0,IF(OR(D2="c",D2="e"),0,1)),IF(OR(D2="A",D2="B",D2="C"),A2-B2,IF(D2="E",A2-E2,E2-A2)))
So starting with the iferror statement this takes two parameters, the first a function it attempts to calculate and second what to do if that function evaluates to and error
the first function is
OFFSET($C$1,LARGE(($D2=$D$1:$D1)*ROW($D$1:D1),1)-1,0)-OFFSET(E2,0,IF(OR(D2="c",D2="e"),0,1))
the second function is
IF(OR(D2="A",D2="B",D2="C"),A2-B2,IF(D2="E",A2-E2,E2-A2)).
So the first function (what the if error tries to calculate)
This is in two parts part 1 is
OFFSET($C$1,LARGE(($D2=$D$1:$D1)*ROW($D$1:D1),1)-1,0)
partt 2 is
OFFSET(E2,0,IF(OR(D2="c",D2="e"),0,1))
both parts use the offset function with 3 parameters the first being a cell to start with, the second parameter is the number of rows to move down from that start cell and the third parameter the number columns to move right from the start cell and will return the value in that cell.
so the first part starts at c1 and moves 0 columns and the clever bit is the determination of the rows with the formula LARGE(($D2=$D$1:$D1)*ROW($D$1:D1),1)-1 which works out the previous instance in column D with the same value as the value in (in this case D2). If there is no such value (i.e. it is the first instance of the material) then this throws up an error (hence the use of iferror).
The second part checks to see if the the material is C or E and if so it will use the value in column E, otherwise it uses the value in column F and this second part was subtracted from the first part
So lets go back to what the iferror function does if this part throws up an error (basically if it is the first instance of that material)
IF(OR(D2="A",D2="B",D2="C"),A2-B2,IF(D2="E",A2-E2,E2-A2))
So here we check to see if the material is A,B or C in which case it does column A - column B, if the material is not A, B or C then it checks to see if the material is E if it is then it does column A - column E otherwise it does column E- column A (which is what material D does).