excel - .Range 和 .InsertShift 在新工作表上复制表格 : overwriting data

标签 excel insert vba

我有一个关于 Sheet.Range 的基本问题和 .Insert Shift:=xlDown .
我想在我的工作表上导入一个只有 2 列的数字表。
每次宏在原始表中读取 2 个值(在同一行上)时,它应该将它们复制到工作表的 A 和 B 列中,并通过在后续行中写入另一对数字来继续该过程。
如果我写
Sheet.Range("A1:B1").Insert Shift:=xlDown
Sheet.Cells(1, 1) = "number 1 "
Sheet.Cells(1, 2) = "number 2"

最后我得到的只是原始表中的最后一对值。
换句话说,宏逐行覆盖而不是向下移动。
我应该修改什么?谢谢!
阿维图斯

最佳答案

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

测试为

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

样本数据

前:
enter image description here

后:
enter image description here

要颠倒顺序,试试这个
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

结果:
enter image description here

备注 xlDown对比 xlShiftDown

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

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

关于excel - .Range 和 .InsertShift 在新工作表上复制表格 : overwriting data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597087/

相关文章:

java - 从 xlsx 文件读取时出现 NullPointerException

java - 如何使用 APACHE POI HSSF 突出显示 Excel 中的单元格

php - 使用php创建Excel工作表

php - 如何将USER表和USERINFO表记录一一匹配?

java - JTextArea insert() 不断出错

Excel VBA 到 Word 取消选择选定的文本

php - 从表单向数据库提交值

excel - 用于更改过滤器的宏按钮

vba - 在 Excel 中使用 VBA 通过索引 # 选择字典项

vba - 如何将VBA中的非ASCII字符写入Excel工作表?