Range vs Selection


Using the Range Object Instead of the Selection Object

Since the Range objects shares a lot of the same properties as the Selection object using the Range object is recommended unless you need to see the changes for some reason.
The macro recorder will often generate code that uses the Selection property to manipulate the Selection object.
However, you can usually accomplish the same task with fewer instructions by using one or more Range objects.
In most cases, Range objects are preferred over the Selection object for the following reasons:


Reasons for Using Range

*) You can define and use multiple Range objects, whereas you can only have one Selection object per document window.
*) Manipulating Range objects doesn't change the selected text.
*) The user will not see anything when a Range object is being manipulated.
*) Manipulating Range objects is faster than working with the Selection.
*) You can always use the Range.Select method to make a range selected.
*) Some properties and methods are not available to the Selection object.
*) Using the Range Method to Return a Range Object


Example 1

Both of the preceding examples change the formatting in the active document however the first one changes the current selection.
This macro applies bold formatting to the first two words in the document.

Selection.HomeKey Unit:=wdUnits.wdStory 
Selection.MoveRight Unit:=wdUnits.wdWord, _
                    Count:=2, _
                    Extend:=wdMovementType.wdExtend
Selection.Font.Bold = wdConstants.wdToggle

The following example accomplishes the same task without using the Selection object.
The Start and End positions refer to the character positions in the active document.

ActiveDocument.Range(Start:=0, End:=ActiveDocument.Words(2).End).Bold = True 

Example 2

The following example applies bold formatting to the first two words in the document, and then it inserts a new paragraph.

Selection.HomeKey Unit:=wdUnits.wdStory 
Selection.MoveRight Unit:=wdUnits.wdWord, _
                    Count:=2, _
                    Extend:=wdMovementType.wdExtend
Selection.Font.Bold = wdConstants.wdToggle
Selection.MoveRight Unit:=wdUnits.wdCharacter, _
                           Count:=1
Selection.TypeParagraph

The following example accomplishes the same task as the preceding example without using the Selection object.

Dim objRange As Range 
Set objRange = ActiveDocument.Range(Start:=0, End:=ActiveDocument.Words(2).End)
objRange.Bold = True
objRange.InsertParagraphAfter

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext