This is the code from the Macro Recorder demonstration
The Macro Recorder is handy for little quickie macros and especially for learning how PowerPoint's object model works, but it doesn't produce code that's very useful as is.
This demonstrates how you can make the recorder produce more useful code and how you can take what you've learned from it and tweak it into something more generally useful.
Suppose the corporate colors have just changed from green to red. You've got dozens or hundreds of presentations with the fills set to the old green and need to change them all. Fast.
You open one in PPT and record a macro while you select a shape and change its color from green to red.
Here's what you end up with:
Sub Macro1() ActiveWindow.Selection.SlideRange.Shapes("Rectangle 5").Select With ActiveWindow.Selection.ShapeRange .Fill.Visible = msoTrue .Fill.ForeColor.RGB = RGB(255, 0, 102) .Fill.Solid End With ActivePresentation.ExtraColors.Add RGB(Red:=255, Green:=0, Blue:=102) End Sub
This has a few problems:
In short, it solves the problem of changing ONE shape on ONE slide from green to red. And that's it. And it creates other potential problems in the process.
But it did show us how to change a shape's color in PowerPoint VBA, so it's not totally useless.
Let's see if we can get it to do something more general.
Select the green rectangle first, THEN record a macro while changing it to red:
Sub Macro2() With ActiveWindow.Selection.ShapeRange .Fill.ForeColor.RGB = RGB(255, 0, 102) .Fill.Visible = msoTrue .Fill.Solid End With End Sub
That's better. A lot better. It works on any selected shape and in fact it works on multiple selected shapes.
It still sets a few extra properties but we can comment those out.
Now you can select all the shapes on each slide, run this macro and ...
No. Don't do that. It'll change all the green selected shapes to red, true. Also all the blue ones and purple ones and so on. ALL the selected shapes.
So you still have to go from slide to slide selecting all (and ONLY) the green shapes, then running the macro again and again.
Enough of this. Here's how you and the other VBA Pros really do this kind of stuff:
Sub GreenToRed() Dim oSh As Shape Dim oSl As Slide ' Look at each slide in the current presentation: For Each oSl In ActivePresentation.Slides ' Look at each shape on each slide: For Each oSh In oSl.Shapes ' IF the shape's .Fill.ForeColor.RGB = pure green: If oSh.Fill.ForeColor.RGB = RGB(0, 255, 0) Then ' Change it to red oSh.Fill.ForeColor.RGB = RGB(255, 0, 0) End If Next oSh Next oSl End Sub
In less time than it takes you to get your finger off the mouse button, that will change thousands of shapes on hundreds of slides from green to red. And it only touches the shapes that are the exact shade of green we've targeted, no other colors.
Click Next to continue