# Help needed with recursion: delete all empty group layers

Question asked by deleted-user-VeC5jUIlNXtq on Aug 26, 2013
Latest reply on Aug 26, 2013 by deleted-user-VeC5jUIlNXtq
Hi all,

I will spare the details of why my map has several empty group layers unless anyone is interested, though it's not likely to be relevant at this point. We have a map of group layers with several more sets of nested group layers within (to keep similar datasets organized).

I'm trying to set something up to loop through the entire table of contents (say, 6 major group layers), check if a group layer is empty (i. e. contains no feature layers), if it is remove it, otherwise do nothing.

I'll post the code below, and the error I'm getting is "Value does not fall within the expected range" which I'm guessing means that the For loop is breaking (in: Public Sub recursiveSearch(ByVal pLayer As ILayer))
. My theory is that deleting the group layer takes the total count down by 1, thus having the for loop sitting at z = 2 when the pMap.LayerCount - 1 is only 1 now. But that's a working theory :P

In the main part of the code:

`        For z = 0 To pMap.LayerCount - 1             pLayerCheck = pMap.Layer(z)             Call recursiveSearch(pLayerCheck)         Next z`

Basically, send each major group layer to the functions below. Any assistance is appreciated and please let me know if more info is required.

Thank you!

`Public Sub deleteGroupLayer(ByVal pLayer As ILayer)         Dim pMxDoc As IMxDocument         Dim pMap As IMap         Dim pTempLayer As ICompositeLayer          pMxDoc = My.ArcMap.Document         pMap = pMxDoc.FocusMap          If TypeOf pLayer Is ICompositeLayer Then             pTempLayer = pLayer             If pTempLayer.Count = 0 Then                 pMap.DeleteLayer(pLayer)             End If         End If       End Sub      Public Sub recursiveSearch(ByVal pLayer As ILayer)          Dim bContinue As Boolean         bContinue = True          Dim iLayerCount As Integer         If Not TypeOf pLayer Is ICompositeLayer Then             Exit Sub         Else             Dim pCompLayer As ICompositeLayer             Dim pSubLayer As ILayer             pCompLayer = pLayer             iLayerCount = pCompLayer.Count             For SubLayerIndex = 0 To iLayerCount - 1                 pSubLayer = pCompLayer.Layer(SubLayerIndex)                 recursiveSearch(pSubLayer)                 Call deleteGroupLayer(pSubLayer)             Next SubLayerIndex         End If      End Sub`