PDA

View Full Version : Alternative way to determine current cursor position in text box



ZOW
05-25-2010, 10:24 AM
Hi all,

Shyam Pillai graciously shares the code to determine on which paragraph is the cursor currently positioned inside a text box in an URL which I can't share due to forum rules, but it is easy to find by googling "powerpoint VBA cursor position"


The reason for joining the forum and this post is to propose an alternative to his code. We think this is more straight-forward, but surely a lot of you know a lot more VBA than us and thus can better judge its efficiency.


Without further ado:

Sub WhichParagraphIsTheCursorOn()

'Determines the current cursor position in the selection
'(Also counts number of paragraphs selected)
'(Will NOT work inside tables)

' --------------------------------------------------------------------------------
' Copyright ©2010 Zebra on Wheels, All Rights Reserved.
' --------------------------------------------------------------------------------
' You are free to use this code within your own applications, add-ins,
' documents etc but you are expressly forbidden from selling or
' otherwise distributing this source code without prior consent.
' This includes both posting free demo projects made from this
' code as well as reproducing the code in text or html format.

' Check that selection type is text
If ActiveWindow.Selection.Type = ppSelectionText Then

' Count lines selected
With ActiveWindow.Selection.TextRange
SelectedParagraphs = .Characters(Start:=.Start, Length:=.Length).Paragraphs.Count
End With

' Check that only one paragraph is selected
If SelectedParagraphs < 2 Then

' ########################################################################### ##
' This is where the "magic" begins
' ########################################################################### ##

' Retrieve the cursor position in number of characters from the beginning of the text inside the text box
CurrentCursorPositionInCharacters = ActiveWindow.Selection.TextRange.Start

' Select the all the text in the shape from the beginning until the currentcursor position
' and count the paragraphs in the selection
With ActiveWindow.Selection.ShapeRange.TextFrame
ParagraphNumber = .TextRange.Characters(Start:=0, Length:=CurrentCursorPositionInCharacters).Paragraphs.Count
End With

MsgBox "Cursor is on paragraph Number: " & ParagraphNumber

' ########################################################################### ##
' "Magic" ends - simple, no?
' ########################################################################### ##
Else
MsgBox "You have selected " & SelectedParagraphs & " paragraphs." & vbCrLf & vbCrLf & _
"Please do not select text spanning more than one paragraph" & vbCrLf & vbCrLf & _
"and try again."
End If
Else
MsgBox "Please place the cursor inside a text box and try again"
End If
End Sub

Feedback is appreciated. :)