尽管这篇文章的年代久远,但我想我会为任何可能偶然发现它的人投入两分钱。我希望我能正确理解你的问题。这是我收集的内容:
目标:对于感兴趣列中的每一行,根据标准对行进行分组。
标准:只有rows in the group
那些没有值(空白、空、空)或有一个值并且有一个值为 0 的相邻单元格(直接在左边)。唯一rows not in the group
的是那些不是空白的并且有一个不为0 的相邻单元格。
以下是一些示例数据:
注意: RangeB1:B12
构成了命名的 range rngList
,就像 OP 所说的那样。
运行宏前的数据:
运行宏后的数据 - 分组未折叠:
运行宏后的数据 - 分组折叠:
处理这个的代码:
要使此代码工作:在 VBE(Visual Basic 编辑器)中,打开包含要分组的数据的工作表(也包含命名的 range rngList
)并粘贴此代码,然后运行宏。
注意:添加注释是为了更详细地解释某些部分,尽管我相信代码本身是以可以解释自身的方式编写的(例如,变量名是有意义的,逻辑是有意义的)。
Public Sub GroupCells()
Dim myRange As Range
Dim rowCount As Integer, currentRow As Integer
Dim firstBlankRow As Integer, lastBlankRow As Integer
Dim currentRowValue As String
Dim neighborColumnValue As String
'select range based on given named range
Set myRange = Range("rngList")
rowCount = Cells(Rows.Count, myRange.Column).End(xlUp).Row
firstBlankRow = 0
lastBlankRow = 0
'for every row in the range
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, myRange.Column).Value
neighborColumnValue = Cells(currentRow, myRange.Column - 1).Value
If (IsEmpty(currentRowValue) Or currentRowValue = "") Then
'if cell is blank and firstBlankRow hasn't been assigned yet
If firstBlankRow = 0 Then
firstBlankRow = currentRow
End If
ElseIf Not (IsEmpty(currentRowValue) Or currentRowValue = "") Then
'if the cell is not blank and its neighbor's (to the left) value is 0,
'and firstBlankRow hasn't been assigned, then this is the firstBlankRow
'to consider for grouping
If neighborColumnValue = 0 And firstBlankRow = 0 Then
firstBlankRow = currentRow
ElseIf neighborColumnValue <> 0 And firstBlankRow <> 0 Then
'if firstBlankRow is assigned and this row has a value with a neighbor
'who isn't 0, then the cell one row above this one is to be considered
'the lastBlankRow to include in the grouping
lastBlankRow = currentRow - 1
End If
End If
'if first AND last blank rows have been assigned, then create a group
'then reset the first/lastBlankRow values to 0 and begin searching for next
'grouping
If firstBlankRow <> 0 And lastBlankRow <> 0 Then
Range(Cells(firstBlankRow, myRange.Column), Cells(lastBlankRow, myRange.Column)).EntireRow.Select
Selection.Group
firstBlankRow = 0
lastBlankRow = 0
End If
Next
End Sub