【问题标题】:Excel VBA Macro to add a row when value changes and populate that rowExcel VBA宏在值更改时添加一行并填充该行
【发布时间】:2013-06-21 13:28:19
【问题描述】:

我正在尝试在 excel 中构建一个宏,该宏将采用这样的一堆数据:

D 1 2 3 4 5
D 1 2 3 9 5
D 1 2 3 4 5

并在第 4 列中的值不同时对其进行处理以插入一行。我还想同时使用静态值或公式填充此行。

理想情况下,我会得到上表:

D 1 2 3 4 5
H A B C D E   <- This row got added as there was a change in column D
D 1 2 3 9 5
H A B C D E   <- This row got added as there was a change in column D
D 1 2 3 4 5

我希望它遍历一个很长的列表。

谁能给我指点?

感谢您的帮助。

【问题讨论】:

  • 你想遍历一个很长的列表 .. 为什么?

标签: excel vba


【解决方案1】:

这样的事情应该可以工作。我没有测试它,但如果你运行它并使用 F8 来迭代它,如果它不能完全按照预期工作,它应该很容易调试。

Dim i as integer

for i = 2 to cells(1,1).end(xldown).row 'itereate thru all rows
  if cells(i,4).value <> cells(i-1,4).value then 'compare the cells in col 4 with previous row
    rows(i).entirerow.insert 'insert a row if the values don't match
    cells(i,1) = "A"
    cells(i,2) = "B"
    cells(i,3) = "C"
    cells(i,4) = "D"
    cells(i,5) = "E"

    i = i + 1 'since we inserted a row we have to make i bigger to go down
  end if
next i

【讨论】:

  • 感谢您的帮助,但在这一行遇到 1004 错误: Rows(i).EntireRow.Insert shift:=xlDown '如果值不匹配则插入一行
  • 尝试摆脱 sfhit:=xldown 业务
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
相关资源
最近更新 更多