Home > Blockchain >  How to get the text before the current selection
How to get the text before the current selection

Time:04-27

I'm trying to create a VBA macro for Word that inserts a field at the position of the cursor. The type of field shall depend on the text directly preceding the cursor. I find it surprisingly hard to access that text.

Here is what I've tried:

MsgBox "Text before selection: " & ActiveDocument.Range(Selection.Start - 10, Selection.Start).Text

This works fine in the main text but fails in other parts of the document (headers, footers, text frames, ...). The reason is that the range created by ActiveDocument.Range points to the main story range. Is there a way to create a Range for the story range of the Selection?

CodePudding user response:

Selection.Range is the already the method you are looking for: It creates a new Range object in the same story range as the selection. Store that Range in a variable and update its Start and End property to get the adjacent text.

This code gets the text before the selection, no matter which part of the document is selected:

Dim oRng As Range
Set oRng = Selection.Range
With oRng
    .End = .Start
    .Start = .Start - 10
    MsgBox "Text before selection: " & .Text
End With

Another option for updating both the Start and End property at once is the SetRange method.


Update: Through the With keyword, it is even possible to spare the variable declaration and assignment. I.e. this also works (but makes it harder to understand, how many objects are involved):

With Selection.Range
    .SetRange .Start - 10, .Start
    MsgBox "Text before selection: " & .Text
End With

CodePudding user response:

To get the text before the Selection, without moving the Selection, you could use:

With Selection.Range.Duplicate
    .SetRange .Start - 10, .Start
    MsgBox "Text before selection: " & .Text
End With

Alternatively, for something more meaningful than the preceding 10 characters (e.g. the preceding two words), you might use something like:

With Selection.Range.Duplicate
  .End = .Words.First.Start
  .MoveStart wdWord, -2
  MsgBox "Text before selection: " & .Text
End With
  • Related