insert rows after a data point changes

走远了吗. 提交于 2020-01-13 20:33:30

问题


I have a data set that looks like this:

This1    GH
This2    GH
This3    GH
This4    BR
This5    BR
This6    VB

when the data point changes, i.e. "GH" to "BR" I want excel to insert a line break. so that the finalized data looks like this.

This1    GH
This2    GH
This3    GH

This4    BR
This5    BR

This6    VB

any idea how this would be done? i think that a negative iterating for loop would work. but i don't know how excel would handle row manipulation in this case.


回答1:


The fastest way to do it (TRIED AND TESTED)

Option Explicit

Sub Sample()
    Dim aCell As Range, bCell As Range
    Dim ExitLoop As Boolean

    With Sheets("Sheet1")
        .Columns("A:B").Subtotal GroupBy:=2, Function:=xlCount, TotalList:=Array(2), _
        Replace:=True, PageBreaks:=False, SummaryBelowData:=True

        Set aCell = .Cells.Find(What:=" Count", LookIn:=xlValues, _
                     LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                     MatchCase:=False, SearchFormat:=False)

        If Not aCell Is Nothing Then
            Set bCell = aCell
            .Rows(aCell.Row).ClearContents
            Do While ExitLoop = False
                Set aCell = .Cells.FindNext(After:=aCell)

                If Not aCell Is Nothing Then
                    If aCell.Address = bCell.Address Then Exit Do
                    .Rows(aCell.Row).ClearContents
                Else
                    ExitLoop = True
                End If
            Loop
        End If

        .Cells.RemoveSubtotal
    End With
End Sub

I am assuming that Row 1 has headers.

MACRO IN ACTION




回答2:


Assuming your spreadsheet does not have thousands of lines you can use this (quick and dirty) code:

Sub doIt()

  Dim i As Long

  i = 2
  While Cells(i, 1) <> ""
    If Cells(i, 2) <> Cells(i - 1, 2) Then
      Rows(i).Insert
      i = i + 1
    End If
    i = i + 1
  Wend

End Sub



回答3:


In addition to above 'slow' excel problem, don't forget to disable the application.screenupdating , it will improve speed in any macro with 5000%

Sub doIt()
  Application.ScreenUpdating = False
  Dim i As Long

  i = 2
  While Cells(i, 1) <> ""
  If Cells(i, 1) <> Cells(i - 1, 1) Then
     Rows(i).Insert

     i = i + 1
  End If
  i = i + 1
 Wend
 Application.ScreenUpdating = True
End Sub


来源:https://stackoverflow.com/questions/10539346/insert-rows-after-a-data-point-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!