在Microsoft Excel中根据数值限制自动创build行
我想根据特定物品的每箱纸箱的最大单位来创build一个纸箱。
例如。
Item Quantity MaxQtyPerCarton A 12 5 B 6 3
这应该通过在Excel中创build行给出如下结果
Item CartonQuantity A 5 A 5 A 2 B 3 B 3
您可以看到项目数量已根据MaxQtyPerCarton划分为三行。 此外,项目B已被分成两个基于MaxQtyPerCarton的行。
任何想法呢?
VBA的方法(只是编程)
Option Explicit Sub Sub1() Dim iRow1&, iRow2&, zItem$, zQuan&, zMaxQ&, zAmt& iRow2 = 10 ' ?? For iRow1 = 2 To 3 ' ?? zItem = Cells(iRow1, 1) zQuan = Cells(iRow1, 2) zMaxQ = Cells(iRow1, 3) Do While zQuan > 0 zAmt = zQuan If zAmt > zMaxQ Then zAmt = zMaxQ Cells(iRow2, 1) = zItem Cells(iRow2, 2) = zAmt iRow2 = iRow2 + 1 zQuan = zQuan - zAmt Loop Next iRow1 End Sub
这不是超级优雅,但它完成了工作。 它要求您的问题中的第一个表结构(包括标题)在range("A1:C3")
。 然后输出到列E
和F
Option Explicit Sub FillCartons() Dim cll As Range Dim rng_Items As Range Dim rng_Quantity As Range Dim rng_MaxQty As Range Dim l_CartonCount As Long Dim l_AlreadyInCartons As Long Set rng_Items = Range(Range("A2"), Range("A1000000").End(xlUp)) l_CartonCount = 1 Range("E:F").ClearContents For Each cll In rng_Items Set rng_Quantity = cll.Offset(, 1) Set rng_MaxQty = cll.Offset(, 2) l_AlreadyInCartons = Application.WorksheetFunction.SumIf(Range("E:E"), cll.Value, Range("F:F")) Do Until l_AlreadyInCartons = rng_Quantity.Value If rng_Quantity.Value - l_AlreadyInCartons > rng_MaxQty.Value Then Cells(l_CartonCount, 5).Value = cll.Value Cells(l_CartonCount, 6).Value = rng_MaxQty.Value Else Cells(l_CartonCount, 5).Value = cll.Value Cells(l_CartonCount, 6).Value = rng_Quantity.Value - l_AlreadyInCartons End If l_CartonCount = l_CartonCount + 1 l_AlreadyInCartons = Application.WorksheetFunction.SumIf(Range("E:E"), cll.Value, Range("F:F")) Loop Next cll End Sub
这是假设你有以下设置,你想输出开始A10
我使用了Mod和Division的合并,重复和Mod的余数
Sub create_rows() Dim arr() arr = Range("A2:C5") Range("A10").Select Dim j For j = LBound(arr, 1) To UBound(arr, 1) Dim looper, z looper = arr(j, 2) / arr(j, 3) 'No of times to print Modder = arr(j, 2) Mod arr(j, 3) 'Leftovers For z = 1 To looper ActiveCell = arr(j, 1) 'Name of the quantity ActiveCell.Offset(0, 1) = arr(j, 3) 'always the max per qtn number ActiveCell.Offset(1, 0).Select Next z If (Modder > 0) Then 'there is leftover quantity ActiveCell = arr(j, 1) ActiveCell.Offset(0, 1).Value = arr(j, 2) - arr(j, 3) * Round(looper, 0) ActiveCell.Offset(1, 0).Select End If Next j End Sub
假设你给出的表格在A1:C3(在第1行中有标题),在E2中input这个数组公式** :
=IFERROR(INDEX($A$2:$A$3,MATCH(TRUE,MMULT(0+(ROW($A$2:$A$3)>=TRANSPOSE(ROW($A$2:$A$3))),CEILING($B$2:$B$3/$C$2:$C$3,1))>=ROWS($1:1),0)),"")
复制下来,直到你开始得到结果的空白。
那么,F2中的这个(非数组)公式:
=IF(E2="","",MIN(INDEX($C$2:$C$3,MATCH(E2,$A$2:$A$3,0)),INDEX($B$2:$B$3,MATCH(E2,$A$2:$A$3,0))-INDEX($C$2:$C$3,MATCH(E2,$A$2:$A$3,0))*(COUNTIF($E$2:$E2,E2)-1)))
根据需要复制。
**数组公式不是以与“标准”公式相同的方式input的。 按住CTRL键和SHIFT键,而不是按下ENTER键,然后按ENTER键。 如果你做得对,你会注意到Excel在公式周围放置了大括号(尽pipe不要试图自己手动插入这些)。