I have a macro which inserts a number of rows depending on user input in Excel 2007. Everything works but I still have a minor issue. I want to copy the complete formatting from the row above. It only works for some cells in the row.
Here is the code for insertion:
Rows("B:B").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Is it possible to change it?
best, US
I am not sure exactly how you are inserting your rows, but if you insert the row below an existing one, it will by default take on the formatting of the row above it, at least it does when you use this type of syntax:
Range("B2").EntireRow.Offset(1, 0).Insert
In this example, it will insert a row below B2 and the format (say, B2's row is highlighted yellow) will be yellow as well. It might have to do with the fact that this type of inserting specifies exactly under which row to insert.
For those that don't want to inherit formatting from parent range use .cells()
.
.rows(2).insert
will inherit formatting while .cells(2).insert
will not.
The answer is the first comment.
New code:
Rows(CStr(InsRowNumber - 1) & ":" & CStr(InsRowNumber - 1)).Copy
Rows(CStr(InsRowNumber) & ":" & CStr(InsRowNumber)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Dim j As Long, r As Range
j = InputBox("type the number of rows to be insered")
Set r = Range("A4")
Do
Range(r.Offset(1, 0), r.Offset(j, 0)).EntireRow.Insert
Set r = Cells(r.Row + j + 1, 1)
If r.Offset(1, 0) = "" Then Exit Do Loop