Zend certified PHP/Magento developer

Formula for data distribution

I would like to know if there is a way to automatically distribute the amounts from column H into column D in 3 sections (Blue, Green, and Yellow) starting from D28 (Start) and climbing to the top D3 (End) filling them in that order from bottom to top, without exceeding the quantity circled in red for each group (Less Than or Equal to), can’t use amounts from column H twice.

For example:

The formula distributes H6, H7, and H15 into Column D starting (Start) from D28 to D26 (Yellow Group), the sum of these quantities (sum=2287) is close to 2300 “less or equal to” (Amount circled in red), then it will proceed to do the same with the green group and leave the blue group to the end.

Example Picture:

Example Picture

Thanks!