Handling Selection objects and Range objects--word two important objects in VBA

Source: Internet
Author: User

Handling Selection objects and Range objects--word two important objects in VBA


Word Developer Reference
Selection Object
Represents the current selection in a window or a pane. The selection represents the area selected (or highlighted) in the document and represents the insertion point if no content is selected in the document. Each document pane can have only one Selection object, and there can be only one active Selection object in the entire application.
Description


You can use the Selection property to return the Selection object. If the Selection property does not use an object qualifier, Microsoft Office Word Returns the selection in the active pane of the Active document window. The following example copies the current selection from the active document.

Selection.Copy

The following example deletes the selection for the third document in the Documents collection. When you access the current selection of the document, the document does not need to be active.

Documents (3). ActiveWindow.Selection.Cut

The following example copies the selection in the first pane of the active document and pastes it into the second pane.

ActiveDocument.ActiveWindow.Panes (1). Selection.Copy
ActiveDocument.ActiveWindow.Panes (2). Selection.paste

The Text property is the default property of the Selection object. Use this property to set or return text in the current selection. The following example assigns the text in the current selection to the variable strtemp. If the last character is a paragraph mark, the character is deleted.

Dim strtemp as String

strtemp = Selection.Text
If Right (strtemp, 1) = vbcr Then _
strtemp = Left (strtemp, Len (strtemp)-1)

The Selection object has several methods and properties that you can use to collapse, extend, or otherwise change the current selection. The following example moves the insertion point to the end of the document and selects the last three rows.

Selection.endof Unit:=wdstory, Extend:=wdmove
Selection.homekey Unit:=wdline, Extend:=wdextend
Selection.moveup Unit:=wdline, count:=2, Extend:=wdextend

The Selection object has several methods and properties that you can use to edit the selected text in the document. The following example selects the first sentence in the active document and replaces the sentence with a new paragraph.

Options.replaceselection = True
Activedocument.sentences (1). Select
Selection.TypeText "Material below is confidential."
Selection.typeparagraph

The following example deletes the last paragraph of the first document in the Documents collection and pastes it at the beginning of the second document.

With Documents (1)
. Paragraphs.Last.Range.Select
. ActiveWindow.Selection.Cut
End with

With Documents (2). Activewindow.selection
. StartOf Unit:=wdstory, Extend:=wdmove
. Paste
End with

The Selection object has several methods and properties that you can use to change the formatting of the current selection. The following example changes the font of the current selection from times New Roman to Tahoma.

If Selection.Font.Name = "Times New Roman" Then _
Selection.Font.Name = "Tahoma"

You can use properties such as Flags, information, and Type to return information about the current selection. You can use the following example in a procedure to determine whether the content is selected in the active document, or skip the remainder of the procedure if it is not selected.

If Selection.type = Wdselectionip Then
MsgBox prompt:= "You had not selected any text! Exiting procedure ... "
Exit Sub
End If

Even if you collapse the selection to the insertion point, the content is not necessarily empty. For example, the Text property still returns characters to the right of the insertion point, and this character also appears in the characters collection of the Selection object. However, methods such as Cut or Copy that are called from the collapsed selection will cause an error.

Users can select areas in the document that do not represent contiguous text (for example, when using the ALT key and the mouse). Because the behavior of this selection is unpredictable, you might want to include a step in your code that checks the Type property of the selection before performing any action on it (Selection.type = Wdselectionblock). Similarly, the selection that contains a table cell also causes unpredictable behavior. The Information property indicates whether the selection is in a table (Selection.Information (wdwithintable) = True). The following example determines whether the selection is normal (for example, it is not a row or column in a table, is not a vertical block of text, and so on), and you can use the example to test the current selection before you perform any action on it.

If Selection.type <> Wdselectionnormal Then
MsgBox prompt:= "not a valid selection! Exiting procedure ... "
Exit Sub
End If

