繁体   English   中英

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

[英]Copy and Paste row by index number in Excel Macro

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

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

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

我假设您要复制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粘贴类型用作xlPasteAll

参考: msdn

范围复制和粘贴

句法

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

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

改变这一行:

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

至:

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

值得注意的是

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

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

你的代码适合我

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

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

与此同时你可以

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

    这将迫使你声明所有变量,从而导致一些额外的工作,但你将得到更多的控制你的变量使用和拼写错误,从而节省调试时间

  • dim变量保存行索引为Long类型,处理行索引高于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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM