I'm having a difficult time understanding the description in your file, but based on your expected results, I put the following formula in D2, then filled down:
=IF(IFERROR(VLOOKUP(A2,Sheet3!$A$2:$D$25,4,FALSE)-SUMIF($A$1:$A1,$A2,$D$1:$D1),0)>0,MIN(C2,VLOOKUP(A2,Sheet3!$A$2:$D$25,4,FALSE)-SUMIF($A$1:$A1,$A2,$D$1:$D1)),"")
And in E2 and down:
=IF(D2="",C2,C2-D2)
Take a look at the attachment to see if I'm on the right track. If I'm not, please try to provide a clear explanation of what is missing and a few more expected results.
Bookmarks