VBA Code


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



ActiveDocument.Words(1).case = wdCharacterCase.wdUpperCase 

ActiveDocument.Paragraphs(1).Range.Font = objFont 
ActiveWindow.Selection.Font = objFont

ActiveWindow.Selection.Font.ColorIndex = wdColorIndex.wdAuto 
ActiveWindow.Selection.Font.ColorIndex = wdColorIndex.wdRed

Getting the current selection

Dim objRange As Range 
Set objRange = Application.Selection.Range

Turn off extension mode

Selection.ExtendMode = False 

This refers to the whole document

objRange = ActiveDocument.Range() 

Documents.Add Template:="Normal", NewTemplate:=False 
ActiveDocument.Content.Information(wdInformation.wdActiveEndAdjustedPageNumber)
ActiveDocument.Close SaveChanges := wdDoNotSaveChanges

Copy the entire document

Selection.HomeKey Unit:=wdUnits.wdStory 
Selection.Extend
Selection.WholeStory

Looping until the end of the document

Do Until ActiveDocument.Bookmarks("\Sel") = ActiveDocument.Bookmarks("\EndOfDoc") 
   ...
Loop


Selection.Paragraphs(1).Range.End 
Selection.StartOf unit:=wdParagraph, Extend:=wdMove
Selection.Paragraphs(1).Range.Select
Selection.Paragraphs(1).Range.text
Selection.SetRange Start:=Selection.Paragraphs(1).Range.Start, End:=Selection.Paragraphs(1).Range.End

VBA - Cursor Position



Is there nothing selected

If (Selection.Start = Selection.End) Then 
End If


Document, Start - Is the cursor at the start of the document



Document, End - Is the cursor at the end of the document

Is the cursor at the end of the document

If ((Selection.Type = wdSelectionIP) And (Selection.End = ActiveDocument.Content.End - 1)) Then 
End If

Does the current selection include the final paragraph mark.

If (Selection.Type = wdSelectionNormal) And (Selection.End = ActiveDocument.Content.End)) Then 
End If

If Selection.Type = wdSelectionType.wdSelectionIP And _ 
   Selection.End = ActiveDocument.Content.End - 1 Then

End If

Paragraph, Start - Is the cursor at the start of the paragraph

If (Selection.Start = Selection.Paragraphs(1).Range.Start) Then 
End If

For ranges substitute the range for the selection.



Paragraph, End - Is the cursor at the end of the paragraph

If (Selection.End = Selection.Paragraphs(1).Range.End - 1) Then 
End If

Detect if the first character in the selection is alphanumeric

If Selection.Characters(1) Like "[a-zA-Z0-9] Then 
   Call Msgbox("Alphanumeric")
End If

Detect if the first character in the selection is alphanumeric

If Selection.Characters(1) Like "[!a-zA-Z0-9] Then 
   Call Msgbox("NOT Alphanumeric")
End If

VBA - Selection Object

The Selection object represents the current selection in a window or pane.
The current selection is either the area that is currently highlighted or if nothing is highlighted then it represents the insertion point.
There can only be one Selection object per window (or pane) and there is only ever one selection that is currently active.


Creating a Selection Object

You can use the Pane object from the active Window object to return the current selection at any time.
The Selection object can only be returned from either an Application, Pane and Window object.

Dim objSelection As Selection 
Set objSelection = Application.ActiveWindow.ActivePane.Selection
Set objSelection = Application.ActiveWindow.Selection
Set objSelection = Application.Selection
Set objSelection = ActiveWindow.Selection
Set objSelection = ActiveWindow.Panes(1).Selection
Set objSelection = ActivePane.Selection
Set objSelection = Selection
Set objSelection = ActiveDocument.ActiveWindow.Selection

Important Differences

The Range and Selection objects refer to a continuous area within a document.
The Range and Selection objects are very similar but have some important differences:
1) There can only be one Selection object per window (or pane), but there can be many range objects
2) The active selection is always highlighted, whereas the range object is not visible unless selected.
The Selection object shares a lot of the same properties and methods as the Range object.


Redefining a Selection Object

You can use the SetRange method to redefine an existing Selection object
The following example defines a selection object to the be equal to the current selection and then redefines it to refer to the current selection plus the next 10 characters.

Dim objSelection As Selection 
Set objSelection = ActiveWindow.Selection
objSelection.SetRange Start:=objRange.Start, _
                      End:=objRange.End + 10

Using the Selection Object

You should always check the Type of the Selection object to make sure that it is sensible.
It is possible for the user to select a vertical block of text that does not have to be represent contiguous text. This can be done by holding down the alt key and dragging with the mouse.

If (Selection.Type <> wdSelectionType.wdSelectionNormal) Then 
   Call MsgBox("This is not a valid selection")
End If

Default Property (Text)

The Text property is the default property for a Selection object.

ActiveWindow.Selection.Text 
ActiveWindow.Selection

Identifying a Selection Object

You can use the Type property to help return information about the current selection

ActiveWindow.Selection.Type = wdSelectionType.wdSelectionNormal 

You can use the Flags property to


You can use the Information property to


Selection.Paste

Selection.Paste 

Selection.TypeText

Inserts the text at the beginning of the current selection.
The selection is turned into an insertion point at the end of the inserted text.
If Options.ReplaceSelection = True then the original selection will be replaced.

Selection.TypeText "some text" 

This behaves exactly the same as typing some text at the keyboard.


Selection.TypeParagraph

Insert a paragraph mark at the beginning of the current selection.
The selection is turned into an insertion point after the inserted paragraph mark.
If Options.ReplaceSelection = True then the original selection will be replaced.

Selection.TypeParagraph 

This behaves exactly the same as pressing the Enter key.


Selection.TypeBackspace

Insert a paragraph mark at the beginning of the current selection.
If the selection is an insertion point, delete the character in front of the insertion point.
If something is currently selected then the selection is turned into an insertion point at the beginning of the current selection.
If Options.ReplaceSelection = True then the original selection will be replaced.

Selection.TypeBackspace 

Selection.PasteAndFormat

Selection.PasteAndFormat(wdRecoveryType.wdPasteDefault)
This method pastes the selected table cells and formats them as specified


Pastes the table cells and formats them as specified

