FIFO使用Excel公式或VBA

时间:2018-04-08 06:28:09

标签: excel excel-vba vba

这是我的“IN”列表 -

PN  Qty Price
A   100 5
B   150 6
C   150 7
D   50  -9
E   100 5
F   5   9
G   20  6
I   5   7
J   15  7
J   30  10
K   100 10
K   50  10
A   20  8

这是我的“OUT”列表 -

PN  Qty
A   120
B   10
C   110
D   60
E   100
J   20
J   10

预期结果 -

手动公式计算PN的价格=“A”=((100 * 5)+(20 * 8))/ 120

PN  Qty Price   Total
A   120 5.5 660
B   10  6   60
C   110 7   770
D   60  -9  -540
E   100 5   500
J   20  7.75    155
J   10  10  100

我想实现FIFO逻辑,根据“IN”列表中的“数量”计算“OUT”列表中的总价。

2 个答案:

答案 0 :(得分:1)

enter image description here

当你有这样的表时,传出按钮包含以下代码:

    Private Sub Outgoing_Click()
Dim pn As String
Dim ammout As Long
Dim current As Long
pn = InputBox("Which Item do you want to take out?")
ammount = InputBox("How Item do you want to take out?")
Dim cells As Long
Dim fifo As Double

counter = 1 //line where your table starts
current = 0
fifo = 0
Do Until IsEmpty(cells(counter, 13).Value Or current = ammount)
    If cells(counter, 13).Value = pn Then
        If cells(counter, 14).Value > (ammount - current) Then
        fifo = fifo + (ammount - current) * cells(current, 15).value
        current = ammount
        Else
        fifo = fifo + cells(counter, 14).Value * cells(counter, 15).Value
        current = current + cells(counter, 14)
        cells(counter, 14).Value = 0
    End If
    counter = counter + 1
Loop
fifo = fifo / ammount
End Sub

应该工作。 如果您在当前列表中有足够的内容,那么我就无法匹配谎言,因此缺少验证部分。

答案 1 :(得分:0)

您的预期结果"与您的"手动公式"

不匹配

遵循后者

Option Explicit
Sub main()
    Dim cell As Range
    Dim dictSum As Object
    Dim dictRept As Object

    Set dictSum = CreateObject("Scripting.Dictionary")
    Set dictRept = CreateObject("Scripting.Dictionary")
    With Worksheets("IN")
        For Each cell In .Range("A2", .Cells(.Rows.Count, 1).End(xlUp))
            dictSum(cell.Value) = dictSum(cell.Value) + cell.Offset(, 1).Value * cell.Offset(, 2).Value
            dictRept(cell.Value) = dictRept(cell.Value) + cell.Offset(, 1).Value
        Next
    End With

    With Worksheets("OUT")
        For Each cell In .Range("A2", .Cells(.Rows.Count, 1).End(xlUp))
            cell.Offset(, 2) = dictSum(cell.Value) / dictRept(cell.Value)
            cell.Offset(, 3) = cell.Offset(, 1) * cell.Offset(, 2)
        Next
    End With
End Sub