Results 1 to 3 of 3

Thread: Select traversed text in Word using Search

  1. #1
    VBAX Regular
    Mar 2016

    Select traversed text in Word using Search

    I edit scientific papers in Word, where strings like this often occur: "...procedure. In this study, we found that alimentary tract infections..." In this example, I'd want to delete everything from "In" to "alimentary", and capitalize its first letter. The result would be "...procedure. Alimentary tract infections...".

    To accomplish this, I'm trying to have a macro begin by selecting everything from the insertion point back to the previous period and space (i.e., end of the previous sentence). I'll then have the macro move right a tad, delete the selection, and do the capping. But to select the text, I'm trying to use Search to find the preceding period/space, and select the intervening text as well.

    I seem to remember from years ago that you could use Search to select all traversed characters up to a search string, but that doesn't seem to work now.

    I've tried just moving the insertion point to the sentence end by using Search, but I've no idea how to select from there to, in this case, the first letter of "alimentary".

    Is there a way to select traversed characters in VBA? Or should I use another method?

    I'm using Word 2007, Win10, and VG 6.5.

  2. #2
    Easy enough in VBA by manipulating the range. With the cursor in the word you wish to keep i.e. alimentary run the following

    Sub Macro1()
    'Graham Mayor - - Last updated - 02 Jul 2021 
    Dim oRng As Range
        Set oRng = Selection.Words(1) 'set a range to the word that contains the cursor
        With oRng
            .Characters(1).Case = wdUpperCase 'make the first character of that word upper case
            .Collapse 1 'collapse the range to its start
            .MoveStartUntil Chr(46), wdBackward 'move the start to the previous full stop/period
            .MoveStartWhile Chr(32) 'move back to retain the space after the full stop/period
            .Text = "" 'clear the range
        End With
        Set oRng = Nothing
    End Sub
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes

  3. #3
    VBAX Regular
    Mar 2016
    Thank you so much, Graham; your macro works perfectly. It'll save me much time. And thanks for your notations as well; they'll help me understand how the macro works.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts