How to return the character before the cursor

Discussion in 'Word VBA' started by Theo van der Ster, Aug 29, 2013.

  1. 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
     
    Theo van der Ster, Aug 29, 2013
    #1
    1. Advertisements

  2. Theo van der Ster

    Stefan Blom Guest

    Hmm, what are you trying to do exactly? None of your examples return a
    single character.
     
    Stefan Blom, Aug 29, 2013
    #2
    1. Advertisements

  3. 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
     
    Theo van der Ster, Aug 29, 2013
    #3
  4. Theo van der Ster

    Stefan Blom Guest

    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
     
    Stefan Blom, Sep 1, 2013
    #4
  5. 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
     
    Theo van der Ster, Sep 23, 2013
    #5
  6. Theo van der Ster

    Stefan Blom Guest

    Thanks for the feedback.
     
    Stefan Blom, Sep 24, 2013
    #6
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.