Thanks Chelsea:)
Shame there's no nice simple way to check if a layer is within a Group Layer, to use with your MoveLayerEx.
Anyway I did roughly what you advised (i hope!) and the function is kind-of working now.
Without On Error Resume Next it falls over, cos as soon as it has moved a layer out of a Group Layer then the looping-through fails as the number of layers is no longer valid. I guess there's a way to deal with this properly but my attempts failed:( As it is now, it works in most cases but sometimes fails to move a couple of the selected layers towards the bottom. At least it doesn't delete them like my first dodgy attempt!
Thanks for your help
Phil
Sub MoveLayersToTop()
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pCV As IContentsView
Set pCV = pMxDoc.CurrentContentsView
Dim pMap As IMap
Set pMap = pMxDoc.FocusMap
Dim pMapLayers As IMapLayers
Set pMapLayers = pMap
Dim pLayer As ILayer
Dim pLayer2 As ILayer
Dim pLayer3 As ILayer
Dim pSubLayer As ILayer
Dim pCompLayer As ICompositeLayer
Dim pCompLayer2 As ICompositeLayer
Dim lngX As Long
Dim lngY As Long
Dim lngZ As Long
Dim pSelectedItem As Variant
Dim pSetItem As Variant
Dim pSelectionSet As ISet
'get selected layers
Dim pFLayer As IFeatureLayer
Dim TheSelectionSet As esriSystem.ISet
Set TheSelectionSet = New esriSystem.Set
If (TypeOf pCV.SelectedItem Is IFeatureLayer) Then
TheSelectionSet.Add (pCV.SelectedItem)
ElseIf (TypeOf pCV.SelectedItem Is ISet) Then
Set TheSelectionSet = pCV.SelectedItem
End If
'1-Go through every layer in TOC
For lngX = 0 To pMxDoc.FocusMap.LayerCount - 1
On Error Resume Next
Set pLayer = pMxDoc.FocusMap.Layer(lngX)
'2a-For a normal layer not in any group layer
If Not TypeOf pLayer Is IGroupLayer Then
If TheSelectionSet.Find(pLayer) Then
pMap.MoveLayer pLayer, 0
'Wilma = MsgBox(pLayer.Name, , "Not Grouped")
End If
End If
'2b-If finds layer is Group Layer, then check within...
If TypeOf pLayer Is IGroupLayer Then
Set pCompLayer = pLayer
'3-Go through every layer in the Group Layer
For lngY = 0 To pCompLayer.Count - 1
On Error Resume Next
Set pLayer2 = pCompLayer.Layer(lngY)
'4a-For a normal layer within the Group Layer
If Not TypeOf pLayer2 Is IGroupLayer Then
If TheSelectionSet.Find(pLayer2) Then
pMapLayers.MoveLayerEx pCompLayer, Nothing, pLayer2, 0
'Wilma = MsgBox(pLayer2.Name, , pLayer.Name)
End If
End If
'4b-If finds a Group Layer within the Group Layer...
If TypeOf pLayer2 Is IGroupLayer Then
Set pCompLayer2 = pLayer2
'5-Go through every layer in the Group-within-Group
For lngZ = 0 To pCompLayer2.Count - 1
On Error Resume Next
'6-For a normal layer within the Group-within-Group
If Not TypeOf pCompLayer2.Layer(IngZ) Is IGroupLayer Then
Set pLayer3 = pCompLayer2.Layer(lngZ)
If TheSelectionSet.Find(pLayer3) Then
pMapLayers.MoveLayerEx pCompLayer2, Nothing, pLayer3, 0
'Wilma = MsgBox(pLayer3.Name, , pLayer2.Name & " " & pLayer.Name)
End If
End If
'End 5
Next lngZ
'End 4b
End If
'End 3
Next lngY
'End 2b
End If
'End 1
Next lngX
End Sub