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.
The following example was created using the macro recorder.
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 

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

activedocument.range(start := mydoc.sentances(2).start, end := mydoc.sentances(4).end) 

Both of the preceding examples change the formatting in the active document however the first one changes the current selection.


In most cases, Range objects are preferred over the Selection object for the following reasons:
0) You can define and use multiple Range objects, whereas you can only have one Selection object per document window.
1) Manipulating Range objects doesn't change the selected text.
2) The user will not see anything when a Range object is being manipulated.
3) Manipulating Range objects is faster than working with the Selection.
4) You can always use the Range.Select method to make a range selected.
5) Some properties and methods are not available to the Selection object.
6) Using the Range Method to Return a Range Object


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