Selection.PasteAndFormat(wdRecoveryType. 

It doesn't matter what the Zoom percentage is, the image is automatically resized to fit the width of the page
This line will paste an Excel chart as a picture

Selection.PasteAndFormat(wdRecovery.wdChartPicture) 

Selection.PasteExcelTable



Selection.PasteFormat


This example inserts the Clipboard contents at the insertion point as unformatted text.

Selection.Collapse Direction:=wdCollapseDirection.wdCollapseStart 

This example copies the first paragraph in the document and pastes it at the insertion point.

ActiveDocument.Paragraphs(1).Range.Copy 
Selection.Collapse Direction:=wdCollapseDirection.wdCollapseStart
Selection.Paste

This example copies the selection and pastes it at the end of the document.


If Selection.Type <> wdSelectionType.wdSelectionIP Then 
    Selection.Copy
    Set Range = ActiveDocument.Content
    Range.Collapse Direction:=wdCollapseDirection.wdCollapseEnd
    Range.Paste
End If



This example copies the selected text and pastes it into a new document as a hyperlink. The source document must first be saved for this example to work.

If Selection.Type = wdSelectionType.wdSelectionNormal Then 
    Selection.Copy
    Documents.Add.Content.PasteSpecial Link:=True, _
        DataType:=wdPasteDataType.wdPasteHyperlink
End If


Selection.Extend

Turns extend mode on (sets the ExtendMode property to True), or if extend mode is already on, extends the Selection object to the next larger unit of text.
The progression of selected units of text is as follows: word, sentence, paragraph, section, entire document.

objSelection.Extend(Character:="A") 

Character - The character through which the selection is extended. This argument is case sensitive and must evaluate to a String or an error occurs. Also, if the value of this argument is longer than a single character, the command is ignored.


This example collapses the current selection to an insertion point and then selects the current sentence.

With Selection 
' Collapse current selection to insertion point.
    .Collapse
' Turn extend mode on.
    .Extend
' Extend selection to word.
    .Extend
' Extend selection to sentence.
    .Extend
End With

Here is an example that accomplishes the same task without the Extend method.

With Selection 
' Collapse current selection.
    .Collapse
' Expand selection to current sentence.
    .Expand Unit:=wdUnits.wdSentence
End With

This example makes the end of the selection active and extends the selection through the next instance of a capital "R".

With Selection 
    .StartIsActive = False
    .Extend Character:="R"
End With

Selection - ExtendMode

This property is True when the Extend mode is active.
This property can only be set during run time; attempts to set it in Immediate mode are ignored. The Extend arguments of the EndOf and StartOf methods are not affected by this property.


This example moves to the beginning of the paragraph and selects the paragraph plus the next two sentences.

With Selection 
    .MoveLeft Unit:=wdUnits.wdCharacter, Count:=4, Extend:=True
    .MoveRight Unit:=wdUnits.wdSentence, Count:=2
    .ExtendMode = True
    .MoveUp Unit:=wdUnits.wdParagraph
    .MoveDown Unit:=wdUnits.wdParagraph
End With

This example collapses the current selection, turns on Extend mode, and selects the current sentence.

With Selection 
    .Collapse
    .ExtendMode = True
' Select current word.
    .Extend
' Select current sentence.
    .Extend
End With


Expanding the current Selection

The easiest way to expand a range is to use either the MoveRight or MoveLeft methods.
The Extend argument can either be wdMove or wdExtend. The default is wdMove.

Selection.MoveRight Unit:=wdUnits.wdCharacter, _ 
                    Count:=1, _
                    Extend:=wdMovementType.wdExtend

This method cannot be used with a Range.


You can also use the Expand method. This method returns the number of characters added to the range.

Selection.Expand (Unit:=wdUnits.wdWord) 

This example expands the selection to include the entire sentence.

Selection.Expand Unit:=wdUnits.wdSentence 


objSelection.MoveStart wdUnits.wdCharacter, 3 

If objSelection.Active = True Then 
'this selection is currently active, ie highlighted
End If

Selection Object - Collapsing

Even when a selection is collapsed to an insertion point it is not empty.
The Text property of a collapsed Selection object will still return the character immediately to the right of the insertion point.
This character will also appear in the Characters collection of the Selection object.



Selection.HomeKey

Moves the Selection object to the beginning of the specified unit.

lNoOfChars = objSelection.HomeKey(Unit:=wdUnits.wdStory, _ 
                                  Extend:=wdMovementType.wdMove)

Unit -
Extend - The default is wdMove.
This method returns a value (Long) that indicates the number of characters the selection has actually moved.
If it returns zero (0) then the moved was unsuccessful.


Selection.EndKey

Moves the Selection object to the end of the specified unit.

lNoOfChars = objSelection.EndKey(Unit:=wdUnits.wdStory, _ 
                                 Extend:=wdMovementType.wdMove)

Unit -
Extend - The default is wdMove.
This method returns a value (Long) that indicates the number of characters the selection has actually moved.
If it returns zero (0) then the moved was unsuccessful.


Selection.MoveUp

Moves the Selection object up and returns the number of units it has moved.
The current selection is collapsed to the end point before being moved up.
The wdWindow constant can also be used to move to the top of the current screen.
The wdScreen constant can also be used to move more than one screen.

lNoOfChars = objSelection.MoveUp(Unit:=wdUnits.wdParagraph, _ 
                                 Count:=1, _
                                 Extend:=wdMovementType.wdMove)

Unit - The unit can be either wdLine, wdParagraph, wdWindow, wdScreen. The default value is wdLine.
Count - The number of units to move. The default is 1.
Extend - The default is wdMove.


Selection.MoveDown

Moves the Selection object down and returns the number of units it has moved.
The current selection is collapsed to the end point before being moved up.
The wdWindow constant can also be used to move to the top of the current screen.
The wdScreen constant can also be used to move more than one screen.

lNoOfChars = objSelection.MoveDown(Unit:=wdUnits.wdParagraph, _ 
                                   Count:=1, _
                                   Extend:=wdMovementType.wdMove)

Unit - The unit can be either wdLine, wdParagraph, wdWindow, wdScreen. The default value is wdLine.
Count - The number of units to move. The default is 1.
Extend - The default is wdMove.


Selection.MoveLeft

Moves the Selection object to the left and returns the number of units it has moved.
The current Selection object is collapsed to the end point before being moved left.

lNoOfChars = objSelection.MoveLeft(Unit:=wdUnits.wdCharacters, _ 
                                   Count:=1, _
                                   Extend:=wdMovementType.wdMove)

Selection.MoveRight

Moves the Selection object to the right and returns the number of units it has moved.
The current Selection object is collapsed to the end point before being moved right.

lNoOfChars = objSelection.MoveRight(Unit:=wdUnits.wdCharacters, _ 
                                    Count:=1, _
                                    Extend:=wdMovementType.wdMove)

Selection.

The following methods also exist for a Selection:
Move, MoveStart, MoveEnd, MoveUntil, MoveWhile, MoveStartUntil, MoveEndUntil, MoveStartWhile, MoveEndWhile

Selection.Move 
Selection.MoveUntil
Selection.MoveWhile
Selection.MoveStart
Selection.MoveStartUntil
Selection.MoveStartWhile
Selection.MoveEnd
Selection.MoveEndUntil
Selection.MoveEndWhile


The following moves to the start of the current line.

objSelection.HomeKey(Unit:=wdUnits.wdLine, _ 
                     Extend:=wdMovementType.wdMove)

The following moves to the end of the line

objSelection.EndKey(Unit:=wdUnits.wdLine, _ 
                    Extend:=wdMovementType.wdMove)

This following moves the selection up three lines.

objSelection.MoveUp(Unit:=wdUnits.wdLine, _ 
                  Count:=3, _
                  Extend:=wdMovementType.wdMove)

Selection.Paragraphs(1).Range.Characters(1).Select 
Selection.Collapse wdCollapseStart

The following moves the selection down two paragraphs.

objSelection.MoveDown(Unit:=wdUnits.wdParagraph, _ 
                      Count:=2, _
                      Extend:=wdMovementType.wdMove)

The following moves to the end of the document.

objSelection.EndKey(Unit:=wdUnits.wdStory, _ 
                    Extend:=wdMovementType.wdMove)

The following example moves to the start of the document.

objSelection.HomeKey(Unit:=wdUnits.wdStory, _ 
                     Extend:=wdMovementType.wdMove)

The following moves the Selection object two words to the left.

objSelection.MoveLeft(Unit:=wdUnits.wdWords, _ 
                      Count:=2, _
                      Extend:=wdMovementType.wdMove)

The following moves the start position backwards until a capital "I" is found.
When the movement is backwards, the Range is expanded.

Selection.MoveStartUntil Cset:="I", _ 
                         Count:=wdConstants.wdBackward

The following moves the start position forwards until a "%" characters is found or for a maximum of ten 10.
When the movement is forwards, the Range is reduced.

Selection.MoveStartUntil Cset:="%", _ 
                         Count:=10

Backspace

Selection.TypeBackspace 
Selection.Delete Unit:=wdUnits.wdCharacter, Count:=1

selection.startof(wdline) 
selection.endof(wdline)

This example inserts the text "Solutions" (enclosed in quotation marks) before the selection and then collapses the selection.

With Selection 
    .InsertBefore Chr(34) & "Solutions" & Chr(34) & Chr(32)
    .Collapse Direction:=wdCollapseDirection.wdCollapseEnd
End With

This example inserts all the font names in the FontNames collection into a new document.

Documents.Add 
For Each aFont In FontNames
    With Selection
        .InsertBefore aFont
        .Collapse Direction:=wdCollapseDirection.wdCollapseEnd
        .TypeParagraph
    End With
Next aFont

This example inserts text at the end of the selection and then collapses the selection to an insertion point.

With Selection 
    .InsertAfter "appended text"
    .Collapse Direction:=wdCollapseDirection.wdCollapseEnd
End With

Deleting text

Selection.TypeBackspace 
Selection.Delete Unit:=wdUnits.wdCharacter, Count:=1

Removes all character formatting (formatting applied either through character styles or manually applied formatting) from the selected text.

Selection.ClearCharacterAllFormatting 


Removes character formatting (formatting that has been applied manually using the buttons on the Ribbon or through the dialog boxes) from the selected text.

Selection.ClearCharacterDirectFormatting 


Removes character formatting that has been applied through character styles from the selected text.

Selection.ClearCharacterStyle 


Removes text and paragraph formatting from a selection.

Selection.ClearFormatting 


Removes all paragraph formatting (formatting applied either through paragraph styles or manually applied formatting) from the selected text.

Selection.ClearParagraphAllFormatting 


Removes paragraph formatting that has been applied manually (using the buttons on the Ribbon or through the dialog boxes) from the selected text.

Selection.ClearParagraphDirectFormatting 


Removes paragraph formatting that has been applied through paragraph styles from the selected text.

Selection.ClearParagraphStyle 

Selection.Paragraph.Reset 

Selection.Paragraphs.Reset 

Selection.ParagraphFormat.Reset 

Selection.Font.Reset 



Selection Object - Properties

BookmarkIDReturns the number of the bookmark that encloses the beginning of the specified selection or range; returns 0 (zero) if there's no corresponding bookmark. (Long)
BookmarksReturns a Bookmarks collection that represents all the bookmarks in the range Read-only.
BordersReturns a Borders collection that represents all the borders for the specified object.
CaseReturns or sets a WdCharacterCase constant that represents the case of the text in the range.
CharactersReturns a Characters collection that represents the characters in the range.
CombinedCharactersReturns True or False indicating if the range contains combined characters.
CommentsReturns a Comments collection that represents all the comments in the range.
DocumentReturns a Document object associated with the specified pane, window, or selection.
DuplicateReturns a duplicate range object representing all the properties from this range.
EditorsReturns an Editors object that represents all the users authorized to modify this range.
EndReturns or sets the ending character position of the range. Read Only (Long)
EndnoteOptionsReturns an EndnoteOptions object that represents the endnotes in the range.
EndNotesReturns an Endnotes collection that represents all the endnotes in the range. Read-only.
ExtendMode 
FieldsReturns Fields collection that represents all the fields in the range. Read Only
FindReturns a Find object that contains the criteria for a find operation. Read-only
FitTextWidthReturns or sets the width (in the current measurement units) in which Microsoft Word fits the text in the current range. (Single).
Flags 
FontReturns or sets a Font object that represents the character formatting of the range.
FootnoteOptionsReturns FootnoteOptions object that represents the footnotes in the range.
FootnotesReturns a Footnotes collection that represents all the footnotes in the range. Read-only.
FormattedTextReturns or sets a Range object that includes the formatted text in the range.
FormFieldsReturns a FormFields collection that represents all the form fields in the range. Read-only.
FramesReturns a Frames collection that represents all the frames in the range. Read-only
GrammarCheckedReturns True or False indicating if a grammar check has been run on the range. False is returned if some of the specified range or document hasn't been checked for grammar.
GrammaticalErrorsReturns a ProofreadingErrors collection that represents the sentences that failed the grammar check on the range. There can be more than one error per sentence. Read-only.
HasChildShapeRange 
HeaderFooter 
HighlightColorIndexReturns or sets the highlight color for the range. (WdColorIndex).
HorizontalInVerticalReturns or sets the formatting for horizontal text set within vertical text. (wdHorizontalInVerticalType).
HTMLDivisionsReturns an HTMLDivisions object that represents an HTML division in a Web document.
HyperlinksReturns a Hyperlinks collection that represents all the hyperlinks in the range. Read-only.
IDCan be used to define hyperlinks in a document ??
InformationReturns information about the specified selection or range. Read-only Variant.
InlineShapesReturns an InlineShapes collection that represents all the InlineShape objects in the range. Read-only.
IsEndOfRowMarkReturns True or False indicating if the range is collapsed and is located at the end-of-row mark in a table. Read-only.
LanguageIDReturns or sets the language for the range.
ListFormatReturns a ListFormat object that represents all the list formatting characteristics of the range. Read-only.
ListParagraphsReturns a ListParagraphs collection that represents all the numbered paragraphs in the range. Read-only.
NextStroyRangeReturns a Range object that refers to the next story, as shown in the following table. Parameter is from wdStoryType
NoProofingTrue if the spelling and grammar checker ignores the specified text. Returns wdUndefined if the NoProofing property is set to True for only some of the specified text. (Long)
OrientationReturns or sets the orientation of text in a range when the Text Direction feature is enabled. WdTextOrientation.
PageSetupReturns a PageSetup object that's associated with the specified range. Read-only.
ParagraphFormatReturns or sets a ParagraphFormat object that represents the paragraph settings for the range
ParagraphsReturns a Paragraphs collection that represents all the paragraphs in the range. Read-only.
PreviousBookmarkIDReturns the number of the last bookmark that starts before or at the same place as the specified selection or range; returns 0 (zero) if there's no corresponding bookmark. Read-only Long.
Range 
ReadabilityStatisticsReturns a ReadabilityStatistics collection that represents the readability statistics for the range. Read-only.
RevisionsReturns a Revisions collection that represents the tracked changes in the range. Read-only.
ScriptsReturns a Scripts collection that represents the collection of HTML scripts in the specified object.
SectionsReturns a Sections collection that represents the sections in the range. Read-only.
SentencesReturns a Sentences collection that represents all the sentences in the range. Read-only.
ShadingReturns a Shading object that refers to the shading formatting for the specified object.
ShapeRangeReturns a ShapeRange collection that represents all the Shape objects in the specified range or selection. The shape range can contain drawings, shapes, pictures, OLE objects, ActiveX controls, text objects, and callouts. Read-only.
ShowAllTrue if all nonprinting characters (such as hidden text, tab marks, space marks, and paragraph marks) are displayed. Read/write Boolean.
SmartTagsReturns a SmartTags object that represents a smart tag in a document
SpellingCheckedTrue if spelling has been checked throughout the specified range or document. False if all or some of the range or document hasn't been checked for spelling. Boolean
SpellingErrorsReturns a ProofreadingErrors collection that represents the words identified as spelling errors in the specified document or range. Read-only.
StartReturns or sets the starting character position of a selection, range, or bookmark. Long.
StartIsActive 
StoryLengthReturns the number of characters in the story that contains the specified range or selection. Read-only (Long)
StoryTypeReturns the story type for the specified range, selection, or bookmark. Read-only WdStoryType.
StyleReturns or sets the style for the specified object. To set this property, specify the local name of the style, an integer, a WdBuiltinStyle constant, or an object that represents the style. For a list of valid constants, consult the Microsoft Visual Basic Object Browser. Read/write Variant.
SubdocumentsReturns a Subdocuments collection that represents all the subdocuments in the specified range or document. Read-only.
SynonymInfoReturns a SynonymInfo object that contains information from the thesaurus on synonyms, antonyms, or related words and expressions for the specified word or phrase
TextReturns or sets the text in the range. (String).
TextRetrievalModeReturns a TextRetrievalMode object that controls how text is retrieved from the specified Range. Read/write.
TwoLinesInOneReturns or sets whether Microsoft Word sets two lines of text in one and specifies the characters that enclose the text, if any. Read/write WdTwoLinesInOneType.
Type 
WordsReturns a Words collection that represents all the words in a range, selection, or document. Read-only. Note Punctuation and paragraph marks in a document are included in the Words collection.
XMLReturns a String that represents the XML text in the specified object.
XMLNodesReturns an XMLNodes collection that represents the collection of all XML elements within a document or in a selection or range - including those elements that are only partially within the selection or range.
XMLParentNodeReturns an XMLNode object that represents the parent node of a range.

Selection Object - Methods

BoldRunReturns True, False or wdUndefined (a mixture of True and False). Can be set to True, False, or wdToggle.
ItalicRunReturns True or False or wdUndefined indicating if the range is formatted in italic. (Long)
Move 
MoveDown 
MoveEnd 
MoveEndUntil 
MoveEndWhile 
MoveLeft 
MoveRight 
MoveStart 
MoveStartUntil 
MoveStartWhile 
MoveUntil 
MoveUp 
MoveWhile 
Next 
Previous 
UnderlineRunReturns or sets the type of underline applied to the font or range. Read/write WdUnderline

VBA - Range Object

A Range object represents a continuous area in a document.
Each range object is defined by a starting and ending character position.
Range objects are independent of the current selection so you can manipulate a range without changing the current selection.
The Range object is very important as it often provides access to many "properties" of an object.
In many cases, what you might expect to be a property of an object is in fact a property of the object's range object.
Although a Range object doesn't have a visual representation in a document you can, however, use the Select method to select it.
This can be useful when debugging to make sure that the Range object refers to the correct range.


Duplicating a Range

link - learn.microsoft.com/en-us/office/vba/word/concepts/customizing-word/assigning-ranges

Set Range2 = Range1.Duplicate 

Creating a Range Object

You can use the Range method of a document object to create a Range object representing that document.
Every Range object is defined by a starting and an ending character position.
The following example applies bold formatting to the first 10 characters in the active document.

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

There are several other ways to create a Range object, here are a few more:

Set objRange = ActiveDocument.Paragraphs(2).Range 
Set objRange = ActiveDocument.Paragraphs(2)
Set objRange = ActiveDocument.Sentences(2)
Set objRange = ActiveDocument.Words(2)
Set objRange = ActiveDocument.Characters(2)
Set objRange = ActiveDocument.Tables(1).Rows(1).Range
Set objRange = ActiveDocument.Bookmarks(1).Range
Set objRange = Cells
Set objRange = Rows
Set objRange = Document
Set objRange = Frame
Set objRange = HeadersFooters
Set objRange = Lists
Set objRange = Sections
Set objRange = Selections
Set objRange = ActiveDocument.Find.Execute

The GoTo Method returns the Range object that represents the starting position of the target of the GoTo method.

Set objRange = ActiveDocument.GoTo What:=wdGoToItem.wdGoToLine, _ 
                                   Which:=wdGoToDirection.wdGoToAbsolute, _
                                   Count:=2

Using a Range Object

You do not have to create an object representing the range it is also possible to refer to the range object directly.

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

Similar to a bookmark, a range can span a group of characters or mark a specific location in a document.
If you want a range to represent a specific location then the start and end character positions need to be the same.
The following example creates a range that represents the location at the start of the active document.

Set objRange = ActiveDocument.Range(Start:=0, End:=0) 

You can then use this range object to insert the text "hello" at the start of the document.

objRange.InsertBefore Text:="hello " 

The following example refers to the first three paragraphs in the active document.

Set objRange = ActiveDocument.Range(Start:=0, _ 
                                    End:=ActiveDocument.Paragraphs(3).Range.End)

Redefining a Range Object

You can use the SetRange method to redefine an existing Range object
The following example defines a range object to the be equal to the current selection and then redefines it to refer to the current selection plus the next 10 characters.

Dim objRange As Range 
Set objRange = ActiveWindow.Selection.Range
objRange.SetRange(Start:=objRange.Start, _
                  End:=objRange.End+10)

Default Property (Text)

The Text property is the default property for the Range object

ActiveDocument.Paragraphs(1).Range.Text 
ActiveDocument.Paragraphs(1).Range

Identifying a Range Object

The Start, End and the StoryType properties of a Range object can be used to uniquely identify it.
There are eleven different story types represented by the wdStoryType constants.



Range Object - Properties

BoldReturns True, False or wdUndefined (a mixture of True and False). Can be set to True, False, or wdToggle.
BookmarkIDReturns the number of the bookmark that encloses the beginning of the specified selection or range; returns 0 (zero) if there's no corresponding bookmark. (Long)
BookmarksReturns a Bookmarks collection that represents all the bookmarks in the range Read-only.
BordersReturns a Borders collection that represents all the borders for the specified object.
CaseReturns or sets a WdCharacterCase constant that represents the case of the text in the range.
CharactersReturns a Characters collection that represents the characters in the range.
CharacterWidthWdCharacterWidth. Returns or sets the character width of the range.
CombinedCharactersReturns True or False indicating if the range contains combined characters.
CommentsReturns a Comments collection that represents all the comments in the range.
DocumentReturns a Document object associated with the specified pane, window, or selection.
DuplicateReturns a duplicate range object representing all the properties from this range.
EditorsReturns an Editors object that represents all the users authorized to modify this range.
EmphasisMarkWdEmphasisMark - Returns or sets the emphasis mark for a character or designated character string.
EndReturns or sets the ending character position of the range. Read Only (Long)
EndnoteOptionsReturns an EndnoteOptions object that represents the endnotes in the range.
EndNotesReturns an Endnotes collection that represents all the endnotes in the range. Read-only.
FieldsReturns Fields collection that represents all the fields in the range. Read Only
FindReturns a Find object that contains the criteria for a find operation. Read-only
FitTextWidthReturns or sets the width (in the current measurement units) in which Microsoft Word fits the text in the current range. (Single).
FontReturns or sets a Font object that represents the character formatting of the range.
FootnoteOptionsReturns FootnoteOptions object that represents the footnotes in the range.
FootnotesReturns a Footnotes collection that represents all the footnotes in the range. Read-only.
FormattedTextReturns or sets a Range object that includes the formatted text in the range.
FormFieldsReturns a FormFields collection that represents all the form fields in the range. Read-only.
FramesReturns a Frames collection that represents all the frames in the range. Read-only
GrammarCheckedReturns True or False indicating if a grammar check has been run on the range. False is returned if some of the specified range or document hasn't been checked for grammar.
GrammaticalErrorsReturns a ProofreadingErrors collection that represents the sentences that failed the grammar check on the range. There can be more than one error per sentence. Read-only.
HighlightColorIndexReturns or sets the highlight color for the range. (WdColorIndex).
HorizontalInVerticalReturns or sets the formatting for horizontal text set within vertical text. (wdHorizontalInVerticalType).
HTMLDivisionsReturns an HTMLDivisions object that represents an HTML division in a Web document.
HyperlinksReturns a Hyperlinks collection that represents all the hyperlinks in the range. Read-only.
IDCan be used to define hyperlinks in a document ??
InformationReturns information about the specified selection or range. Read-only Variant.
InlineShapesReturns an InlineShapes collection that represents all the InlineShape objects in the range. Read-only.
IsEndOfRowMarkReturns True or False indicating if the range is collapsed and is located at the end-of-row mark in a table. Read-only.
ItalicReturns True or False or wdUndefined indicating if the range is formatted in italic. (Long)
LanguageIDReturns or sets the language for the range.
ListFormatReturns a ListFormat object that represents all the list formatting characteristics of the range. Read-only.
ListParagraphsReturns a ListParagraphs collection that represents all the numbered paragraphs in the range. Read-only.
NextStroyRangeReturns a Range object that refers to the next story, as shown in the following table. Parameter is from wdStoryType
NoProofingTrue if the spelling and grammar checker ignores the specified text. Returns wdUndefined if the NoProofing property is set to True for only some of the specified text. (Long)
OrientationReturns or sets the orientation of text in a range when the Text Direction feature is enabled. WdTextOrientation.
PageSetupReturns a PageSetup object that's associated with the specified range. Read-only.
ParagraphFormatReturns or sets a ParagraphFormat object that represents the paragraph settings for the range
ParagraphsReturns a Paragraphs collection that represents all the paragraphs in the range. Read-only.
PreviousBookmarkIDReturns the number of the last bookmark that starts before or at the same place as the specified selection or range; returns 0 (zero) if there's no corresponding bookmark. Read-only Long.
ReadabilityStatisticsReturns a ReadabilityStatistics collection that represents the readability statistics for the range. Read-only.
RevisionsReturns a Revisions collection that represents the tracked changes in the range. Read-only.
ScriptsReturns a Scripts collection that represents the collection of HTML scripts in the specified object.
SectionsReturns a Sections collection that represents the sections in the range. Read-only.
SentencesReturns a Sentences collection that represents all the sentences in the range. Read-only.
ShadingReturns a Shading object that refers to the shading formatting for the specified object.
ShapeRangeReturns a ShapeRange collection that represents all the Shape objects in the specified range or selection. The shape range can contain drawings, shapes, pictures, OLE objects, ActiveX controls, text objects, and callouts. Read-only.
ShowAllTrue if all nonprinting characters (such as hidden text, tab marks, space marks, and paragraph marks) are displayed. Read/write Boolean.
SmartTagsReturns a SmartTags object that represents a smart tag in a document
SpellingCheckedTrue if spelling has been checked throughout the specified range or document. False if all or some of the range or document hasn't been checked for spelling. Boolean
SpellingErrorsReturns a ProofreadingErrors collection that represents the words identified as spelling errors in the specified document or range. Read-only.
StartReturns or sets the starting character position of a selection, range, or bookmark. Long.
StoryLengthReturns the number of characters in the story that contains the specified range or selection. Read-only (Long)
StoryTypeReturns the story type for the specified range, selection, or bookmark. Read-only WdStoryType.
StyleReturns or sets the style for the specified object. To set this property, specify the local name of the style, an integer, a WdBuiltinStyle constant, or an object that represents the style. For a list of valid constants, consult the Microsoft Visual Basic Object Browser. Read/write Variant.
SubdocumentsReturns a Subdocuments collection that represents all the subdocuments in the specified range or document. Read-only.
SynonymInfoReturns a SynonymInfo object that contains information from the thesaurus on synonyms, antonyms, or related words and expressions for the specified word or phrase
TextReturns or sets the plain unformatted text in the range. (String).
TextRetrievalModeReturns a TextRetrievalMode object that controls how text is retrieved from the specified Range. Read/write.
TwoLinesInOneReturns or sets whether Microsoft Word sets two lines of text in one and specifies the characters that enclose the text, if any. Read/write WdTwoLinesInOneType.
UnderlineReturns or sets the type of underline applied to the font or range. Read/write WdUnderline
WordsReturns a Words collection that represents all the words in a range, selection, or document. Read-only. Note Punctuation and paragraph marks in a document are included in the Words collection.
XMLReturns a String that represents the XML text in the specified object.
XMLNodesReturns an XMLNodes collection that represents the collection of all XML elements within a document or in a selection or range - including those elements that are only partially within the selection or range.
XMLParentNodeReturns an XMLNode object that represents the parent node of a range.

Range Object - Methods


VBA - Inserting & Deleting


Range.InsertParagraph

Replaces a Range or Selection with a new paragraph.
After this method has been used, the range or selection is the new paragraph.

oRange.InsertParagraph 

If you don't want to replace the range or selection, use the Collapse method before using this method.
The InsertParagraphBefore method inserts a new paragraph before the range.

oRange.InsertParagraphBefore 

The InsertParagraphAfter method inserts a new paragraph after the range.

oRange.InsertParagraphAfter 

Range.InsertBefore

Inserts the specified text before the Range.
After the text is inserted, the range or selection is expanded to include the new text.

oRange.InsertBefore(Text:="hello world") 

If the selection or range is a bookmark, the bookmark is also expanded to include the next text.
You can insert characters such as quotation marks, tab characters, and nonbreaking hyphens by using the Visual Basic Chr function with the InsertBefore method.
You can also use the following Visual Basic constants: vbCr, vbLf, vbCrLf and vbTab.


Range.InsertAfter

Inserts the specified text after the Range
After the text is inserted, the range or selection expanded to include the new text.

oRange.InsertAfter(Text:="hello world") 

You can insert characters such as quotation marks, tab characters, and nonbreaking hyphens by using the Visual Basic Chr function with the InsertAfter method.
If you use this method with a range or selection that refers to an entire paragraph, the text is inserted after the ending paragraph mark (the text will appear at the beginning of the next paragraph).
To insert text at the end of a paragraph, determine the ending point and subtract 1 from this location (the paragraph mark is one character), as shown in the following example.


This example inserts text at the end of the active document. The Content property returns a Range object.

ActiveDocument.Content.InsertAfter "end of document" 


This example inserts text from an input box as the second paragraph in the active document.

response = InputBox("Type some text") 
With ActiveDocument.Paragraphs(1).Range
    .InsertAfter "1." & Chr(9) & response
    .InsertParagraphAfter
End With



Insert text at start of document

Set oRange = ActiveDocument.Paragraphs(2).Range 
oRange.Collapse Direction:=wdCollapseDirection.wdCollapseStart
oRange.Text = "start of document"

or

Set oRange = ActiveDocument.Range(Start:=0, End:=0) 
oRange.Text = "start of document"

or

Set oRange = ActiveDocument.Range 
oRange.StartOf Unit:=wdUnits.wdStory, _
                 Extend:=wdMovementType.wdMove
oRange.Text = "start of document"


Insert text to the end of a document

To insert text at the end of a document, you can collapse the range to the end using wdCollapseEnd

Set oRange = ActiveDocument.Paragraphs(2).Range 
oRange.Collapse Direction:=wdCollapseDirection.wdCollapseEnd
oRange.Text = "end of document"

or

Set oRange = ActiveDocument.Range 
oRange.EndOf Unit:=wdUnits.wdStory, _
               Extend:=wdMovementType.wdMove
oRange.Text = "end of document"

To refer to the insertion point immediately after the tenth character, set the character position to 10.

Set oRange = ActiveDocument.Range(10,0) 
Set oRange = ActiveDocument.Range(9,9) ??

The end paragraph mark is actually counted as a character when you use:

ActiveDocument.Characters.Count 

In general

iTotalChars = ActiveDocument.Characters.Count 
Set objRange = ActiveDocument.Range(iTotalChars - 1, iTotalChars - 1)


To insert text into a document without replacing existing text use a Range or Selection object that represents a single location (i.e. whose start and end points are equal).
This is easily obtained from an existing range, using the Collapse method

oRange.Collapse Direction:=wdCollapseDirection.wdCollapseStart 
oSelection.Collapse Direction:=wdCollapseDirection.wdCollapseEnd


Deleting Text

This will remove the contents but preserve the range object.

oRange.Delete 


VBA - Selecting Text

Using Range


Selecting the Current Line

Using Range


Selecting the Current Paragraph

Using Range


VBA - Pasting


Copying

Range.Copy 

Range.Paste

This is the same as Selection.Paste
Pastes the contents of the clipboard at the current position. This replaces the current selection
Inserts the contents of the Clipboard at the specified range or selection. If you don't want to replace the contents of the range or selection, use the Collapse method before using this method.
When this method is used with a range object, the range expands to include the contents of the Clipboard.
When this method is used with a selection object, the selection doesn't expand to include the Clipboard contents; instead, the selection is positioned after the pasted Clipboard contents.


This example copies and pastes the first table in the active document into a new document.

If ActiveDocument.Tables.Count >= 1 Then 
    ActiveDocument.Tables(1).Range.Copy
    Documents.Add.Content.Paste
End If

Range.PasteSpecial

This is the same as Selection.PasteSpecial
Inserts the contents of the Clipboard allowing you to control the format of the pasted information and (optionally) establish a link to the source file (for example, a Microsoft Excel worksheet).
Note If you don't want to replace the contents of the specified range or selection, use the Collapse method before you use this method. When you use this method, the range or selection doesn't expand to include the contents of the Clipboard.


oRange.PasteSpecial(IconIndex:= , _ 
                    Link:=False, _
                    Placement:=wdOLEPlacement.wdInLine , _
                    DisplayAsIcon:=False, _
                    DataType:=wdPasteDataType.wdPasteText , _
                    IconFileName:= , _
                    IconLabel )

IconIndex - (Variant) If DisplayAsIcon is True, this argument is a number that corresponds to the icon you want to use in the program file specified by IconFilename. Icons appear in the Change Icon dialog box (Insert menu, Object command, Create New tab): 0 (zero) corresponds to the first icon, 1 corresponds to the second icon, and so on. If this argument is omitted, the first (default) icon is used.
Link - (Variant) True to create a link to the source file of the Clipboard contents. The default value is False.
DisplayAsIcon - (Variant) True to display the link as an icon. The default value is False.
IconFileName - (Variant) If DisplayAsIcon is True, this argument is the path and file name for the file in which the icon to be displayed is stored.
IconLabel - (Variant) If DisplayAsIcon is True, this argument is the text that appears below the icon.


oRange.PasteSpecial DataType:=wdPasteDataType.wdPasteText 

Range.Expand

Expands the Range or Selection object by a particular unit.

oRange.Expand(Unit:=wdUnits.wdCharacter) 

Unit - The default is wdWord. The unit can only be one of the following constants:

oRange.Expand(Unit:=wdUnits.wdCell) 
oRange.Expand(Unit:=wdUnits.wdCharacter)
oRange.Expand(Unit:=wdUnits.wdColumn)
oRange.Expand(Unit:=wdUnits.wdParagraph)
oRange.Expand(Unit:=wdUnits.wdRow)
oRange.Expand(Unit:=wdUnits.wdSentence)
oRange.Expand(Unit:=wdUnits.wdSection)
oRange.Expand(Unit:=wdUnits.wdStory)
oRange.Expand(Unit:=wdUnits.wdTable)
oRange.Expand(Unit:=wdUnits.wdWord)

Using any other unit will generate a Bad Paramater error.
You can only use wdLine when using a Selection object.


This method returns a value (Long) that indicates the number of characters added to the Range.

oRange.Expand(Unit:=wdUnits.wdCharacter) 

The following expands the Range object to include another sentence

oRange.Expand(Unit:=wdUnits.wdSentence) 


You can also define the start and end points of a range by using the Start and End properties of a range.
The following example creates a Range object that refers to the third and fourth sentences in the active document.

Set myDoc = ActiveDocument 
Set myRange = myDoc.Range(Start:=myDoc.Sentences(3).Start, _
                          End:=myDoc.Sentences(4).End)


Dim oRange As Range 
Set oRange = ActiveDocument.Range
oRange.Collapse wdCollapseDirection.wdCollapseStart
oRange.End = 0
oRange.StartOf wdUnits.wdStory, _
                 wdMovementType.wdMove

Set oRange = ActiveDocument.Range(0,0)

Expanding a range to include the whole document

oRange.WholeStory 
oRange.Expand wdUnits.wdStory


There a several ways you can change a given Range object

Range.SetRange

This redefines the starting and end position of existing selection or range
All characters are counted including non printable characters and hidden characters.

oRange.SetRange Start:=0 
                  End:=0

This line of code will set the insertion point to the beginning of the active document

ActiveWindow.Selection.SetRange(0,0) 


Range.StartOf

Its is also possible to refines the starting and end position of a range by a specific number of units

oRange.StartOf Unit:=wdUnits.wdLine, _ 
                 Extend:=wdMovementType.wdMove

Extend has the default of wdMove
When wdMove is used both the ends of the range are moved to the beginning , ie the range is collapsed to a point.
Note: The beginning of the range is not moved if the range is already at the beginning of the specified unit.

oRange.StartOf Unit:=wdUnits.wdWord, _ 
                 Extend:=wdMovementType.wdMove

Range.EndOf


oRange.EndOf Unit:=wdUnits.wdLine, _ 
               Extend:=wdMovementType.wdExtend

When wdMove is used both ends of the range are moved to the end, ie the range is collapsed to a point.



HomeKey



EndKey

Returns a range representing the resulting insertion point



Extends to the next complete unit

Dim oRange As Range 
Set oRange = Application.Selection.Range
oRange.Expand Unit:=wdUnits.wdCharacter

VBA - Range Object Collapsing


Range.Collapse

Collapses a Range object to the start or end position.
After a range or selection is collapsed, the starting and ending points are equal.

oRange.Collapse Direction:=wdCollapseDirection.wdCollapseStart 

Direction - The default value is wdCollapseStart.


If you use wdCollapseEnd to collapse a range that refers to an entire paragraph, the range is located after the ending paragraph mark (the beginning of the next paragraph).
The following moves the Range back one character (using MoveEnd) once the Range is collapsed).