Because the Range object is the same as many of the methods and properties of the Selection object, it is a good idea to use a Range object to work with the document if it is not necessary to make actual changes to the current selection. For more information about Selection objects and Range objects, see Working with Selection objects and working with Range objects.


? 2006 Microsoft Corporation. All rights reserved.

=================================================================================
Word Developer Reference
Working with Selection objects

When you work with a document in Microsoft Office Word, you typically select the text first, and then perform actions on the selection, such as formatting text or typing text. In Microsoft Visual Basic, you typically do not need to select text before you modify it, but instead create a Range object that references a specific area in the document. For information about defining a Range object, see Working with a Range object. However, if you want the code to respond or change the selection, you can use the Selection object.

If the text is not already selected, use the Select method to select the text associated with the particular object and create a Selection object. For example, the following instruction selects the first word in the active document.

Sub Selectfirstword ()
Activedocument.words (1). Select
End Sub

For more information, see Select Text in a document.

If you have selected text, you can use the Selection property to return a Selection object that represents the currently selected content in the document. There can be only one Selection object per document, and the object always accesses the current selection. The following example changes the formatting of a paragraph in the current selection.

Sub formatselection ()
Selection.Paragraphs.LeftIndent = InchesToPoints (0.5)
End Sub

This example inserts the word "Hello" after the current selection.

Sub inserttextafterselection ()
Selection.InsertAfter text:= "Hello"
End Sub

This example applies bold formatting to the selected text.

Sub Boldselectedtext ()
Selection.Font.Bold = True
End Sub

Macro Recorder often creates macros that use Selection objects. The following example is created using the macro recorder. The macro selects the first two words in the active document and applies bold formatting to them.

Sub Macro ()
Selection.homekey unit:=wdstory
Selection.MoveRight Unit:=wdword, count:=2, Extend:=wdextend
Selection.Font.Bold = Wdtoggle
End Sub

The following example accomplishes the same task, but does not select text or use the Selection object.

Sub Workingwithranges ()
ActiveDocument.Range (Start:=0, _
End:=activedocument.words (2). END). Bold = True
End Sub

? 2006 Microsoft Corporation. All rights reserved.

=================================================================================

Word Developer Reference
Range Object
Represents a contiguous region in a document. Each Range object is defined by a starting character position and a terminating character position.
Description


Similar to how bookmarks are used in documents, a Range object is used in a Visual Basic procedure to identify specific parts of a document. However, unlike bookmarks, a Range object exists only when the process that defines the object runs. The Range object is independent of the selection. That is, you can define and manipulate a range without changing the selection. You can also define multiple scopes in a document, but only one selection in each pane.

Use the Range method to return a Range object that is defined by the specified start and end character positions. The following example returns a Range object that represents the first 10 characters in the active document.

Set MyRange = ActiveDocument.Range (start:=0, end:=10)

Use the Range property to return a Range object that is defined by the start and end point of another object. The Range property can be applied to many objects (for example, Paragraph, Bookmark, and Cell). The following example returns a Range object that represents the first paragraph in the active document.

Set arange = activedocument.paragraphs (1). Range

The following example returns a Range object that represents the second to fourth paragraphs in the active document.

Set Arange = ActiveDocument.Range (_
Start:=activedocument.paragraphs (2). Range.Start, _
End:=activedocument.paragraphs (4). Range.End)

For more information about working with a Range object, see Working with a Range object.


? 2006 Microsoft Corporation. All rights reserved.

=================================================================================
Word Developer Reference
Working with Range objects
Show All
Hide All

A common task that you accomplish with Microsoft Visual Basic is to specify a region in your document and then perform certain actions on that area, such as inserting text or applying formatting. For example, you might want to write a macro that looks for a word or phrase in a part of the document. The part of the document can be represented by a Range object. After you identify a Range object, you can apply the methods and properties of the Range object to modify the contents of that range.

