像這樣的東西應該工作:
Sub Consignment()
Dim Rng As Range
Dim Cell As Range
Dim GroupTotal As Integer
Set Rng = Sheet1.Range("B1:B60") '<-- Set to your units to pack column
For Each Cell In Rng
GroupTotal = GroupTotal + CInt(Cell.Value)
If (GroupTotal = 32) Then
'Insert just one row, no products to be split:
Cell.Offset(1, -1).EntireRow.Insert
'Reset Group Total:
GroupTotal = 0
ElseIf (GroupTotal > 32) Then
'The amount in which we divide the product to ensure the unit total equals 32
Dim SplitProduct As Integer: SplitProduct = GroupTotal - 32
'The name of the product we want to split between two groups.
Dim CurrentProduct As String: CurrentProduct = Cell.Offset(0, -1).Value
'Insert two rows, the second one we will include the name of the split group and remaining units
Cell.Offset(1, 0).EntireRow.Insert
Cell.Offset(1, 0).EntireRow.Insert
'Add split product to new group
Cell.Offset(2, -1).Value = CurrentProduct
'Add remaing product to new group
Cell.Offset(2, 0).Value = SplitProduct
'Remove product from group to leave 32 products in total
Cell.Value = CInt(Cell.Value) - SplitProduct
'Reset Group Total:
GroupTotal = 0
End If
Next Cell
End Sub
注意我的回答使用Offset
函數來獲取產品名稱,所以當我們分開,我們可以在下面的行復制此任何金額。
歡迎SO。如果你有一個'excel-vba'標籤,如果你沒有發佈**你已經嘗試過的代碼**,那麼問題容易出現downvoted和closed。要獲得更多幫助,請向我們展示您的嘗試,以及無法使用它的內容。請參見[如何提問](http://stackoverflow.com/help/how-to-ask) –