Set oRange = ActiveDocument.Paragraphs(1).Range 
oRange.Collapse Direction:=wdCollapseDirection.wdCollapseEnd
oRange.MoveEnd Unit:=wdUnits.wdCharacter, _
                 Count:=-1

The following sets a Range object to the first paragraph and then moves the range forward three paragraphs.
After this macro is run, the insertion point is positioned at the beginning of the fourth paragraph.

Set oRange = ActiveDocument.Paragraphs(1).Range 
oRange.Collapse Direction:=wdCollapseDirection.wdCollapseStart
oRange.Move Unit:=wdUnits.wdParagraph, _
              Count:=3
oRange.Select


Range.StartOf

Moves the Range object to the beginning of the specified unit.

lNoOfChars = oRange.StartOf(Unit:=wdUnits.wdStory, _ 
                              Extend:=wdMovementType.wdMove)

Unit - The default is wdWord. The unit can only be one of the following constants:

oRange.StartOf(Unit:=wdUnits.wdCell) 
oRange.StartOf(Unit:=wdUnits.wdCharacter)
oRange.StartOf(Unit:=wdUnits.wdColumn)
oRange.StartOf(Unit:=wdUnits.wdParagraph)
oRange.StartOf(Unit:=wdUnits.wdRow)
oRange.StartOf(Unit:=wdUnits.wdSentence)
oRange.StartOf(Unit:=wdUnits.wdSection)
oRange.StartOf(Unit:=wdUnits.wdStory)
oRange.StartOf(Unit:=wdUnits.wdTable)
oRange.StartOf(Unit:=wdUnits.wdWord)

