簡體   English   中英

Excel VBA宏在值更改時添加一行並填充該行

[英]Excel VBA Macro to add a row when value changes and populate that row

我正在嘗試在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

我希望這可以遍歷很長的列表。

誰能給我任何指示?

謝謝您的幫助。

這樣的事情應該起作用。 我沒有測試它,但是如果您運行它並使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM