在Excel宏中按索引编号复制和粘贴行

时间:2016-06-16 08:15:32

标签: excel vba excel-vba macros

我正在尝试按索引号复制整行,并在满足某个条件时将其粘贴到具有不同索引号的另一行(我知道问题不在于条件逻辑)。我在考虑这样的事情:

Sub Makro1()

Dim i As Integer

With ActiveSheet
    'for looping
    totalRows = .Cells(.Rows.Count, "A").End(xlUp).Row

    'index of last row even after rows have been added
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    'data starts at row #3
    For i = 3 To totalRows
        If .Cells(i, 19).Value > 0 Then
            Number = .Cells(i, 19).Value
            Do While Number > 0
                lastRow = lasRow + 1
                'Next line doesnt do anything
                .Rows(lastRow) = .Rows(i).Value
                Number = Number - 1
            Loop
        End If
    Next i
End With
End Sub

这个逻辑就像它应该的那样工作,但没有粘贴任何线条。我已经一步一步走了,我确定问题不在于逻辑。

3 个答案:

答案 0 :(得分:3)

我假设您要复制Rows(i)并将其粘贴为Rows(lastRow)中的值。所以,你需要替换这一行

 .Rows(lastRow) = .Rows(i).Value

这两行:

.Rows(i).Copy
.Rows(lastRow).PasteSpecial xlPasteValues

.Rows(lastRow).Copy
.Rows(i).PasteSpecial xlPasteValues

如果您要复制Rows(lastRow)并将其粘贴为Rows(i)中的值。

修改

要粘贴所有内容(公式+值+格式),请将粘贴类型用作xlPasteAll

参考:msdn

答案 1 :(得分:2)

范围复制和粘贴

语法

  

范围()。复制[目的地]

方括号表示Destination是可选参数。如果未指定目标范围,则会将选择内容复制到剪贴板。否则,它会将第一个范围直接复制到新位置。

更改此行:

  

.Rows(lastRow)= .Rows(i).Value

要:

  

.Rows(lastRow).copy .Rows(i)

值得注意的是

  

.Rows(lastRow).copy .Cells(i,1)

也会奏效。 Excel将调整目标范围的大小以适应新数据。

答案 2 :(得分:2)

您的代码适合我

所以只需在。Rows(lastRow) = .Rows(i).Value语句中添加断点,然后在立即窗口中查询所有相关变量值,如:

?lastRow
?.Rows(lastRow).Address
?i
?.Rows(i).Address

同时你可以

  • 在代码模块的最顶部添加Option Explicit语句

    这会强制您声明所有变量,从而导致一些额外的工作,但是您可以通过更多地控制变量使用和拼写错误来获得回报,从而节省调试时间

  • 用于保存Long类型的行索引的dim变量,以处理高于32767的行索引

  • 使用范围对象的Resize()方法

  • 来避免内循环

非常类似:

Option Explicit

Sub Makro1()

    Dim i As Long, totalRows As Long, lastRow As Long, Number As Long

    With ActiveSheet
        'for looping
        totalRows = .Cells(.Rows.Count, "A").End(xlUp).Row

        'index of row to add from
        lastRow = totalRows + 1 '<--| start pasting values one row below the last non empty one in column "A"

        'data starts at row #3
        For i = 3 To totalRows
            If .Cells(i, 19).Value > 0 Then
                Number = .Cells(i, 19).Value
                .Rows(lastRow).Resize(Number).Value = .Rows(i).Value
                lastRow = lastRow + Number
            End If
        Next i
    End With
End Sub