2016-01-16 243 views
2

如何以编程方式按列B中的值分组以下数据?按值分组

请注意,列AC中有随机值。

enter image description here

像这样:

enter image description here - > enter image description here

回答

4

试试这个

Sub demo() 
    Dim r As Range 
    Dim v As Variant 
    Dim i As Long, j As Long 

    With ActiveSheet 
     On Error Resume Next 
     ' expand all groups on sheet 
     .Outline.ShowLevels RowLevels:=8 
     ' remove any existing groups 
     .Rows.Ungroup 
     On Error GoTo 0 
     Set r = .Range("B1", .Cells(.Rows.Count, 2).End(xlUp)) 
    End With 

    With r 
     'identify common groups in column B 
     j = 1 
     v = .Cells(j, 1).Value 
     For i = 2 To .Rows.Count 
      If v <> .Cells(i, 1) Then 
       ' Colum B changed, create group 
       v = .Cells(i, 1) 
       If i > j + 1 Then 
        .Cells(j + 1, 1).Resize(i - j - 1, 1).Rows.Group 
       End If 
       j = i 
       v = .Cells(j, 1).Value 
      End If 
     Next 
     ' create last group 
     If i > j + 1 Then 
      .Cells(j + 1, 1).Resize(i - j - 1, 1).Rows.Group 
     End If 
     ' collapse all groups 
     .Parent.Outline.ShowLevels RowLevels:=1 
    End With 
End Sub 
+0

非常感谢你,这就是它!在某个地方有点小事,因为它停止工作,当它找到只有一条相同的线,例如。 'text1 text1 text1' **'text2' **'text3 text3'。 – gaffcz

+0

@gaffcz我用稍微不同的方式解决了这个错误:查看更新代码 –

+0

太好了,谢谢! – gaffcz