Subscribe to andrewsw's Blog        RSS Feed
-----

Word VBA - Avoiding Selection

Icon Leave Comment
Here is some code that I supplied in response to a question on SO, which finds the text between the words "Title" and "Address".

Sub FindIt()
    Dim blnFound As Boolean
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rngFound As Range
    Dim strTheText As String

    Application.ScreenUpdating = False
    Selection.HomeKey wdStory
    Selection.Find.Text = "Title"
    blnFound = Selection.Find.Execute
    If blnFound Then
        Selection.MoveRight wdWord
        Set rng1 = Selection.Range
        Selection.Find.Text = "Address"
        blnFound = Selection.Find.Execute
        If blnFound Then
            Set rng2 = Selection.Range
            Set rngFound = Activedocument.Range(rng1.Start, rng2.Start)
            strTheText = rngFound.Text
            MsgBox strTheText
        End If
    End If
    'move back to beginning
    Selection.HomeKey wdStory
    Application.ScreenUpdating = True
End Sub

I like this code, but knew that it could be improved. The Selection Object represents the cursor position or selected text and I believed that it should be possible to work without this, hopefully with the Range Object.

Microsoft MVP Jay Freedman kindly supplied me with the following much improved version.

Jay Freedman said:

There is only one Selection, and it represents the cursor/insertion point/extended selection on the screen. A Range is similar but invisible and not linked to the cursor, and you can have more than one.


Sub RevisedFindIt()
' Purpose: display the text between (but not including)
' the words "Title" and "Address" if they both appear.
    Dim rng1 As Range
    Dim rng2 As Range
    Dim strTheText As String
    
    Set rng1 = Activedocument.Range
    If rng1.Find.Execute(FindText:="Title") Then
        Set rng2 = Activedocument.Range(rng1.End, Activedocument.Range.End)
        If rng2.Find.Execute(FindText:="Address") Then
            strTheText = Activedocument.Range(rng1.End, rng2.Start).Text
            MsgBox strTheText
        End If
    End If
End Sub

Because the cursor never moves there is no need to turn off the screen-updating, or to position the cursor when the code finishes.

Recorded Macros will make constant use of Selection. I believe that, with a little effort, most macros and Word VBA code can be improved by removing references to Selection.

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

October 2020

S M T W T F S
    123
45678910
11121314151617
18192021222324
25 26 2728293031

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    1 user(s) viewing

    1 Guests
    0 member(s)
    0 anonymous member(s)

    Google

    Categories