How to return the character before the cursor

T

Theo van der Ster

Hi, I often need to determine what the character before the cursor is. For the character after the cursor, this is easy

MsgBox Selection will do it.

To return the character before the cursor, I resort to this:

Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
MsgBox Selection

This seems unnecessary cumbersome. Is there any other way?

Thanks for helping.

Best regards,
Theo van der Ster
The Netherlands
 
S

Stefan Blom

Hmm, what are you trying to do exactly? None of your examples return a
single character.
 
T

Theo van der Ster

Hmm, what are you trying to do exactly? None of your examples return a

single character.



--

Stefan Blom

Microsoft Word MVP

Actally, the do. If nothing is selected, MsgBox Selection will return one character, the one immediately following it.

My second example selects the character preceding the insertion point.

I was just wondering if there was a way to know what character preceded the insertion point without actually selecting it.

Regards,
Theo
 
S

Stefan Blom

Taking into account that the current selection may not be in the main body
of the document, the following should work:

Sub GetCharToLeftOfSelection()
Dim r As Range
Set r = Selection.Range
If r.Start > 0 Then
r.End = r.Start
r.Start = r.Start - 1
MsgBox "The character to the left of the selection is """ _
& r.Text & """"
Else
MsgBox "There is no character to the left of the selection"
End If
End Sub
 
T

Theo van der Ster

Thank you, Stefan. I hadn't been back here so I only saw your answer today. Actually, I was wondering wether VBA had a default function for returning the character before the insertion point. Apparently not, so I'll have to use a bit more code.

Thanks for your thoughts on this.

Best regards,
Theo van der Ster
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top