Grouping Rows in VBA

后端 未结 2 458
时光说笑
时光说笑 2020-12-06 07:10

I have the code below that doesn\'t seem to be working. Essentially, rngList refers to a defined name range in Excel that is about 500 rows long and every

2条回答
  •  [愿得一人]
    2020-12-06 07:46

    I have used Sam's code to group without using column A. Thought others could find it useful.

    Sub Group_Jobs()
    
    Dim myRange As Range
    Dim rowCount As Integer, currentRow As Integer
    Dim firstBlankRow As Integer, lastBlankRow As Integer
    Dim currentRowValue As String
    Dim nextRowValue As String
    
    Application.ScreenUpdating = False 'Stop screen updating while grouping
    
    'select range based on given named range
    Set myRange = Range("A1:A1000")
    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
        nextRowValue = Cells(currentRow + 1, myRange.Column).Value
    
    'Assign firstBlankRow & lastBlankRow
        'if currentRowValue = NotBlank(Job#) And nextRowValue = NotBlank(Job#) Then Skip
        'if currentRowValue = Blank          And nextRowValue = Blank          Then Skip
        'if currentRowValue = NotBlank(Job#) And nextRowValue = Blank          Then is firstBlankRow
        'if currentRowValue = Blank          And nextRowValue = NotBlank(Job#) Then is lastBlankRow
        If Not (currentRowValue = "" Or currentRowValue = "") Then
            If (IsEmpty(nextRowValue) Or nextRowValue = "") Then
                firstBlankRow = currentRow + 1
            End If
        ElseIf (IsEmpty(currentRowValue) Or currentRowValue = "") Then
            If Not (IsEmpty(nextRowValue) Or nextRowValue = "") Then
                If firstBlankRow <> 0 Then
                    lastBlankRow = currentRow
                End If
            End If
        End If
        Debug.Print "Row " & currentRow; ": firstBlankRow: " & firstBlankRow; ", lastBlankRow: " & lastBlankRow
    
    'Group firstBlankRow & lastBlankRow
        'if first & last blank rows have been assigned, create a group
        If firstBlankRow <> 0 And lastBlankRow <> 0 Then
            'Debug.Print "Row: " & currentRow; ", Outline Level: " & ActiveSheet.Rows(currentRow).OutlineLevel
            If Not ActiveSheet.Rows(currentRow).OutlineLevel > 1 Then 'Ignore if last row is already grouped
                Range(Cells(firstBlankRow, myRange.Column), Cells(lastBlankRow, myRange.Column)).EntireRow.Select
                Selection.Group
            End If
            firstBlankRow = 0: lastBlankRow = 0 'reset the first/lastBlankRow values to 0
        End If
    Next
    
    Application.ScreenUpdating = True 'Start screen updating as macro is complete
    End Sub
    

提交回复
热议问题