如何根据x行数复制单元格值x次

时间:2018-07-27 03:44:53

标签: excel vba excel-vba

我是vba的新手,感谢您的帮助。

我有这个Receipt工作表,其中包含一些客户信息,并设法创建了一个宏,该宏在每次执行时都会添加新的产品系列。

Receipt sheet

但是我想运行一个宏,该宏将此信息复制到Report表中,该宏将复制先前添加的产品线,并根据复制的产品线复制客户信息“ x”次。接下来的收据也一样,因此Report工作表看起来像这样。

Report Sheet

您可以看到我为“ John”添加了3个产品,为“ Walter”添加了2个产品,因此它们的信息分别被复制了3次和2次。

我什至不知道在vba中是否可以做到这一点,因此您的任何建议将不胜感激。 感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我不知道您的收据总体上看起来如何,所以我将在您的屏幕上构建代码:

 Sub CopyData()
    Dim i As Long, lastRow As Long, firstName As String, lastname As String, _
        dt As String, id As Long, no As Long
    Dim wsReceipt As Worksheet, wsReport As Worksheet
    Set wsReceipt = Worksheets("Receipt worksheet")
    Set wsReport = Worksheets("Report worksheet")
    'gather information from receipt sheet
    no = wsReceipt.Cells(1, 2).Value
    dt = wsReceipt.Cells(2, 2).Value
    id = wsReceipt.Cells(3, 2).Value
    firstName = wsReceipt.Cells(4, 2).Value
    lastname = wsReceipt.Cells(4, 3).Value

    lastRow = wsReceipt.Cells(7, 2).End(xlDown).Row
    'loop through receiptSheet and past all information to reportSheet
    For i = 7 To lastRow
        wsReport.Cells(i - 5, 1).Value = no
        wsReport.Cells(i - 5, 2).Value = dt
        wsReport.Cells(i - 5, 3).Value = id
        wsReport.Cells(i - 5, 4).Value = firstName
        wsReport.Cells(i - 5, 5).Value = lastname
        wsReport.Cells(i - 5, 6).Value = wsReceipt.Cells(i, 2).Value
        wsReport.Cells(i - 5, 7).Value = wsReceipt.Cells(i, 3).Value
    Next
End Sub