excel-vba 2013,插入一行与上面的行相同的格式
我正在循环通过列(M),如果值是> = 1,我想插入下面的一行。 它应该具有与上面的行相同的格式,并从列A:I中复制数据
Sub insertRow() Dim LastRow As Long Dim rng As Range, Cell As Range, rng2 As Range, rng3 As Range LastRow = xlLastRow Set rng = Range("M3:M" & LastRow) For Each Cell In rng If Cell.Value >= 1 Then Rows.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Set rng2 = Range("A3:I3") rng2.Copy set rng3 = Range("A4") rng3.PasteSpecial Paste:=xlPasteAllUsingSourceTheme Next Cell
xlLastRow函数在别处定义。 我在“Then”语句上收到“应用程序定义或对象定义的错误”。 谢谢你的帮助。
插入(或删除)行时,您需要向后退一步(从最后一行开始向上移动)。 这是因为一旦你插入一行,它将通过范围closures,如果你从头到尾,你会错过行。
这是一个问题。 另一个问题是,你没有特别指出你想要插入的单元格和行。 避免错误的最佳方法是限定并直接与您的对象合作。 还有第三个问题是,你似乎没有结束你的If
块,但是我可能会误解代码。 看到我的笔记下面。
看到这个代码,它应该更顺利地为你工作:
Dim LastRow As Long Dim x as Long Dim ws as Worksheet Set ws = Sheets("Sheeet1") 'change as needed LastRow = xlLastRow For x = LastRow to 3 Step -1 If ws.Range("M" & x).Value >= 1 Then ws.Rows(x).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove 'this will copy data A:I from same row into newly inserted row ws.Range("A" & x & ":I" & x).Copy ws.Range("A" & x +1 & ":I" & x + 1).PasteSpecial Paste:=xlPasteAllUsingSourceTheme End If Next Cell
在'next'开始的行之前,你需要结束if语句。 在'then'之后缩进也是正常的
您必须指定相对于它插入新行的行。
行(X).Insert