Working with Tags (and a bit about Functions)
Tags are wonderfully useful things. Think of them as invisible "sticky notes" that you can attach to presentations, slides within presentations, and shapes on slides. You can attach lots of tags to each of these, too. No "one per object" limit. In fact, we're not sure what the limits are, but we've added several megabytes of tags to test presentations without suffering any especially evil side effects.
You can use tags to record information about objects, to make them easier to identify later or for any other purpose you have in mind. Tags are always string data (though binary tags may be exposed in PowerPoint 2007). Tags consist of a name and a value (if you're familiar with VB/VBA's Collections, you'll feel right at home here).
Suppose you want to identify a shape in such a way that you can locate it later. Select the shape then run this to tag it:
With ActiveWindow.Selection.ShapeRange(1) .Tags.Add "ShapeName", "Moose" End With
The shape now has a tag named "ShapeName" and the tag's value is "Moose"
Now suppose you want to locate our shape whose ShapeName tag is Moose. You could use "inline" code ... that is, the same code, over and over, every time you need to do this. Or you could save trouble and time by putting most of the code in a function you can call when you need it. That's what we'll do next. Here's a function to get the shape with a specific tag name/value from a particular slide:
Function GetShapeTaggedWith(sTagName as String, _ sTagValue as String, _ oSl as Object) as Shape ' Returns a reference to the shape ' whose sTagName tag is sTagValue ' on the slide, slide master, layout, notesmaster etc. ' referenced by oSl Dim oSh as Shape Dim oTemp as Shape On Error GoTo ErrorHandler Set oTemp = Nothing ' look at each shape on the slide For Each oSh in oSl.Shapes ' see if it has the tag name and value we're after If oSh.Tags(sTagName) = sTagValue then ' It's the shape we're after Set oTemp = oSh Exit For End if Next ' oTemp now contains a reference to the shape ' we're after (if it was on the slide) or is nothing ' The function returns it either way: Set GetShapeTaggedWith = oTemp NormalExit: Exit Function ErrorHandler: MsgBox "Error: " & Err.Number & " " & Err.Description Resume NormalExit End Function
Now we can use this snippet in our main code when we need to locate the shape whose ShapeName tag is Moose:
Dim oSh as Shape Set oSh = GetShapeTaggedWith("ShapeName", "Moose", _ ActiveWindow.Selection.SlideRange(1)) If Not oSh Is Nothing Then ' we found it ' do something with it ... for example: ' move it an inch to the right oSh.Left = oSh.Left + 72 End If
See How do I use VBA code in PowerPoint? to learn how to use this example code.