Using any other unit will generate a Bad Paramater error.
You can only use wdLine when using a Selection object.
Extend - The default value is wdMove.


This method returns a negative value if the movement is backward in the document,
If the start of the selection is already at the beginning of the specified unit, then the selection does not move.
The following makes sure that the selection is at the beginning of the line.

oRange.StartOf(Unit:=wdUnits.wdLine, _ 
                 Extend:=wdMovementType.wdMove)

Range.EndOf

Moves the Range object to the end of the specified unit.

lNoOfChars = oRange.EndOf(Unit:=wdUnits.wdStory, _ 
                            Extend:=wdMovementType.wdMove)

Unit - The default is wdWord. The unit can only be one of the above constants.
You can only use wdLine when using a Selection object.
Extend - The default value is wdMove.
If the end of the selection is already at the end of the specified unit, then the selection does not move.


The following makes sure that the selection is at the end of the line.
Both ends of the range or selection object are moved to the end of the specified unit.

oRange.EndOf(Unit:=wdUnits.wdLine, _ 
               Extend:=wdMovementType.wdMove)

Range.Shrink

Shrinks the range to the next smallest complete unit of text, in the following order (word, sentence, paragraph, section, entire document)

oRange.Shrink 

Important

Calling methods like Cut and Copy from a collapsed Selection object will generate an error.


