Can someone offer up a Christmas present here? I'm stuck on how to collapse all layers in my ArcMap projects (9.3). I've tried a few bits of sample code, but they all seem to fail for some reason or other.

Some of the layers might be grouped, and some are imagery or WMS layers if that makes a difference.

Here is some code I have tinkered with, but does not work:

Dim pMxdoc As IMxDocument
Set pMxdoc = ThisDocument
Dim pFeatLayer As IFeatureLayer
Dim pEditLayers As IEditLayers
Set pEditLayers = pEditor
Dim pMap As IMap
Set pMap = pMxdoc.FocusMap
Dim pLayer As ILayer

'Collapse any expanded grouplayers
Dim pGroupLayer As IGroupLayer
For i = 0 To pMxdoc.FocusMap.LayerCount - 1
Set pLayer = pMxdoc.FocusMap.Layer(i)
'Check if the reached layer is a group
If TypeOf pLayer Is IGroupLayer Then
Set pGroupLayer = pLayer
if pGroupLayer.Expanded = true Then
pGroupLayer.Expanded = false
End if
End If
Next i
pMxdoc.UpdateContents
pMxdoc.ActiveView.Refresh


-
Have you tried pGroupLayer.Expanded = false? That's the syntax for C#, so just taking a stab at it. –  Chad Cooper Dec 19 '11 at 19:33
Hi Chad, I cleaned up the code as you suggested. It does work for the Grouped layers now, so it's close... What interface or ArcObjects should be used for non-grouped layers? I don't see the Expanded property available with pLayer. –  User Error Dec 19 '11 at 20:34
see my answer below. –  Chad Cooper Dec 19 '11 at 20:47

Try pGroupLayer.Expanded = false to collapse the group. As far as non-grouped layers, here is a snippet I used to collapse the legends on rasters in the TOC, it uses the ILegendGroup interface:

// Collapse the legends on each raster
ILegendInfo legendInfo = (ILegendInfo)pRasterLayer.Renderer;
ILegendGroup legendGroup = (ILegendGroup)legendInfo.get_LegendGroup(0);
legendGroup.Visible = false;

-
Note that some layers can have more than one legend group (unique value renderers, etc.) so to be sure, you'll want to iterate over the legend groups and set each one's Visible property to false: forums.esri.com/… –  blah238 Dec 19 '11 at 20:49
Thank you both, this is much more complicated than I imagined. Michael Knight's code on the ESRI forum gets as far as a grouped annotation layer in my .mxd then crashes with a Type mismatch error. Not sure what is special about one of the featureclasses in there but the "09 - Stream Labels" one doesn't have a "+" or "-". –  User Error Dec 19 '11 at 22:05
@UserError - that's odd. Is the layer valid? I would think that it would have to have some sort of symbology associated with it. Maybe test for the presence of the legend group first, and if there isn't one, move on? –  Chad Cooper Dec 19 '11 at 22:22

When the layer is an IAnnotationLayer, use the ICompositeLayer2 interface: ICompositeLayer2 compositeLayer = (ICompositeLayer2)featureLayer; compositeLayer.Expanded = false;

-