Sub FIFO()
Dim a, i As Long, n As Long, txt As String, e, w
Dim CD As Double, QTY As Long, dic As Object
Set dic = CreateObject("Scripting.Dictionary")
dic.CompareMode = 1
With Sheets("inward").Range("a1").CurrentRegion
.Sort key1:=.Cells(1, 2), order1:=1, Header:=xlYes
a = .Value
End With
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
For i = 2 To UBound(a, 1)
txt = Join$(Array(a(i, 3), a(i, 4), a(i, 8)), Chr(2))
If Not dic.exists(txt) Then
Set dic(txt) = CreateObject("Scripting.Dictionary")
End If
dic(txt)(a(i, 1)) = VBA.Array(a(i, 5), a(i, 6), a(i, 2))
Next
With Sheets("outward").Cells(1).CurrentRegion
.Sort key1:=.Cells(1, 2), order1:=1, Header:=xlYes
.Offset(1, 6).ClearContents
For i = 2 To .Rows.Count
txt = Join$(Array(.Cells(i, 3).Value, .Cells(i, 4).Value, .Cells(i, 5).Value), Chr(2))
CD = .Cells(i, 6).Value
If dic.exists(txt) Then
n = 0
For Each e In dic(txt)
w = dic(txt)(e)
If w(2) <= .Cells(i, 2).Value Then
If CD > 0 Then
If CD <= w(0) Then
w(0) = w(0) - CD
QTY = CD
CD = 0
Else
QTY = w(0)
CD = CD - w(0)
w(0) = 0
End If
.Cells(i, 7 + n).Resize(, 3).Value = _
Array(QTY, e, QTY * w(1))
n = n + 3
dic(txt)(e) = w
If w(0) = 0 Then dic(txt).Remove e
End If
End If
Next
End If
If CD > 0 Then
MsgBox .Cells(i, 3) & " " & .Cells(i, 4) & vbLf & CD & " short", _
vbCritical, Format$(.Cells(i, 2), "mmm dd yyyy")
GoTo Exit_Sub
End If
Next
End With
Exit_Sub:
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Bookmarks