VBA - Moving


Range.Move (collapse before)

Range objects include non printing characters such as spaces, tab characters and paragraph marks !!
Collapses the Range or Selection object to its start or end position (referring to an insertion point) and then moves the Range the specified number of units.
This method returns a value (Long) that indicates the number of units by which the start position has actually moved.
If it returns zero (0) then the move was unsuccessful.

lNoOfChars = oRange.Move(Unit:=wdUnits.wdParagraph, _ 
                           Count:=1)

Unit - The unit can only be one of the wdUnits enumerations. The default is wdCharacter.
You can only use wdLine when using a Selection object.
Count - The number of units to move. The default value is 1.
If Count is positive, the Range object is collapsed to its end position and moved forward.
If Count is negative, the Range object is collapsed to its start position and moved backward.


oRange.Move(Unit:=wdUnits.wdCell) 
oRange.Move(Unit:=wdUnits.wdCharacter)
oRange.Move(Unit:=wdUnits.wdColumn)
oRange.Move(Unit:=wdUnits.wdParagraph)
oRange.Move(Unit:=wdUnits.wdRow)
oRange.Move(Unit:=wdUnits.wdSentence)
oRange.Move(Unit:=wdUnits.wdSection)
oRange.Move(Unit:=wdUnits.wdStory)
oRange.Move(Unit:=wdUnits.wdTable)
oRange.Move(Unit:=wdUnits.wdWord)

