I am trying to ungroup and regroup a series of groups I've stored in arrays. When I run it, however, I get the following error:
Run-time error '1004':
Ungroup method of Range class failed
My code is below. The xxxDim variables are used to identify if an array exists. I have previously identified all the sSub, eSub, sGroup, eGroup, sCat and eCat variables correctly so the actual values are not of concern. I've done the ungrouping and regrouping manually using the exact ranges I refer to so I do not believe I am referring to a range that it is having difficulty figuring out what to ungroup/group.
I have used the ungroup and group methods using this format (.Range("A" & variable & ":A" & variable).ungroup) before without issue.
''''' START WITH UNGROUPING EVERYTHING '''''
''''' SUB-MODELS '''''
If sSubDim = True Then 'This Array has been dimensioned and therefore has at least one entry
For i = LBound(sSub) To UBound(sSub)
.Range("A" & sSub(i) & ":A" & eSub(i)).Ungroup 'Receive error on this line first
Next
End If
''''' GROUPS '''''
If sGroupDim = True Then 'Multiple groups exist
For i = LBound(sGroup) To UBound(sGroup)
.Range("A" & sGroup(i) & ":A" & eGroup(i)).Ungroup
Next
End If
''''' CATEGORY '''''
.Range("A" & sCat & ":A" & eCat).Ungroup
''''' NOW GROUP EVERYTHING '''''
''''' SUB-MODELS '''''
If sSubDim = True Then 'This Array has been dimensioned and therefore has at least one entry
For i = LBound(sSub) To UBound(sSub)
.Range("A" & sSub(i) & ":A" & eSub(i)).Group
Next
End If
''''' GROUPS '''''
If sGroupDim = True Then 'Multiple groups exist
For i = LBound(sGroup) To UBound(sGroup)
.Range("A" & sGroup(i) & ":A" & eGroup(i)).Group
Next
End If
''''' CATEGORY '''''
.Range("A" & sCat & ":A" & eCat).Group
''''' START WITH UNGROUPING EVERYTHING '''''
Well there's the problem.
Before you can do this:

You need to make sure the things are grouped in the first place.
Calling Range.Ungroup on cells that aren't grouped, will raise the error you're getting.
I haven't found a way to avoid the error in the 30 seconds I devoted to trying, so a quick-and-dirty work-around would be to wrap the "dangerous" call into its own procedure, and swallow any errors that it throws:
Private Sub UngroupSafely(ByVal target As Range)
On Error Resume Next
target.Ungroup
Err.Clear ' Err.Number will be 1004 if target was already ungrouped
On Error GoTo 0
End Sub
Thus:
If sSubDim Then
For i = LBound(sSub) To UBound(sSub)
UngroupSafely .Range("A" & sSub(i) & ":A" & eSub(i))
Next
End If
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With