Try this VBA function then. The syntax is =SellIntoBuys(Offers, Prices, Amount to sell).
Hope this works for you.
Option Explicit
Function SellIntoBuys(ByVal Offers As Range, _
ByVal Prices As Range, _
Units As Double)
Dim UnitsOffered As Double
Dim UnitsRemaining As Double
Dim Price As Double
Dim SaleValue As Double
Dim row As Long
UnitsRemaining = Units
SaleValue = 0
For row = 1 To UBound(Offers.Value2)
UnitsOffered = Offers.Value2(row, 1)
Price = Prices.Value2(row, 1)
If (UnitsRemaining > 0) Then
If (UnitsRemaining >= UnitsOffered) Then
SaleValue = SaleValue + UnitsOffered * Price
Else
SaleValue = SaleValue + UnitsRemaining * Price
End If
UnitsRemaining = UnitsRemaining - UnitsOffered
End If
Next row
SellIntoBuys = SaleValue
End Function