A Range object refers to a contiguous region in a document. Each Range object is defined by the start and end character positions. Similar to how bookmarks are used in documents, using a Range object in a Visual Basic procedure identifies a specific part of the document. The Range object can be as small as an insertion point or as large as the entire document. However, unlike bookmarks, a Range object exists only when the procedure that defines it runs.

The Start, End, and StoryType properties uniquely identify a Range object. The start and End properties return or set the position of the start and end characters of the Range object. The character position at the beginning of the document is 0, the position after the first character is 1, and so on. The WdStoryType constant of the StoryType property can represent 11 different article types.

Comments
The Range object is not relevant to the selection. In other words, you can define and modify an area without changing the current selection. You can also define multiple areas in a document, with only one selection in each document pane.

Using the Range method
Use the Range method of the Document object to create a Range object that is in the main text section article: text contained in a single text box or a string of linked text boxes. ) and has a given start and end point. The following example creates a Range object that starts at the beginning of the first character and extends to the tenth character.

Sub Setnewrange ()
Dim Rngdoc as Range
Set Rngdoc = ActiveDocument.Range (start:=0, end:=10)
End Sub

When you apply a property or method to a Range object, you can see that a Range object has been created. The following example applies bold formatting to the first 10 characters of the active document.

Sub Setboldrange ()
Dim Rngdoc as Range
Set Rngdoc = ActiveDocument.Range (start:=0, end:=10)
Rngdoc.bold = True
End Sub

If you need to refer to a Range object more than once, use the SET statement to set a variable whose value is the Range object. However, if you only need to perform one operation on a Range object, you do not have to store the object in a variable. You can also get the same result by using only one instruction that identifies the area and changes the Bold property.

Sub Boldrange ()
ActiveDocument.Range (start:=0, end:=10). Bold = True
End Sub

Similar to bookmarks, an area can span a set of characters or mark a location in a document. The Range object in the following example has the same start and end position. The area does not contain any text. The following example inserts text at the beginning of the active document.

Sub Inserttextbeforerange ()
Dim Rngdoc as Range
Set Rngdoc = ActiveDocument.Range (start:=0, end:=0)
Rngdoc.insertbefore "Hello"
End Sub

You can use the above character position numbers, or define the start and end positions of a range by using the start and End properties for objects such as Selection, Bookmark, or Range. The following example creates a Range object that starts at the beginning of the second paragraph and ends at the end of the third paragraph.

Sub Newrange ()
Dim Doc as Document
Dim Rngdoc as Range

Set doc = ActiveDocument
Set Rngdoc = doc. Range (Start:=doc. Paragraphs (2). Range.Start, _
End:=doc. Paragraphs (3). Range.End)
End Sub

For additional information and examples, see the Range method.

Using the Range property
There are multiple objects that have a Range property, such as Paragraph, Bookmark, and Cell. This property is used to return a Range object. The following example returns a Range object that refers to the first paragraph in the active document.

Sub Setparagraphrange ()
Dim Rngparagraph as Range
Set rngparagraph = activedocument.paragraphs (1). Range
End Sub

After you get the Range object, you can use any of its properties or methods to modify the Range object. The following example selects the second paragraph in the active document and centers the selection.

Sub FormatRange ()
Activedocument.paragraphs (2). Range.Select
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
End Sub

To apply multiple properties or methods to the same Range object, you can use the with ... END with structure. The following example sets the text format for the first paragraph in the active document.

Sub Formatfirstparagraph ()
Dim Rngparagraph as Range
Set rngparagraph = activedocument.paragraphs (1). Range
With Rngparagraph
. Bold = True
. ParagraphFormat.Alignment = wdAlignParagraphCenter
With. Font
. Name = "Stencil"
. Size = 15
End with
End with
End Sub

For additional information and examples, see the Range Properties topic.

