宏来复制以前起作用的行,现在不起作用但没有错误消息?

时间:2019-02-05 14:56:25

标签: excel vba

我正在使用以下宏将信息从一行复制到下面的空白行(我已经生成)中。这个宏大约一个月前就起作用了,但是当我现在运行它时,尽管没有错误消息,但什么也没发生。

Sub FillEveryOther()

Dim lastRow As Long
Dim i As Long

lastRow = Cells(Rows.Count, 12).End(xlUp).Row

For i = 2 To i = lastRow Step 2
        Rows(i).EntireRow.Select
        Selection.Copy
        Rows(i + 1).EntireRow.Select
        ActiveSheet.Paste
     If i = lastRow + 1 Then Stop
Next i

End Sub

2 个答案:

答案 0 :(得分:2)

由于

的事实,您永远不会进入循环
For i = 2 to i = lastRow Step 2

在功能上与

相同
For i = 2 to False Step 2

由于False的值为0,所以实际上是在说

For i = 2 to 0 Step 2

所以它永远不会进入循环。

只需将其更改为

For i = 2 To lastRow Step 2

编辑:

为清楚起见,无论该语句评估True还是False,它都不会进入循环,因为False评估0True评估-1

答案 1 :(得分:0)

每隔一行用上一行填充

代码

Sub FillEveryOther()

    Const cCol As Variant = 12    ' Last-Row-Column Letter/Number
    Const cFirstRow As Long = 2   ' First Row Number

    Dim lastRow As Long   ' Last Row Number
    Dim i As Long         ' Cell (Row) Counter

    ' Calculate Last Row Number in Last-Row-Column.
    lastRow = Cells(Rows.Count, cCol).End(xlUp).Row

    ' Loop through every other cell (row) of Last-Row-Column.
    For i = cFirstRow To lastRow Step 2
        ' Copy current row to the row below.
        Rows(i).Copy Rows(i + 1)
    Next

End Sub

改进?

以下代码允许行严格不偶数(2,4,6 ...),并且下面可以有多个空行。但是,cCol的单元格或其中的公式(IsEmpty的单元格中始终必须有数据。

Sub CopyNotEmpty()

    Const cCol As Variant = 12    ' Last-Row-Column Letter/Number
    Const cFirstRow As Long = 2   ' First Row Number

    Dim lastRow As Long   ' Last Row Number
    Dim i As Long         ' Cell (Row) Counter

    ' Calculate Last Row Number in Last-Row-Column.
    lastRow = Cells(Rows.Count, cCol).End(xlUp).Row

    ' Loop through cells (rows) of Last-Row-Column.
    For i = cFirstRow To lastRow
        ' Check if there is data in current cell.
        If Not IsEmpty(Cells(i, cCol)) Then
            ' Copy current row a row below.
            Rows(i).Copy Rows(i + 1)
            ' Increase Cell (Row) Counter, because we don't want to copy
            ' the already copied row.
            i = i + 1
        End If
    Next

End Sub