Sub Ship()
Set D = CreateObject("Scripting.Dictionary")
Arr = Range([庫存!C2], [庫存!A5000].End(3))
For R = 1 To UBound(Arr) '料件X:>日期1,庫存1>日期2,庫存2>日期3,庫存3...........
D(Arr(R, 1)) = D(Arr(R, 1)) & ">" & Arr(R, 2) & "," & Arr(R, 3)
Next
Sheets("結果").Activate
For R = 2 To [A5000].End(3).Row
Key$ = Cells(R, 2)
LData = D(Key)
If LData = "" Then
Cells(R, 4) = "沒有資料"
Cells(R, 5) = "數量不足"
GoTo 下一流水號
End If
Data = Split(LData, ">")
Ci = 4 'D欄開始填
需求 = Cells(R, 3)
For i = 1 To UBound(Data)
日期 = Split(Data(i), ",")(0)
庫存 = Split(Data(i), ",")(1)
If 庫存 = 0 And i = UBound(Data) Then '最後一筆也是庫存0
Cells(R, Ci) = "沒有資料"
Cells(R, Ci + 1) = "數量不足"
GoTo 下一流水號
End If
If 庫存 = 0 Then GoTo 下一庫存 '非最後一筆,庫存0
If 庫存 - 需求 >= 0 Then
Cells(R, Ci) = 日期
Cells(R, Ci + 1) = 需求
庫存 = 庫存 - 需求
Data(i) = 日期 & "," & 庫存
GoTo 已出貨完
Else '庫存 - 需求 <0
Cells(R, Ci) = 日期
Cells(R, Ci + 1) = 庫存
需求 = 需求 - 庫存
Ci = Ci + 2
Data(i) = 日期 & "," & 0
If i = UBound(Data) And 需求 > 0 Then '最後一個庫存也無法滿足出貨
Cells(R, Ci) = "沒有資料"
Cells(R, Ci + 1) = "數量不足"
End If
End If
下一庫存: Next i
已出貨完: '(已經0庫存 或者 滿足出貨需求)
LData = Join(Data, ">")
D(Key) = LData
Debug.Print Key & ":" & LData
下一流水號: Next R
End Sub作者: ikboy 時間: 2020-3-31 08:45
Option Explicit
Sub TEST()
Dim Arr, Brr, Crr, 需求&, Z, i&, j%, C%, T$, 庫存&, D As Date, W&, V&, R&
Set Z = CreateObject("Scripting.Dictionary")
Brr = Range([庫存!C1], [庫存!A65536].End(3))
For i = 2 To UBound(Brr)
T = Trim(Brr(i, 1)): If T = "" Then GoTo i01
If Not IsObject(Z(T)) Then Set Z(T) = CreateObject("Scripting.Dictionary")
Z(T)(i) = 0: Z(T & "Tot") = Z(T & "Tot") + Val(Brr(i, 3))
i01: Next
Crr = Range([原始!C1], [原始!A65536].End(3))
ReDim Arr(2 To UBound(Crr), 1 To 100)
For i = 2 To UBound(Crr)
T = Trim(Crr(i, 2)): 需求 = Val(Crr(i, 3)): C = 0: If Z(T & "Tot") = 0 Then GoTo i02
For j = Z(T & "No") To Z(T).Count - 1
W = W + 1: R = Z(Trim(Crr(i, 2))).keys()(j)
庫存 = Val(Brr(R, 3))
D = CDate(Brr(Z(Trim(Crr(i, 2))).keys()(j), 2))
V = IIf(庫存 < 需求, 庫存, 需求)
Arr(i, C + 1) = D: Arr(i, C + 2) = V: C = C + 2
Z(T & "Tot") = Z(T & "Tot") - V
需求 = 需求 - V: 庫存 = 庫存 - V
If 庫存 = 0 Then Z(T & "No") = Z(T & "No") + 1 Else Brr(R, 3) = 庫存
If 需求 = 0 Then Exit For
Next
i02: If Z(T & "Tot") = 0 And 需求 > 0 Then Arr(i, C + 1) = "沒有資料": Arr(i, C + 2) = "數量不足"
Next
[原始!D2].Resize(UBound(Arr) - 1, UBound(Arr, 2)) = Arr
MsgBox "迴圈數:" & W
End Sub