Code to move selected layers to the top of the TOC, ArcMap 9.2 - any help please?

Discussion created by philatvwuk on Aug 16, 2011
Latest reply on Aug 21, 2011 by philatvwuk
Hi there

I'm trying to put together some code that moves any/all selected layers to the top of the Table of Contents.  I'm planning to put it on the TOC context menu(s), to let users easily bring to the top just the relevant layers amongst the >50 layers in >8 group layers that are on our standard MXD.

Using the trusty Ctrl-C, Ctrl-V and posts on the old forums by greater minds than mine, i've got:-

[INDENT]Private Sub SortLayers_Click()

  Dim pMxDocument As IMxDocument
  Dim pContentsView As IContentsView
  Set pMxDocument = Application.Document
  Set pContentsView = pMxDocument.CurrentContentsView
  Dim pMap As IMap
  Set pMap = pMxDocument.FocusMap
  Dim pSelectedItem As Variant
  Dim pLayer As ILayer
  Dim pSetItem As Variant
  Dim pSelectionSet As ISet
  If Not IsNull(pContentsView.SelectedItem) Then
    Set pSelectedItem = pContentsView.SelectedItem
    If TypeOf pSelectedItem Is ILayer Then
      Set pLayer = pSelectedItem
      pMap.MoveLayer pLayer, 0
    ElseIf TypeOf pSelectedItem Is ISet Then
      Set pSelectionSet = pSelectedItem
      For Count = 0 To pSelectionSet.Count - 1
        Set pSetItem = pSelectionSet.Next
        If TypeOf pSetItem Is ILayer Then
          Set pLayer = pSetItem
          pMap.MoveLayer pLayer, 0
        End If
      Next Count
    End If
  End If
  End Sub[/INDENT]

...which does the job except for one slightly unfortunate side-effect - if the selected layer is within a group layer then the entire group layer goes AWOL:eek:

Any ideas gratefully received!  Maybe something using ICompositeLayer?