Excel VBA 按问题分组

Excel VBA 按问题分组

我一直在研究分组功能,但是我遇到了一个问题,因为当宏遇到只有一行的 sheet 时,它会在下面的注释行抛出一个异常,而实际上如果它不能对一行进行分组,它应该退出。

我确信这可能是一个简单的修复,但我尝试了一些解决方法,例如 elseif 条件,但我找不到解决办法

VBA 代码:

  Dim gruRng As Range
  Dim gruVari 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 gruRng = .Range("T4", .Cells(.Rows.Count, 2).End(xlUp))
    End With
   
    With gruRng
        'identify common groups in column S (Job No)
        j = 1
        gruVari = .Cells(j, 1).Value
       
        For i = 2 To .Rows.Count
           If gruVari <> .Cells(i, 1) Then
             ' Column S (Job No) has changed, create group
              gruVari = .Cells(i, 1)
              If i > j + 1 Then
                 .Cells(j + 1, 1).Resize(i - j - 1, 1).Rows.Group ' <- Throws exception here: Application-defined or object defined error
              End If
              j = i
              gruVari = .Cells(j, 1).Value
           End If
        Next
       
         'create last group
         If i > j Then
            .Cells(j + 1, 1).Resize(i - j - 1, 1).Rows.Group
         End If
        ' collapse all groups
        .Parent.Outline.ShowLevels RowLevels:=1

相关内容