根据另一个表中列中的值,将特定数量的行插入表中

时间:2017-01-11 10:15:32

标签: excel excel-vba vba

对于excel VBA,我有点无用。我有一个问题需要解决,我在Excel中的两个单独的工作表上有两个表。

sheet1上的表1看起来像1(附图)

我需要实现的是复制表1中前4列的值,并在表2中将其粘贴到表2中“x”次。 “x”由table1中count列的相应值定义。

sheet2上生成的table2看起来与2类似:(附图片)

如果有人能告诉我如何使用vba宏实现这一目标,我将非常感激。

非常感谢!

-shawn

1 个答案:

答案 0 :(得分:1)

学习如何创建宏的最佳方法是使用“记录宏”功能。它将生成您在工作簿中执行的操作的代码,但是,在这种情况下,您需要循环,因此它更复杂。

以下代码将实现您的目标。我在评论中添加了解释每行的内容。

Sub copyRow()

Application.ScreenUpdating = False                      'Turn off ScreenUpdating so you won't see all the
                                                        'actions happen in real time

    Dim count As Integer                                'Declare variables
    Dim lastRow1 As Integer, lastRow2 As Integer
    Dim ws1 As Worksheet, ws2 As Worksheet

    Set ws1 = Worksheets("Sheet1")                      'Set worksheet values
    Set ws2 = Worksheets("Sheet2")

    ws1.Activate                                        'Sheet1 needs to be active to perform next step
    lastRow1 = ws1.Range("A50").End(xlUp).row           'Identify last row in table to know data size

    For i = 2 To lastRow1                               'For the number of rows in table, perform the following
        count = ws1.Range("F" & i).Value                'Set 'count' variable, number of times to paste row
        ws1.Activate                                    'Sheet2 needs to be active to perform next step
        ws1.Range(Range("A" & i), Range("D" & i)).Copy  'Copy data you want to transfer

        ws2.Activate
        lastRow2 = ws2.Range("A50").End(xlUp).row       'Identify last row in table
        lastRow2 = lastRow2 + 1                         'Want to paste data to NEXT row

        For j = lastRow2 To lastRow2 + count - 1        'Paste the data the number of times indicated
            ws2.Range("A" & j).PasteSpecial
        Next j
    Next i

Application.ScreenUpdating = True                       'Turn back on ScreenUpdating to see updated sheet

End Sub