Search code examples
vbavstopowerpointoffice-interop

How to group a number of shapes on another PowerPoint.Slide


I want to group a number of shapes in another slide. The task seems very simple. However, the problem is the shapes needed to be grouped is not on the current slide.

For example,

The current slide is slide number 2. My shapes needed to be grouped are on the slide number 10. When a shape on the slide number 10 get selected, it always causes error. It seems that, we cannot change the slide selection.

My code is follow:

PowerPoint.Slides allSlides = ppApp.ActivePresentation.Slides;

for (int i = 1; i <= allSlides.Count; i++)

{

PowerPoint.Slide slide = allSlides[i]; if (slide.SlideId == 10) { //- Select the slide first slide.Select(); //- Select (assuming) shape1 and shape3 slide.Shapes[1].Select(); //- Error: The shape1 cannot be selected???? slide.Shapes[3].Select(Microsoft.Office.Core.MsoTriState.msoFalse); PowerPoint.ShapeRange shapeRange = ppApp.ActiveWindow.Selection.ShapeRange; shapeRange.Group(); } }

Solution

  • Unless there's no way around it, NEVER select slides or shapes. And there's almost never a situation where you need to select them.

    In VBA, if you want to work with something on Slide 10:

    Dim oGrpShp as shape 
    
    With ActivePresentation.Slides(10)
      ' And here you could work with the slide's ShapeRange
      set oGrpShp = .Shapes.Range.Group
      ' now you can work with the group as needed:
      oGrpShape.left = 300 ' or whatever
    End With
    

    If you try this on a slide that includes placeholders, it will error; you cannot include placeholders in a group.