循环插入行,复制数据

我放弃。 我花了四个小时试图弄清楚为什么这个macros不起作用。 我希望它采取给定的源范围,循环使用For循环,并将值复制到不同的列。

我希望它在给定的目标单元格开始

  • input值
  • 使用Insert创build一个新行(整行,而不是插入到该列中,我想将数据放入现有的一组行中)
  • 不覆盖指定目标列终点的标记。 有下面的数据需要保存。

我无法弄清楚为什么

  • 在过程的一个实例中,它input值,但在插入下一行时擦除数据。
  • 在第二种情况下,它跳过一行并删除列标记的结尾

请注意,我并不是在寻找聪明,优雅的解决scheme来解决这个问题,为了教我自己的vba范式,我想把事情保持真正的基础。 随着我对基础知识的进一步了解,我会尝试一些高级技巧。

TIA

 Sub Macro1() Dim firstRow As Range, lastRow As Range Dim source As Range, destination As Range Dim readCell As Range Set firstRow = Range("F2") Set lastRow = Range("F20") Set destination = Range("A21") Set source = Range(firstRow.Address(False, False) & ":" & lastRow.Address(False, False)) For Each readCell In source destination.Select destination.Value = readCell.Value If (readCell.Address(False, False) = lastRow.Offset(1, 0)) Then Exit For Else 'destination.Select End If 'MsgBox (destination.Value) destination.EntireRow.Insert Shift:=xlUp Set destination = destination.Offset(1, 0) Next End Sub 

这里有一些提示:

鉴于firstRowlastRow是单个单元格,不需要Address东西。 使用

 Set source = Range(firstRow, lastRow) 

destination.EntireRow.Insert Shift:=xlUp ,因为您将Insert应用于整行, Shift没有任何区别。 使用

 destination.EntireRow.Insert 

放置在destination上方的插入行, destination向下移动。 所以for循环的第一个迭代就是这样做的

  1. destination设定为A21
  2. 插入行,将destination转移到A22
  3. 设置一行,即A23

接下来的迭代将覆盖原来在A22的数据,现在在A23

我想你想要

 Sub Macro1() Dim firstRow As Range, lastRow As Range Dim destination As Range Dim readCell As Range Set firstRow = Range("F2") Set lastRow = Range("F20") Set destination = Range("A21") For Each readCell In Range(firstRow, lastRow) destination.Value = readCell.Value destination.EntireRow.Offset(1, 0).Insert Set destination = destination.Offset(1, 0) Next End Sub 

非常值得赞赏的是,你想了解以及解决

使用行计数器比从固定的目的地增量更容易。 这个小调整

  • 避免Select
  • 使用一个计数器lngRow来控制新的行和新的值

    code

     Sub Macro1() Dim readCell As Range Dim lngRow As Long For Each readCell In Range("F2:F20") [a21].Offset(lngRow, 0).EntireRow.Insert Shift:=xlUp [a21].Offset(lngRow, 0).Value = readCell.Value lngRow = lngRow + 1 Next End Sub