How can I insert a new row below a range and then get a reference to that new row so I can populate it?
Dim newRow As Range
newRow = row.Offset(1).EntireRow.Insert
results in an object variable or width block variable not set error but the new row is inserted. I can't however seem to get a reference to it.
A second question is that in above could I'm iterating over range and inserting rows into that range. Will the insert affect the iteration?
My prior statement was incorrect because I misunderstood what you were trying to do. Below is an example of looping through a range and upon satisfying a condition, a row will be inserted below the current row in the loop. A boolean is needed to then skip over the inserted row.
Sub InsertAfterLastRow()
Dim Rng As Range
Set Rng = Range("A1:B5") 'Arbritrary
Dim LastRow As Long
Dim InsertRow As Long
Dim Inserted As Boolean
Dim NewRow As Range
Inserted = False
For Each Row In Rng.Rows
If Inserted = False Then
If Row.Cells(1, 1).Value = "Yes" Then
Rows(Row.Row + 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Set NewRow = Range(Row.Row + 1 & ":" & Row.Row + 1)
NewRow.Cells(1, 1).Value = "Inserted"
Inserted = True
Else
Row.Cells(1, 1).Value = "No"
End If
Else
'Avoid a double insert, skipping a row
Inserted = False
End If
Next
End Sub
OMG. Stupid VBA syntax. ;)
Set newRow = Rows(rowNumber + 1 & ":" & rowNumber + 1)
works. the important part beign the Set keyword.
I've been battling with a similar issue wanting to add or delete a variable number of rows at a point below a reference range (named range) without affecting the named range. First I determine how many rows to add (or remove) variable holding the number of rows = addR
addR = 2 ' you'd use some logic to derive the value of addR Rows(Range("OutputBlock").Row + 1).EntireRow.Resize(addR).insert
Output block being my named range where I want to add the rows.
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.