How do I insert text at the cursor insertion point based on adjacent text or surrounding word? RRS feed

  • Question

  • I’m having difficulty understanding the proper methods to use for dealing with the following scenario: If no text is currently selected, I need to detect whether the insertion point is in the middle of a word or adjacent to a word.  If the cursor is in the middle of a word, I want to select the word and replace the text with substitute text (e.g. replace a first name with the full name from a managed list).  This is easy enough to do with Range.Expand, Range.Select and setting Selection.Text.

    Alternately, if the cursor is beside a word, I want to insert a different word (i.e. a chosen full name from a list) and not affect the adjacent text/word (and ideally, insert a leading or trailing space to prevent conjoining words).  However, I can’t see any properties in the Range or Selection objects that differs and would allow me to tell the difference with a “non-selection” (i.e cursor is in a word or cursor is next to a word).  It seems odd that if the insertion point is beside a word it would return the first or last character of the adjacent word, even though nothing is selected.  The properties seem the same as if the insertion point is inside a word.  So what’s the best method/object in this scenario?

    Similarly, I am having trouble ensuring that if I do automatically insert text somewhere that it never interferes with whatever is adjacent to it.  Depending on the cursor position I see preceding or trailing text get replaced if I use the InsertBefore/After methods.

    Eric Legault (MVP: Outlook)
    Co-author, Microsoft Office 2013 Professional Step-By-Step
    Try Outlook Touch!

    Wednesday, July 29, 2015 5:24 PM


  • You can test whether the insertion point is in a word with code like:

    Dim Rng As Range
    With Selection
      If .Type = wdSelectionIP Then
        Set Rng = .Words.Last
        With Rng
          .End = .End - (Len(.Words.Last) - Len(Trim(.Words.Last)))
        End With
        If Rng.End = .End Then
          MsgBox "not in a word"
          MsgBox "in a word"
        End If
      End If
    End With
    Set Rng = Nothing

    Paul Edstein
    [MS MVP - Word]

    Thursday, July 30, 2015 12:15 AM

All replies