Wednesday, January 16, 2013

How to find paragraph under cursor in PowerPoint 2010 VBA

The following VBA function returns paragraph under cursor in Microsoft PowerPoint 2010:
Function GetParagraphUnderCursor() As TextRange2
    On Error Resume Next
    First = ActiveWindow.Selection.TextRange.Start
    If Err.Number <> 0 Then
        Exit Function
    End If
    On Error GoTo 0
    Set ShapeRange = ActiveWindow.Selection.ShapeRange
    If (1 = ShapeRange.Count) And (14 = ShapeRange(1).Type) And (ShapeRange(1).HasTextFrame) Then
        For Each Paragraph In ShapeRange(1).TextFrame2.TextRange.Paragraphs
            If (Paragraph.Start <= First) And ((Paragraph.Start + Paragraph.Length - 1) >= First) Then
                Set GetParagraphUnderCursor = Paragraph
                Exit Function
            End If
        Next Paragraph
    End If
End Function

Sub Test()
    Dim Paragraph As TextRange2
    Set Paragraph = GetParagraphUnderCursor()
    If Paragraph Is Nothing Then
        MsgBox "No text selected!"
        MsgBox Paragraph.Text
    End If
End Sub

1 comment:

  1. Great tutorial for PowerPoint beginners. Sometimes I have to edit a presentation made by another employee of the company. So there are a lot of PP functions I need to know. There is a great article describing Common Errors Using PowerPoint for IT companies.