2016-01-21 170 views
-1

我們正在發貨。我在第1列中有產品名稱,各個單元在Excel中第2列中包裝。我想把產品分成32個組。一旦單位總數達到32個,首先添加兩個新行,其中第一個是空白,第二個與剩餘單元的最後一行相同。將單元格值添加到常數

product1 12 
product2 16 
product3  8 
product4  9 

看起來像

product1 12 
product2 16 
product3  4 
(empty row) 
product3  4 
product4  9 

等。


請提出解決方案。

+0

歡迎SO。如果你有一個'excel-vba'標籤,如果你沒有發佈**你已經嘗試過的代碼**,那麼問題容易出現downvoted和closed。要獲得更多幫助,請向我們展示您的嘗試,以及無法使用它的內容。請參見[如何提問](http://stackoverflow.com/help/how-to-ask) –

回答

1

我要發表我的:

Sub nnnn() 
    Dim ws As Worksheet 
    Dim ttl As Integer 
    Dim i As Long 
    Dim temp As Integer 

    i = 1 

    Set ws = ActiveSheet 'This can be changed to Set ws = Sheets("Sheet1") 
    With ws 
     'Loop until the end of the range dynamically 
     Do Until .Cells(i, 1) = "" 
      'check if less than 32 
      If ttl + .Cells(i, 2) < 32 Then 
       ttl = ttl + .Cells(i, 2) 
       i = i + 1 
      ' check if equal to 32 
      ElseIf ttl + .Cells(i, 2) = 32 Then 
       Rows(i + 1).Insert 
       i = i + 2 
       ttl = 0 
      'if not less than or equal must be over 
      Else 
       Rows(i + 1 & ":" & i + 2).Insert      
       temp = .Cells(i, 2) 
       .Cells(i, 2) = 32 - ttl 
       .Cells(i + 2, 1) = .Cells(i, 1) 
       .Cells(i + 2, 2) = temp - .Cells(i, 2) 
       i = i + 2 
       ttl = 0 
      End If 
     Loop 
    End With 
End Sub 
1

像這樣的東西應該工作:

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函數來獲取產品名稱,所以當我們分開,我們可以在下面的行復制此任何金額。

+1

這絕對是接近的,但如果您看一下示例,則會在第一個和第二個之間分割產品3。每個組必須等於32,其餘組將移至下一個組。 –

+1

這不太符合需求的要求。它不會在產品名稱旁邊留下適當的商品數 –

+0

是的,我剛剛意識到這一點!我正在迅速提煉我的答案:-) –

相關問題