用VBA在单元格中分组

我想在Excel中使用VBA进行一些分组

我的“标准”栏是“A”,它是一般的数字清单,显然是多余的,应该分组以使用户更好地了解Excel表格

我已经命名了列“A”“Vertrag__Nr”。

我的代码

Sub Test() Dim i As Integer, LastRow As Integer LastRow = Cells(Rows.Count, 1).End(xlUp).Row For i = 1 To LastRow If Not Left(Cells(i, 1), 2) = "Vertrag__Nr." Then Cells(i, 2).EntireRow.Group End If Next i End Sub 

我的问题是,我的代码,而不是通过条目“Vertrag _Nr。”分组。 (A列)将整列分成一大组

在这里输入图像说明

因为分组是用于摘要的,所以在组之间必须有一个汇总的地方,它们不能连续,试试这个代码:

 Sub Test() Dim i As Integer, j As Integer, LastRow As Integer Dim currVal As Variant With ActiveSheet LastRow = .Cells(Rows.Count, 1).End(xlUp).Row i = 2 While i <= LastRow currVal = .Cells(i, 1).Value j = 0 Do j = j + 1 Loop Until .Cells(i + j, 1).Value <> currVal If j > 1 Then .Rows(i + j).Insert .Cells(i + j, 1).Value = currVal Range(.Cells(i, 1), .Cells(i + j - 1, 1)).EntireRow.Group End If i = i + j Wend End With End Sub