Excel VBA-分组空白之间的行

时间:2019-01-31 19:05:52

标签: excel vba grouping

和我一起承受,我在这里问的第一个问题。

作为更大的格式化过程的一部分,我试图将原始数据提取中的行分组为空白小计行之间的轮廓。

示例数据看起来像(抱歉,仍然是新用户,就我所知,不允许粘贴。):     Example Data Example Result

开始研究我在Grouping Rows in VBA中找到的答案

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

它将空白单元格分组在一起,但是我需要弄清楚如何使lastBlankRow在下一个数据块之后拾取下一个空白行。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用嵌套在Do While中的For-Next循环,并在B列中保留非空白单元格的数量,然后使用该数量-1进行分组,然后添加这取决于您的迭代。

通过重新测试数据结构进行了测试,并获得了预期的结果:

Sub GroupRows()

    Dim r As Long
    Dim i As Long
    Dim rowCount As Long

    rowCount = Range("A" & Rows.Count).End(xlUp).Row

    For i = 2 To rowCount
        r = 0
        Do While Range("B" & i + r) <> "" And Not IsEmpty(Range("B" & i + r))
            r = r + 1
        Loop
        Range("B" & i & ":B" & i + r - 1).Rows.Group
        i = i + r
    Next i

End Sub