计数,插入行,粘贴到其他选项卡中

时间:2018-03-21 14:44:16

标签: excel vba excel-vba

我正在尝试创建一个代码,查看sheet1中的A列,然后在sheet2中插入新行。然后将A列(sheet1)的内容粘贴到sheet2的A列中。见附图: Sheet1 - 总列表 Sheet2 - 现有列表,需要从sheet1添加新行并向下移动其余内容。 Sheet3 - 结果。

我每次都会手动执行此操作,但我尝试将其设置为自动,以便节省一些时间。我将为此分配一个按钮。

提前致谢。 尼尔森

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试下面的代码:

Sub test()

            Dim ws As Worksheet
            Dim ws2 As Worksheet

            Set ws = ThisWorkbook.Sheets("sheet1")
            Set ws2 = ThisWorkbook.Sheets("sheet2")

            lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
            lastRow2 = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row

            i = 1
            Do While ws.Cells(i, 1).Value = ws2.Cells(i, 1).Value
                 i = i + 1
            Loop

            For j = i To lastRow
                lastRow2 = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row
                ws2.Rows(lastRow2 + 1).EntireRow.Insert
                ws2.Range("A" & lastRow2 + 1).Value = ws.Range("A" & j).Value
            Next j

        End Sub