kate n
kate n

Reputation: 53

How to change slide layout programmatically in PowerPoint?

I need to change a slide's layout programmaticaly with C# (Add-In Express 2009 for Office and .NET is used). If the new layout is a predefined one then everything is fine, but not if I need to set a custom layout as a new one (without slide recreating). Unfortunately, I didn't find any information on how to do it, PowerPoint object model reference documentation didn't answer me as well. There is just the ability to create a new slide that uses custom layout.

I've done an experiment and have ensured that the Slide object stayed being the same while I have been changing layout both predefined and custom ones. I don't want to create a new slide when I need just switch the layout.

Is it possible at all? Please help me to find a way of doing it.

Upvotes: 5

Views: 5127

Answers (2)

David
David

Reputation: 41

You could do that, but it's really not recommended. Also, creating a new slide this way and applying the layout is prone to errors. In the following code snippet you can see how to retrieve a layout by name from the master....

private PowerPoint.CustomLayout DpGetCustomLayout(
        PowerPoint.Presentation ppPresentation, string myLayout)
{
   //
   // Given a custom layout name, find the layout in the master slide and return it
   // Return null if not found
   //
   PowerPoint.CustomLayout ppCustomLayout = null;

   for (int i = 0; i < ppPresentation.SlideMaster.CustomLayouts.Count; i++)
   {
       if (ppPresentation.SlideMaster.CustomLayouts[i + 1].Name == myLayout)
           ppCustomLayout = ppPresentation.SlideMaster.CustomLayouts[i + 1];
   }
      return ppCustomLayout;
}

then you can assign it to the slide as you saw above. However, if the layouts are incompatible, then results may be unpredictable. I assume that the slides are at least relatively the same. You should try to create a new slide and copy the content over to avoid being hostage to changes in the underlying theme or template.

See code descriptions for more on this.

Upvotes: 2

Todd Main
Todd Main

Reputation: 29155

The only way it will work is if your custom layout is actually used in the deck first. Then you simply take that layout and apply it to the slide you want. You could programatically create a new slide with your custom layout, use it's layout to apply to another slide and then delete that new slide you had created. Here's code to apply the custom layout (note that my ap.Slides(2) is a Custom Layout)

Sub ChangeLayout()
    Dim ap As Presentation
    Set ap = ActivePresentation
    Dim slide1 As Slide
    Set slide1 = ap.Slides(1)
    Dim customLayout As PpSlideLayout
    customLayout = ap.Slides(2).Layout
    slide1.Layout = ly
End Sub

Upvotes: 4

Related Questions