1

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

4

1 回答 1

3

您发布的代码似乎可以工作,但是以相反的顺序放置新数据

测试为

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

样本数据

前:
在此处输入图像描述

后:
在此处输入图像描述

要颠倒顺序,试试这个

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

结果:
在此处输入图像描述


关于xlDownvs的注意事项xlShiftDown

Excel VBa 为参数提供了许多枚举集。每个枚举都有一个基础数值。Insert方法,Shift参数使用Enumeration XlInsertShiftDirection: xlShiftDown, xlShiftToRight.
xlShiftDown= -4121
从另一个集合中提供一个恰好具有相同基础数值(例如xlDown)的枚举将起作用,但并不完全正确。

注意事项Insert

Shift参数是可选的。如果省略,Excel 会根据范围的形状来决定移动的方式。

于 2013-03-24T23:10:36.713 回答