Redefine a Range object
Use the SetRange method to redefine an existing Range object. The following example defines a range as the current selection. Then apply the SetRange method to redefine the area so that it contains the current selection and the next 10 characters.

Sub Expandrange ()
Dim Rngparagraph as Range
Set rngparagraph = Selection.Range
Rngparagraph.setrange Start:=rngparagraph.start, _
End:=rngparagraph.end + 10
End Sub

For additional information and examples, see the Range method for Document.

Comments
When you debug a macro, you can use the Select method to ensure that the Range object references the correct text area. For example, the following example selects a Range object that refers to the second and third paragraphs in the active document, and then sets the font format for the selection.

Sub Selectrange ()
Dim Rngparagraph as Range

Set rngparagraph = activedocument.paragraphs (2). Range

Rngparagraph.setrange Start:=rngparagraph.start, _
End:=activedocument.paragraphs (3). Range.End
Rngparagraph.select

Selection.Font.Italic = True
End Sub

? 2006 Microsoft Corporation. All rights reserved.

=========================================================================
Word Developer Reference
WdStoryType Enumeration
Specifies the part type of the selection or item.
Name Value Description
wdCommentsStory 4 Annotation section.
Wdendnotecontinuationnoticestory 17 Endnote Continuation marker section.
Wdendnotecontinuationseparatorstory 16 Endnote Continuation separator section.
Wdendnoteseparatorstory 15 Endnote Separator section.
Wdendnotesstory 3 Endnote section.
wdEvenPagesFooterStory 8 Even Page footer section.
wdEvenPagesHeaderStory 6 Even Page header section.
wdFirstPageFooterStory 11 The first page footer section.
wdFirstPageHeaderStory 10 first Page header section.
Wdfootnotecontinuationnoticestory 14 footnote continuation Mark section.
Wdfootnotecontinuationseparatorstory 13 footnote Continuation separator section.
Wdfootnoteseparatorstory 12 Footnote Separator section.
Wdfootnotesstory 2 footnote section.
wdMainTextStory 1 body part.
wdPrimaryFooterStory 9 Home Foot section.
wdPrimaryHeaderStory 7 Homepage Eyebrow section.
Wdtextframestory 5 text Frame section.

=========================================================================
Word Developer Reference
WdUnits Enumeration
Specifies the unit of measure to use.
Name Value Description
Wdcell 12 cells.
Wdcharacter 1 characters.
Wdcharacterformatting 13-character format.
Wdcolumn 9 columns.
Wditem 16 options.
Wdline of 51 segments.
Wdparagraph 4 paragraphs.
Wdparagraphformatting 14 paragraph format.
Wdrow 10 lines.
Wdscreen 7 screen size.
Wdsection 81 knots.
Wdsentence 3 sentences.
Wdstory 6 section.
Wdtable of 151 tables.
Wdwindow 11 window.
Wdword 2 words.

? 2006 Microsoft Corporation. All rights reserved.
=========================================================================
Word Developer Reference
WdSelectionType Enumeration
Specifies the selection type.
Name Value Description
Wdnoselection 0 No selection.
Wdselectionblock 6 column mode selected.
Wdselectioncolumn 4 Column selection.
Wdselectionframe 3 Frame selection.
Wdselectioninlineshape 7 Inline shape selection.
Wdselectionip 1 inline paragraph selection.
Wdselectionnormal 2 Standard or user-defined selection tolerance.
Wdselectionrow 5 Line Selection.
Wdselectionshape 8 shape selection.

? 2006 Microsoft Corporation. All rights reserved.

=========================================================================
Word Developer Reference
Selection.Information Property
Returns information about the specified selection. Variant type, read-only.
Grammar

An expression. Information (Type)

The expression must be selected. A variable that represents the Selection object.

Parameters

Name required/Optional data type description
Type required wdinformation information types.

Example


This example displays the current page numbers and the total number of pages in the active document.

