Home » excel » excel vba – .Range and .InsertShift to copy a table on a new worksheet: overwriting data

excel vba – .Range and .InsertShift to copy a table on a new worksheet: overwriting data

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a basic question on Sheet.Range and .Insert Shift:=xlDown.
I would like to import on my worksheet a table of numbers which has just 2 columns.
Every time the macro reads 2 values (on the same row) in the original table, it should copy them in columns A and B in the worksheet and continue the process by writing another pair of numbers in the subsequent row.
If I write

Sheet.Range("A1:B1").Insert Shift:=xlDown
Sheet.Cells(1, 1) = "number 1 "
Sheet.Cells(1, 2) = "number 2"

all I get in the end is the last pair of values from the original table.
In other words, the macro overwrites instead of moving down, row by row.
What should I amend? Thanks!
Avitus

How to&Answers:

your code as posted apears to work, but puts the new data in in reverse order

Tested as

Sub demoAsIs()
    Dim Sheet As Worksheet
    Dim i As Long
    Set Sheet = ActiveSheet
    For i = 0 To 4
        Sheet.Range("A1:B1").Insert Shift:=xlShiftDown
        Sheet.Cells(1, 1) = "number " & 2 * i + 1
        Sheet.Cells(1, 2) = "number " & 2 * i + 2
    Next
End Sub

Sample data

Before:
enter image description here

After:
enter image description here

To reverse the order, try this

Sub demo()
    Dim Sheet As Worksheet
    Dim i As Long
    Dim rNewData As Range
    Set Sheet = ActiveSheet
    Set rNewData = Sheet.Range("A1:B1")
    For i = 0 To 4
        rNewData.Insert Shift:=xlShiftDown
        ' rNewData now refers to the one row down from where it was
        rNewData.Cells(0, 1) = "number " & 2 * i + 1
        rNewData.Cells(0, 2) = "number " & 2 * i + 2
    Next
End Sub

Result:
enter image description here


Note on xlDown vs xlShiftDown

Excel VBa provides many enumeration sets for parameters. Each enumeration has an underlying numeric value. The Insert method, Shift parameter uses the XlInsertShiftDirection Enumeration: xlShiftDown, xlShiftToRight.
xlShiftDown = -4121
Supplying an enumeration from another set that happens to have the same underlying numeric value (such as xlDown) will work, but is not strictly correct.

Note on Insert

The Shift parameter is optional. If it is omitted, Excel decides which way to shift based on the shape of the range.