在数据点更改后插入行

我有一个数据集,看起来像这样:

这1 GH
这2 GH
这3 GH
这4 BR
这5 BR
这6个VB

当数据点发生变化时,即“GH”到“BR”,我希望excel插入一个换行符。 所以最终的数据看起来像这样。

这1 GH
这2 GH
这3 GH

这4 BR
这5 BR

这6个VB

任何想法如何做到这一点? 我认为负循环的循环会起作用。 但我不知道在这种情况下excel如何处理行操作。

最快的方法( 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 

我假设第1行有标题。

macros观行动

在这里输入图像描述

假设你的电子表格没有数千行,你可以使用这个(快速和肮脏的)代码:

 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 

除了上面的“缓慢”excel问题,不要忘记禁用application.screenupdating,它会提高任何macros的速度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