Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

vba - Excel Macro - Copy Row -> Insert Row under -> Paste data

I have a code that runs through column E(Column C in example below) and searches for any change in data. It then inserts a blank row under that change and loops through the set of data (200-500 rows long). I am looking for a way to modify/add to the code a "copy and paste" feature of the last row of data, before the change, into the newly inserted row.

Before:

Column A Column B Column C Column E
1 2 Sally 5
1 2 Sally 6
1 2 Sally 2
1 2 Chase 1
1 2 Chase 4
1 2 Ben 9
question from:https://stackoverflow.com/questions/65890535/excel-macro-copy-row-insert-row-under-paste-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edited::

Try the updated code, please:

Sub testInsertRowCopyBefore()
  Dim sh As Worksheet, lastRow As Long, i As Long
  
  Set sh = ActiveSheet
  lastRow = sh.Range("A" & Rows.count).End(xlUp).row
  
  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual
   For i = lastRow + 1 To 3 Step -1
    If sh.Range("C" & i).Value <> sh.Range("C" & i - 1).Value Then
        sh.Range("C" & i).EntireRow.Insert xlUp
        sh.Range("B" & i & ":C" & i).Value = sh.Range("B" & i - 1 & ":C" & i - 1).Value
    End If
   Next i
  Application.ScreenUpdating = True
  Application.Calculation = xlCalculationAutomatic
  MsgBox "Ready..."
End Sub

The above code assumes that "Column A", "Column B" and "Column C" are the headers, which stay on the sheet first row.

Please, test it and send some feedback


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...