Visual Basic for Applications
MsgBox "The selection is on page" & _
Selection.Information (wdActiveEndPageNumber) & "of page" _
& Selection.Information (Wdnumberofpagesindocument)

This example selects the table if the selection is in a table.

Visual Basic for Applications
If selection.information (wdwithintable) Then _
Selection.tables (1). Select

This example displays a message that indicates the current section number.

Visual Basic for Applications
Selection.Collapse Direction:=wdcollapsestart
MsgBox "The insertion point are in section" & _
Selection.Information (Wdactiveendsectionnumber)


? 2006 Microsoft Corporation. All rights reserved.

======================================================================
Word Developer Reference
WdInformation Enumeration
Specifies the type of information returned that involves specifying the selected content or range.
Name Value Description
wdActiveEndAdjustedPageNumber 1 Returns the page number that contains the end of the activity for the specified selection or range. If you set a starting page number or make other manual adjustments, the adjusted page number is returned (different from wdActiveEndPageNumber).
wdActiveEndPageNumber 3 Returns the page number that contains the end of the activity for the specified selection or range. Count from the beginning of the document. Ignore any manual adjustments to page numbers (different from wdactiveendadjustedpagenumber).
Wdactiveendsectionnumber 2 Returns the section number that contains the end of the activity for the specified selection or range.
Wdatendofrowmarker 31 This parameter returns TRUE if the specified selection or range is at the end of the row of the table.
Wdcapslock 21 If Caps Lock is valid, this parameter returns TRUE.
Wdendofrangecolumnnumber 17 Returns the table column number that contains the end of the specified selection or range in the table column.
Wdendofrangerownumber 14 Returns the table row number that contains the end of the specified selection or range in the table row.
Wdfirstcharactercolumnnumber 9 Returns the position of the first character in the specified selection or range. If the selection or range is collapsed, the character number immediately to the right of the selection or range is returned (the number is the same as the number of character columns after column in the status bar).
wdFirstCharacterLineNumber 10 Returns the position of the first character in the specified selection or range. If the selection or range is collapsed, the character number immediately to the right of the selection or range is returned (the number is the same as the number of characters following the line in the status bar).
wdframeisselected 11 This parameter returns True if the selection or range is a complete frame or text box.
Wdheaderfootertype 33 Returns a value that indicates the type of header or footer that contains the specified selection or range. For additional information, see the table in the Remarks section.
Wdhorizontalpositionrelativetopage 5 Returns the horizontal position of the specified selected content or range. The position is the distance between the left edge of the selection or range and the left edge of the page, measured in points (1 points = 20 twips, 72 points = 1 inches). If the selection or range is not displayed on the screen, the parameter returns-1.
Wdhorizontalpositionrelativetotextboundary 7 Returns the horizontal position of the specified selection or range relative to the left edge of the nearest body boundary, in points (1 points = 20 twips, 72 lbs = 1 inches). If the selection or range is not displayed on the screen, the parameter returns-1.
Wdinclipboard 38 For information about this constant, see the language reference Help that is included in the Microsoft Office Macintosh Edition.
Wdincommentpane 26 This parameter returns TRUE if the specified selection or range is in the comment pane.
wdInEndnote 36 This parameter returns TRUE if the specified selection or range is in the Endnote area of Page view, or in the endnote pane of normal view.
wdInFootnote 35 This parameter returns TRUE if the specified selection or range is in the footer area of the page view, or in the footnote pane of normal view.
wdInFootnoteEndnotePane 25 This parameter returns TRUE if the specified selection or range is in the footnote or endnote pane of normal view, or in the footnote or endnote area of Page view. For more information, see the previous instructions for wdInFootnote and wdInEndnote.
Wdinheaderfooter 28 This parameter returns TRUE if the specified selection or range is in the header or footer pane, or is in the header or footer of print layout view.
Wdinmasterdocument 34 This parameter returns TRUE if the selection or range is in a master document (that is, a document that contains at least one subdocument).
wdInWordMail 37 This parameter returns TRUE if the specified selection or range is in the header or footer pane, or is in the header or footer of print layout view.
Wdmaximumnumberofcolumns 18 Returns the maximum number of table columns for any row in the selection or range.
Wdmaximumnumberofrows 15 Returns the maximum number of rows in a table in the specified selection or range.
Wdnumberofpagesindocument 4 Returns the number of pages of the document associated with the selected content or range.
Wdnumlock 22 If Num Lock is valid, this parameter returns TRUE.
Wdovertype 23 If Overtype mode is enabled, this parameter returns TRUE. You can use the Overtype property to change the state of the overtype mode.
Wdreferenceoftype 32 Returns a value that indicates the position of the selection relative to the footnote, endnote, or annotation reference, as shown in the table in the Remarks section.
Wdrevisionmarking 24 This parameter returns TRUE if the Track Changes feature is turned on.
Wdselectionmode 20 Returns a value that indicates the current selected mode, as shown in the following table.
Wdstartofrangecolumnnumber 16 Returns the table column number that contains the starting point for the selection or range in the table column.
Wdstartofrangerownumber 13 Returns the table row number that contains the starting point of the selection or range in the table row.
Wdverticalpositionrelativetopage 6 Returns the vertical position of the selection or range, that is, the distance between the top edge of the selection and the top edge of the page, measured in points (1 points = 20 twips, 72 points = 1 inches). If the selection does not appear in the document window, the parameter returns-1.
Wdverticalpositionrelativetotextboundary 8 Returns the vertical position of the selection or range relative to the top edge of the nearest body boundary, measured in points (1 points = 20 twips, 72 lbs = 1 inches). This parameter can be used to determine the position of the insertion point in a frame or table. If the selection does not appear on the screen, the parameter returns-1.
wdWithInTable 12 This parameter returns True if the selection is in a table.
Wdzoompercentage 19 Returns the current magnification percentage set by the Percentage property.