Using any other unit will generate a Bad Paramater error.
You can also control the collapse direction by using the Collapse method before using the Move method.
If the range is in the middle of a unit or isn't collapsed, moving it to the beginning or end of the unit counts as moving it one full unit.


Range.MoveStart

Moves the start position of the Range or Selection object a specified number of units.
This method returns a value (Long) that indicates the number of units by which the start position has actually moved.
If it returns zero (0) then the move was unsuccessful.

lNoOfChars = oRange.MoveStart(Unit:=wdUnits.wdCharacter, _ 
                                Count:=1)

Unit - The unit can only be one of the wdUnits enumerations. The default is wdCharacter.
You can only use wdLine when using a Selection object.
Count - The number of characters to move. The default is 1.


Range.MoveEnd

Moves the end position of the Range or Selection object a specified number of units.
This method returns the number of units by which the start position has moved.
If it returns zero (0) then the move was unsuccessful.

lNoOfChars = oRange.MoveEnd(Unit:=wdUnits.wdCharacter, _ 
                              Count:=1)

Unit - The unit can only be one of the wdUnits enumerations. The default is wdCharacter.
You can only use wdLine when using a Selection object.
Count - The number of units to move. The default is 1.


Range.MoveUntil (collapse before)

Collapses the Range or Selection object to an insertion point and moves it infront of the first specified character.
This method returns a value (Long) that indicates the number of units by which the Range has actually moved.

