f00dFights
New Member
- Joined
- Jul 12, 2022
- Messages
- 12
- Office Version
- 365
- Platform
- Windows
Hi,
ive been working on a group by function however ive run into an issue, because when the macro comes across a sheet with one row then it throws an exception at the commented line below when really it should escape if it cant group a row.
Im sure its probably an easy fix but ive tried a few workarounds such as elseif conditions but I can't quite find a fix
ive been working on a group by function however ive run into an issue, because when the macro comes across a sheet with one row then it throws an exception at the commented line below when really it should escape if it cant group a row.
Im sure its probably an easy fix but ive tried a few workarounds such as elseif conditions but I can't quite find a fix
VBA Code:
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
End With