2016-01-16 282 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