lNoOfChars = oRange.MoveUntil(Cset:=  , _ 
                                Count:=1

Cset - One or more characters. This argument is case sensitive.
Count - The maximum number of characters to move. Can also be the wdForward or wdBackward constant. The default value is wdForward.
If Count is positive, the Range is moved forward (starting at the end position).
If Count is negative, the Range is moved backward (starting at the start position).
If Count is greater than 0 (zero), this method returns the number of characters moved plus 1.
If Count is less than 0 (zero), this method returns the number of characters moved minus 1.
If none of the characters are found the method returns zero (0) and the Range is not changed.


Range.MoveWhile (collapse before)

Collapses the Range or Selection object to an insertion point and moves it infront of the characters while any of the specified characters are found.
This method returns a value (Long) that indicates the number of units by which the Range has actually moved.

lNoOfChars = oRange.MoveWhile(Cset:=  , _ 
                                Count:=1

Cset - One or more characters. This argument is case sensitive.
Count - The maximum number of characters to move. Can also be the wdForward or wdBackward constant. The default value is wdForward.
If Count is a positive, the Range is moved forward (starting at the end position).
If Count is negative, the Range is moved backward (starting at the start position).
If Count is greater than 0 (zero), this method returns the number of characters moved plus 1.
If Count is less than 0 (zero), this method returns the number of characters moved minus 1.
If none of the characters are found the method returns zero (0) and the Range is not changed.


Range.MoveStartUntil

Moves the start position of the Range or Selection object until one of the specified characters is found.
This method returns the number (Long) of characters that the start position has moved.

lNoOfChars = oRange.MoveStartUntil(Cset:=  , _ 
                                     Count:=1

Cset - One or more characters. This argument is case sensitive.
Count - The maximum number of characters to move. Can also be the wdForward or wdBackward constant. If Count is a positive, the Range is moved forward. If Count is negative, the Range is moved backward. The default value is wdForward.
If Count is greater than 0 (zero), this method returns the number of characters moved plus 1.
If Count is less than 0 (zero), this method returns the number of characters moved minus 1.
If none of the characters are found the method returns zero (0) and the Range is not changed.
If the start position is moved forward to a point beyond the end position, the Range is collapsed and both the start and end positions are moved together.


Range.MoveEndUntil

Moves the end position of the Range or Selection object until one of the specified characters is found.
This method returns the number (Long) of characters that the end position has moved.

lNoOfChars = oRange.MoveEndUntil(Cset:=  , _ 
                                   Count:=1

Cset - One or more characters. This argument is case sensitive.
Count - The maximum number of characters to move. Can also be the wdForward or wdBackward constant.
If Count is a positive, the Range is moved forward. If Count is negative, the Range is moved backward. The default value is wdForward.
If the movement is forwards then then the Range is expanded.


Range.MoveStartWhile

Moves the start position of the Range or Selection object while any of the specified characters are found.
This method returns the number (Long) of characters that the start position has moved.

oRange.MoveStartWhile(Cset:=  , _ 
                        Count:=1)

Cset - One or more characters. This argument is case sensitive.
Count - The maximum number of characters to move. Can also be the wdForward or wdBackward constant.
If Count is a positive, the Range is moved forward. If Count is negative, the Range is moved backward. The default value is wdForward.
If none of the characters are found then the Range does not change.


Range.MoveEndWhile

Moves the end position of the Range or Selection object while any of the specified characters are found.
This method returns the number (Long) of characters that the end position has moved.

oRange.MoveEndWhile(Cset:=  , _ 
                      Count:=1)

Cset - One or more characters. This argument is case sensitive.
Count - The maximum number of characters to move. Can also be the wdForward or wdBackward constant.
If Count is a positive, the Range is moved forward. If Count is negative, the Range is moved backward. The default value is wdForward.


Line, Start - Move the cursor to the start of the line

The following moves the start position of the Range to the start of the line.

objRange.MoveStart Unit:=wdUnits.wdLine, _ 
                   Count:=-1


Line, End - Move the cursor to the end of the line

The following moves the end of the Range to the end of the line.

oRange.MoveEnd Unit:=wdUnits.wdLine, _ 
                 Count:=1

Line, Up - Move the cursor up 3 lines



Paragraph, Start - Move the cursor to the start of a paragraph



Paragraph, End - Move the cursor to the end of a paragraph

The following collapses the Range and moves it to the end of the active paragraph.

oRange = ActiveDocument.Selection.Range 
lNoOfChars = oRange.MoveUntil(Cset:=Chr$(13), _
                                Count:=wdConstants.wdForward)

Paragraph, Down - Move the cursor down 2 paragraphs




Document, Start - Move the cursor to the start of the document



Document, End - Move the cursor to the end of the document




Characters, 1 Backward - Move the end position of the range 1 character backward

The following moves the end of the Range one character backward, the range is reduced by one character.

oRange.MoveEnd Unit:=wdUnits.wdCharacter, _ 
                 Count:=-1


Characters, 1 Forward - Move the start position of the range 1 character forward

The following moves the start position of the Range one character forward (the selection size is reduced by one character).

oRange.MoveStart Unit:=wdUnits.wdCharacter, _ 
                   Count:=1


Words,2 Left - Move the selection 2 words to the left

The following collapses the Range and moves it forward through the next 100 characters in the document until the character "t" is found.

Set oRange = ActiveDocument.Words(1) 
oRange.MoveUntil Cset:="t", _
                   Count:=100


The following collapses the Range and moves it over any consecutive tabs.

oRange.MoveWhile Cset:=wdUnits.vbTab, _ 
                   Count:=wdConstants.wdForward

The following collapses the Range and moves it past any of the following characters "a", "t" or "h" (uppercase or lowercase)

Set oRange = ActiveDocument.Characters(1) 
oRange.MoveWhile Cset:="atiATI", _
                   Count:=wdConstants.wdForward

VBA - Formatting


Obtains a collection of all the font names that are currently available

Dim oFontName As FontNames 
oFontNames = Application.FontNames
oFontNames = Application.PortraitFontNames
oFontNames = Application.LandscapeFontNames

Note the loop variable must be either an object variable or a variable of type Variant
It cannot be a string variable, as would otherwise be appropriate here.

Dim oFontName As Variant 
For Each oFontName In Application.FontNames
   Selection.InsertAfter objFontName.Name & vbCrLf
Next oFontName

Dim oFont as Font 
Set oFont = ActiveWindow.Selection.Font

Difference between Text and FormattedText

objRange.Text = the objects unformatted text

sText = oRange.Text 

objRange.FormattedText - returns a range object that represents the text and the formatting

oRange = obAnotherRange.FormattedText 

The FormattedText property has a special use and that is to transfer text and formatting from one range to another


Dim oRange As Range 
oRange = ActiveDocument.Words(2)

Clear Formatting


wdUndefined and wdToggle

This value cannot be set as a value but might be returned when a Range contains several different types of formatting.
Lets imagine that the first paragraph in a document contains both bold and not bold text.
This code will change all the text to bold when there is a mixture of bold and not bold and toggle the bold when it either all bold or all not bold.

Dim oFont as Font 
Set oFont = ActiveDocument.Paragraphs(1).Range.Font
If (oFont.Bold = wdConstants.wdUndefined) Then
   oFont.Bold = True
Else
   oFont.Bold = wdConstants.wdToggle
End If

Dim oFont As Font 
Set oFont = New Font
oFont.Name = "Arial"
oFont.Bold = -1 (True) / 0 (False)
oFont.Italic = True / False
oFont.Size = 12
oFont.Color = wdConstants.wdColorDarkYellow
oFont.TextColor.RGB = RGB(50,50,50)
oFont.Underline = wdUnderline.wdUnderlineSingle
oFont.UnderlineColor = wdColor.wdColorAutomatic

Effects

Dim oFont As Font 
Set oFont = New Font
      With oFont
         .StrikeThrough = True | False | wdConstants.wdToggle
         .DoubleStrikeThrough = True | False
'Setting the Superscript property to True automatically sets the Subscript property to False, and vice versa.
         .Superscript = True | False
         .Subscript = True | False
         .Shadow = True | False
         .Outline = True | False
         .Emboss = True | False
         .Engrave = True | False
         .SmallCaps = True
         .AllCaps = True | False
         .Hidden = True | False
      End With

oFont.Spacing = 0
oFont.Scaling = 100
oFont.Position = 0
oFont.Kerning = 0
oFont.Animation = wdAnimation.wdAnimationNone

VBA - Words Collection

The Words collection is read-only and represents all the words in the specified document, range or selection.


This is the Words collection for the current selection

ActiveWindow.Selection.Words 

This is the first word in the current selection

ActiveWindow.Selection.Words(1) 

Each item in the Words collection is a Range object. There is no Word object.
Every item in the words collection includes the word and the space after the word.


You can remove the space by using the RTrim() function.


Words(index) - where index is the position of the word in the collection.


If the Selection is the insertion point and it is immediately followed by a space then this line refers to the word BEFORE the selection.

ActiveWindow.Selection.Words(1) 

If the Selection is the insertion point and it is immediately followed by a character then this line refers to the word AFTER the selection.

ActiveWindow.Selection.Words(1) 


Count Property

The count property returns the total number of words and also includes punctuation and paragraph marks.

ActiveWindow.Selection.Words.Count 

Counting Words Only

If you want to obtain just the total number of words in a range or selection you can use the Word Count dialog box.

Set dlgWordCount = Dialogs(wdWordDialog.wdDialogToolsWordCount) 
dlgWordCount.Execute
iTotalWords = dlgWordCount.Words


Sentences Collection


VBA - Characters Collection

The Characters collection is Read-Only and represents all the characters in a specified range or selection.
Each item in the characters collection is a Range object. There is no Character object.


Characters(index) - where index is the index number
This obtains the first character in the current selection and assigns it to a Range object.

Dim objRange As Range 
objRange = ActiveWindow.Selection.Characters.Item(1)
sChar = objRange.Text

It is also possible to refer to the Range properties and methods directly.

sChar = ActiveWindow.Selection.Characters.Item(1).Text 


Count Property (Read Only)

The Count property returns the total number of characters (as a Long).

Dim lTotal As Long 
lTotal = ActiveWindow.Selection.Characters.Count

This displays the total number of characters in the first sentence of the active document

lTotal = ActiveDocument.Sentences(1).Characters.Count 

VBA - Fonts


Display a list of all Fonts currently installed

Public Sub CreateTable 
Dim objDocument As Document
Dim sSampleText As String
Dim sFontName As String
Dim objRange As Range
Dim objStartRange As Range
Dim lcount As Long

   Set objDocument = Documents.Add
   sSampleText = Chr(147) & _
       "ABCDEFGHIJKLMNOPQRSTUVWYZ" & Chr(148) & ", " & Chr(147) & _
       "abcdefghijklmnopqrstuvwxyz" & Chr(148) & ", " & Chr(147) & _
       "The quick brown fox jumps over the lazy dog" & Chr(148) & ", " & Chr(147) & _
       "(;,.:£$?!)" & Chr(146)

   System.Cursor = wdCursorType.wdCursorWait
   With objDocument
      For lcount = 1 To Application.FontNames.Count
         sFontName = Application.FontNames(lcount)
         StatusBar = "Adding " & sFontName
         Set objRange = .Range
         With objRange
            .Collapse wdCollapseDirection.wdCollapseEnd
            .Font.Reset
            .InsertAfter sFontName & " - " & SampleText
         End With
         Set objRange = .Range
         With objRange
            .Collapse wdCollapseDirection.wdCollapseEnd
            .InsertAfter sSampleText
            Set objStartRange = .Duplicate
            objStartRange.End = .End
            objStartRange.Font.Name = sFontName
            .InsertAfter vbCrLf
         End With
      Next lcount

      .Range.Sort FieldNumber:="Paragraphs"
      .Paragraphs(1).Range.Text = "Font" & vbTab & "Sample" & vbCr
      .Range.ConvertToTable Format:=wdTableFormat.wdTableFormatClassic1, _
                            AutoFit:=True

      With .Tables(1)
         .Rows.AllowBreakAcrossPages = False
         .Rows(1).HeadingFormat = True
      End With

   End With

   System.Cursor = wdCursorType.wdCursorNormal
End Sub


© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrev