插入新行并将单元格复制到其他单元格

时间:2015-07-16 16:59:17

标签: excel-vba vba excel

在各列单元的D1列:D50000中,我的值为1。 我想检查列D值的哪个单元格是1,并在值为1的所有单元格上方插入一行,我想将一个单元格值从M1复制到左侧第一个单元格的所有新插入行

1 个答案:

答案 0 :(得分:0)

在这里,我的问题解决方案。

Public Sub insertRow()

    Dim row As Integer
    Dim rowCount As Long

    'Set start row and end row
    row = 1
    rowCount = 50000

    With Sheets("sheetname")

        'Loop until to last row
        Do While row <= rowCount

            'If D cell is equal with 1.
            If .Range("D" & row) = 1 Then

                'Insert new rwo above that row
                Rows(row).EntireRow.Insert

                'Copy value from M cell of current to first cell of newly inserted row
                .Range("A" & row) = .Range("M" & row + 1)

                'Increase row
                row = row + 1

                'Increase row count
                rowCount = rowCount + 1

            End If

            'Increase row
            row = row + 1

        Loop

    End With

End Sub