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

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

表1在表1中看起来像这样1 (附图)

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

sheet2上产生的table2应该看起来类似于这个2 (附图)

我真的很感激,如果有人可以告诉我如何实现与vbamacros。

非常感谢!

-shawn

学习如何创buildmacros的最佳方法是使用loggingmacrosfunction。 它会产生你在工作簿中做什么的代码,但是在这个例子中你需要循环,所以它更复杂。

下面的代码将实现你正在寻找的东西。 我在评论中添加了解释每一行的function。

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