打破数量

时间:2011-05-06 02:21:37

标签: excel vba excel-vba

我之前从未设置过宏,但我看过一个宏,它在电子表格中查看“数量”列,并取任何不是(1)的数量,并将条目重复列出的次数在“数量”栏中。

有人可以告诉我如何设置它吗?

1 个答案:

答案 0 :(得分:3)

这可能有助于您入门。我假设您想要以下内容:

      Col A    Col B                  Col A    Col B
1     Item     Quantity               Item     Quantity
2     Apple    1                      Apple    1
3     Orange   2                      Orange
4     Banana   1              ----->  Orange   2
5     Pear     4                      Banana   1
6     Grape    2                      Pear
7                                     Pear
8                                     Pear
9                                     Pear     4
10                                    Grape    
11                                    Grape    2

这可以通过以下代码实现:

Sub ExpandItem()
    Dim lastRow As Long, rngQuantity As Range, rw As Long

    lastRow = Range("A1").End(xlDown).Row

    For rw = lastRow To 2 Step -1
        If Cells(rw, 1) > 1 Then
            AddItem Cells(rw, 1), Cells(rw, 1).Offset(0, 1)
        End If
    Next rw
End Sub

Sub AddItem(item As Range, quantity As Long)
    Dim i As Long
        For i = 1 To (quantity - 1)
               item.EntireRow.Insert Shift:=xlDown
               item.Offset(-1, 0) = item.Value
        Next i
End Sub

希望这有助于您朝着正确的方向前进