gpt4 book ai didi

excel - 按值对行进行分组

转载 作者:行者123 更新时间:2023-12-03 00:55:30 24 4
gpt4 key购买 nike

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

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

enter image description here

像这样:

enter image description here --> enter image description here

最佳答案

试试这个

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

关于excel - 按值对行进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34824529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com