I sort of got interested in this and as always there was a bit more to do than I first thought of.
This is a real hacked bit of code with no error checking etc. but it does work on the Table1 you supplied. First you'll need a couple of queries that I've imaginatively called query1 and query2
query1 (SQL view) :-
Select sum(units)
from Table1
query2 (SQL view):-
SELECT *
FROM Table1
WHERE units > 0
ORDER BY id;
This is the VBA code which I hope will give you a good start - fingers crossed:-
Sub FIFO()
Dim db As Database
Dim rs As Recordset
Dim Balance As Long
Dim UpdateAmt As Long
Dim Id As Long
'Connect to the database
Set db = CurrentDb
Set rs = db.OpenRecordset("Query2")
'Get the balance which should stay the same overall
Balance = GetBalance()
'Starting at the bottom ...
rs.MoveLast
'... keep moving up until the balance goes negative
While Not rs.BOF And Balance > 0
UpdateAmt = Balance 'this line just remembers what the update amount needs to be
Balance = Balance - rs.Fields(2)
rs.MovePrevious
Wend
'move back up one so we put the update amount in the right place
rs.MoveNext
'The next 3 lines just do the update
rs.Edit
rs.Fields(2) = UpdateAmt
rs.Update
'Finally delete the rest of the records
rs.MovePrevious
Id = rs.Fields(0)
DoCmd.SetWarnings False
DoCmd.RunSQL ("Delete from table1 where units < 0")
DoCmd.RunSQL ("Delete from Table1 where id <= " & Id)
DoCmd.SetWarnings True
End Sub
Function GetBalance() As Long
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Query1")
rs.MoveFirst
GetBalance = rs.Fields(0)
End Function