I have a basic question on
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.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!
your code as posted apears to work, but puts the new data in in reverse order
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
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
Excel VBa provides many enumeration sets for parameters. Each enumeration has an underlying numeric value. The
Shift parameter uses the
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.
Shift parameter is optional. If it is omitted, Excel decides which way to shift based on the shape of the range.