宏基于单元格中的数量在单独的选项卡中创建新行

时间:2016-11-01 19:15:21

标签: excel vba excel-vba macros

我在Excel中有一个标签(数据标签),用户可以在其中粘贴需要在列中排序的产品列表' A'以及“' B'。

中每个产品的数量

我试图创建一个宏来查看列中的数量' B'每行并将许多记录创建到新选项卡(上传选项卡)。

即。

数据标签

Data Tab

期望的结果

Desired results in (upload tab)

1 个答案:

答案 0 :(得分:0)

创建一个activex按钮,将此代码放在上面。如果上传表不存在,则创建它,否则在执行代码之前清除所有内容。

Private Sub CommandButton1_Click()
    Dim lastrow As Long
    Dim lastrow2 As Long
    Dim row As Long
    Dim product As String
    Dim count As Long
    Dim repeat As Long
    Dim ws As Worksheet
    If Evaluate("ISREF('" & "Upload" & "'!A1)") = False Then
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.count))
        ws.Name = "Upload"
    End With
    Else
        Sheets("Upload").UsedRange.ClearContents
    End If
    Set ws = Sheets("Upload")
    ws.Cells(1, 1) = "Product"
    lastrow = Cells(Rows.count, "A").End(xlUp).row
    lastrow2 = ws.Cells(Rows.count, "A").End(xlUp).row
    For row = 2 To lastrow
        product = Cells(row, 1)
        count = Cells(row, 2)
            For repeat = 1 To count
                lastrow2 = lastrow2 + 1
                ws.Cells(lastrow2, 1) = product
            Next repeat
    Next row

End Sub