Description


The following table lists the possible values for Wdheaderfootertype.

The type of the value header or footer
-1 None (the selection or range is not in the header or footer)
0 (0) even page header
1 Odd Page header (or header when the odd and even pages are not distinguished)
2 Even page footer
3 Odd Page footer (or footer when not distinguishing odd and even pages)
4 First Header
5 first Footer

The following table lists the possible values for Wdreferenceoftype.

Value Description
1 The selection or area contains, but is not limited to, footnotes, endnotes, or comment references.
0 (0) The selection or range is not preceded by a footnote, endnote, or comment reference.
1 The selection or range is before the footnote reference.
2 The selection or range is positioned before the endnote reference.
3 The selection or range is before the annotation reference.

The following table lists the possible values for Wdselectionmode.

Value selection mode
0 (0) General selection mode
1 Extending the selected mode ("Extended" appears on the status bar)
2 Column selection mode ("column" appears on the status bar)


? 2006 Microsoft Corporation. All rights reserved.

======================================================================
Word Developer Reference
Text in the selected document

Use the Select method to select objects in the document. The Select method can be used with multiple objects, such as Bookmark, Field, Range, and Table. The following example selects the first table in the active document.

Sub selecttable ()
Activedocument.tables (1). Select
End Sub

The following example selects the first field in the active document.

Sub Selectfield ()
Activedocument.fields (1). Select
End Sub

The following example selects the first four paragraphs in the active document. The Range method creates a Range object that references the first four paragraphs, and then applies the Select method to the Range object.

Sub Selectrange ()
Dim Rngparagraphs as Range
Set rngparagraphs = ActiveDocument.Range (_
Start:=activedocument.paragraphs (1). Range.Start, _
End:=activedocument.paragraphs (4). Range.End)
Rngparagraphs.select
End Sub

For more information, see Working with Selection objects.

Handling Selection objects and Range objects--word two important objects in VBA

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.