问题
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