简体   繁体   中英

excel-vba 2013, insert a row with the same format as the Row above

I'm looping through column (M) and if the value is >= 1, I want to insert a row beneath. it should have the same formatting as the row above and Copy down the data from columns 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

The xlLastRow function is defined elsewhere. I am receiving an "Application-defined or object-defined error" on the "Then" statement. Thanks for your help.

When inserting (or deleting) rows you'll need to step backwards through the row count (start at last row and move up). This is because once you insert a row, it will through the range off, if you go from first to last and you will miss rows.

That is one issue. The other issue, is that you don't specifically refer to which cells and rows you want to insert. The best way to avoid errors is to qualify and work directly with your objects. And still a third issue is that you don't appear to end your If block, but I could be misunderstanding the code a bit. See my notes below.

See this code, which should work more smoothly for you:

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

You need an end if statement before the line commencing 'next'. It's also normal to indent after the 'then' to make the if more clearly defined

You must specify the row which you insert a new row relative to it.

Rows(x).Insert

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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