Getting the character before the cursor?

J

Jun

How do you get the previous character where the cursor is placed?

I've tried using Word's goto but it doesn't seem to work.

Thanks.
 
J

Jay Freedman

Jun said:
How do you get the previous character where the cursor is placed?

I've tried using Word's goto but it doesn't seem to work.

Thanks.

Hi Jun

Besides the fact that Selection.GoTo is a nasty kluge, you really shouldn't
move the selection around while the user is looking at the screen. Instead,
use a Range object. There are several ways to do it, but this is probably
the quickest:

Dim oRg As Range
' if Selection.Start = 0 then there isn't any previous char
If Selection.Start > 0 Then
Set oRg = ActiveDocument.Range( _
Selection.Start - 1, Selection.Start)
MsgBox oRg.Text
End If

It's possible that the "character" before the selection is a graphic, a
table, or some other non-text item. Be sure to allow for that in your code.
 
H

Helmut Weber

Sub Macro1()
On Error GoTo NoCharacter
MsgBox Selection.Range.Previous
Exit Sub
NoCharacter:
MsgBox "no previous character"
End Sub
 
J

Jun

Thanks. That worked out fine.

Jay Freedman said:
Hi Jun

Besides the fact that Selection.GoTo is a nasty kluge, you really shouldn't
move the selection around while the user is looking at the screen. Instead,
use a Range object. There are several ways to do it, but this is probably
the quickest:

Dim oRg As Range
' if Selection.Start = 0 then there isn't any previous char
If Selection.Start > 0 Then
Set oRg = ActiveDocument.Range( _
Selection.Start - 1, Selection.Start)
MsgBox oRg.Text
End If

It's possible that the "character" before the selection is a graphic, a
table, or some other non-text item. Be sure to allow for that in your code.
 

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