在Excelmacros中按索引号复制并粘贴行
我试图通过索引号复制整个行,并将其粘贴到具有不同索引号的另一行,当满足一定的条件(我知道问题不在于条件逻辑)。 我在想这样的事情:
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)
值。 所以,你需要replace这一行
.Rows(lastRow) = .Rows(i).Value
有这两行:
.Rows(i).Copy .Rows(lastRow).PasteSpecial xlPasteValues
要么
.Rows(lastRow).Copy .Rows(i).PasteSpecial xlPasteValues
如果您想复制Rows(lastRow)
并将其作为值粘贴到Rows(i)
。
编辑:
要粘贴所有内容(公式+值+格式),请使用粘贴types作为xlPasteAll
。
参考: msdn
范围复制和粘贴
句法
范围()。复制[目标]
方括号表示Destination是一个可选参数。 如果您不指定目的地范围,则将select复制到剪贴板。 否则,它将第一个范围直接复制到新的位置。
改变这一行:
.Rows(lastRow)= .Rows(i).Value
至:
.Rows(lastRow).copy .Rows(i)
值得注意的是
.Rows(lastRow).copy .Cells(i,1)
也将工作。 Excel将调整目标范围以适应新的数据。
你的代码适合我
所以只需添加一个断点。 Rows(lastRow) = .Rows(i).Value
语句,然后查询立即窗口中的所有相关variables值,如:
?lastRow ?.Rows(lastRow).Address ?i ?.Rows(i).Address
同时你可以
-
在你的代码模块的最上面添加
Option Explicit
语句这将迫使你声明所有的variables,从而导致一些额外的工作,但你会得到更多的控制你的variables使用和拼写错误,从而节省debugging时间
-
暗淡variables来保存行索引从
Long
types,以处理行索引高于32767 -
避免使用Range对象的
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