I see that nobody else has posted any solution, so here is what I came up with. It's definitely not the cleanest solution, but maybe it gives you some ideas.
I created a spreadsheet that looks like this (sorry I haven't downloaded the tool that would allow me to post an actual spreadsheet):
A B C D E F G H I J
1
2 Purchases: Sales:
3 Date quantity item price Total cost Date quantity Input field:
4 4/1/2004 51 $10.00 $510.00 4/1/2004 62 4/10/2004
5 4/1/2004 102 $11.00 $1,122.00 4/2/2004 12
6 4/3/2004 153 $10.00 $1,530.00 4/3/2004 112
7 4/3/2004 204 $8.00 $1,632.00 4/4/2004 360
8 4/5/2004 255 $9.00 $2,295.00 4/5/2004 62
9 4/6/2004 306 $12.00 $3,672.00 4/6/2004 127
10 4/7/2004 357 $15.00 $5,355.00 4/7/2004 142
11 4/8/2004 408 $14.00 $5,712.00 4/8/2004 157
12 4/9/2004 459 $13.00 $5,967.00 4/9/2004 172
13 4/10/2004 501 $12.00 $6,012.00 4/10/2004 1500
14 4/11/2004 552 $11.00 $6,072.00 4/11/2004 202
15 4/12/2004 603 $10.00 $6,030.00 4/12/2004 217
16 4/13/2004 654 $9.00 $5,886.00 4/13/2004 232
17 4/14/2004 705 $8.00 $5,640.00 4/14/2004 247
18 4/15/2004 756 $11.00 $8,316.00 4/15/2004 262
Then I created a macro that would tell me the cost of an order based upon the input date in Cell J4:
Code:
Sub COGS()
' Macro to calculate Cost Of Goods Sold using FIFO
Dim Q As Variant
Dim Q2 As Variant
Dim Q3 As Variant
Dim P As Variant
Dim P1 As Variant
Dim P2 As Variant
Dim ln1 As String
Dim ln2 As String
Dim ln3 As String
Dim title As String
Sheets("Purchases").Select
Q = Application.WorksheetFunction.VLookup(Range("I3"), Range("F3:G17"), 2)
Q2 = Application.WorksheetFunction.VLookup(Range("I3"), Range("A3:D17"), 2)
If Q2 >= Q Then
P = Application.WorksheetFunction.VLookup(Range("I3"), Range("A3:D17"), 3)
Else
Range("A3").Select
X = Application.WorksheetFunction.Match(Range("I3"), Range("A3:A17"))
ActiveCell.Offset(X - 1, 1).Select
P = ActiveCell.Offset(0, 2).Value
Repeat:
ActiveCell.Offset(-1, 0).Select
Q3 = ActiveCell.Value
Q2 = Q2 + Q3
I = ActiveCell.Offset(0, 1).Value
P1 = ActiveCell.Offset(0, 2).Value
P = P + P1
If Q2 > Q Then
P = P - P1
P1 = (Q - (Q2 - Q3)) * I
P = P + P1
End If
If Q2 < Q Then GoTo Repeat 'repeat until Q2 >= Q
End If
P2 = P / Q
ln1 = "The total cost for the order was: " & P
ln2 = "The cost per item was: " & P2
title = "COGS"
MsgBox ln1 & vbLf & ln2 & vbLf, , title
End Sub
As I said not the best written code, but it works.
JPM