Posts Tagged ‘PowerPoint 2007’

Function to Convert TextRange to TextRange2 Objects and Vice-Versa

March 13, 2009

PowerPoint 2007 introduced the TextRange2 object which enhances the features of the TextRange object.

You may find the need to switch from a TextRange object to a TextRnge2 object because of the enhanced features available there. Conversely, you may wish to switch from a TextRange2 object to a TextRange object so you can use the more traditional features available there. Let’s get into the code…

' Convert from TextRange to TextRange2.
Function TextRangeToTextRange2(TextRange As PowerPoint.TextRange) As Office.TextRange2
    With TextRange
        Set TextRangeToTextRange2 = .Parent.Parent.TextFrame2.TextRange.Characters(.Start, .Length)
    End With
End Function

I had a need to make extensive use of the new properties of the TextRange2 object. However, I had some legacy code which made use of the Font.Color and Font.Underline properties. Well, surprise, surprise, those properties are not available in the Font2 object. I wanted a simple solution, so I wanted to go from a Font2 object to a regular Font object.

The best way to do this is to make use of my function TextRange2ToTextRange. Here is some sample code:

Sub SetUnderline(TextRange2 As Office.TextRange2)
    ' TextRange2.Font.Underline = msoTrue would not work.
    ' This does not work because TextRange2's Font property is a Font2 object.
    ' The Font2 object has UnderlineColor and UnderlineStyle properties,
    ' not the old-style Underline property.
    ' Instead we use the conversion function:
    TextRange2ToTextRange(TextRange2).Font.Underline = msoTrue
End Sub

Similarly, the Color property is not a member of Font2, so if you want to set just a plain-old RGB color, you can use the function:

Sub MakeRed(TextRange2 As Office.TextRange2)
    TextRange2ToTextRange(TextRange2).Font.Color = vbRed
End Sub
Advertisements