Process Selection object and range object -- two important objects in Word VBA

Source: Internet
Author: User

Process Selection object and range object -- two important objects in Word VBA

Word developer reference
Selection object
Indicates the currently selected content in a window or pane. The selected content indicates the selected (or highlighted) area in the document. If no content is selected in the document, it indicates the insertion point. Each document pane can have only one
Selection object, and only one active selection object can be found in the entire application.
Description

You can use the selection attribute to return the selection object. If the selection property does not use the object qualifier
Microsoft Office Word returns the selected content in the activity pane of the activity document window. The following example copies the selected content from the activity document.

Selection. Copy

The following example deletes the selected content of the third document in the documents set. When you access the selected content of this document, this document does not need to be active.

Documents (3). activewindow. selection. Cut

In the following example, copy the selected content in the first pane of the activity document and paste it into the second pane.

Activedocument. activewindow. panes (1). selection. Copy
Activedocument. activewindow. panes (2). selection. Paste

The text attribute is selection.
The default property of the object. You can use this property to set or return text in the selected content. The following example assigns the text in the selected content to the variable
Strtemp. If the last character is a paragraph mark, delete it.

Dim strtemp as string

Strtemp = selection. Text
If right (strtemp, 1) = vbcr then _
Strtemp =
Left (strtemp, Len (strtemp)-1)

Selection
Objects have multiple methods and attributes that can be used to collapse, expand, or otherwise change the selected content. In the following example, the insertion point is moved to the end of the document and the last three rows are selected.

Selection. endof unit: = wdstory, extend: = wdmove
Selection. homekey unit: = wdline, extend: = wdextend
Selection. moveup unit: = wdline, Count: = 2, extend: = wdextend

Selection
Objects can be edited by using multiple methods and attributes. In the following example, select the first sentence in the activity document and replace it with a new paragraph.

Options. replaceselection = true
Activedocument. Sentences (1). Select
Selection. typetext "material below is confidential ."
Selection. typeparagraph

In the following example, the last section of the first document in the documents set is deleted and pasted to the beginning of the second document.

With documents (1)

. Paragraphs. Last. range. Select

. Activewindow. selection. Cut
End

With documents (2). activewindow. Selection
. Startof
Unit: = wdstory, extend: = wdmove
. Paste
End

The selection object has multiple methods and attributes that can be used to change the format of the selected content. The following example shows how to change the font of the selected content from Times New
Roman is changed to tahoma.

If selection. Font. Name = "Times New Roman" then _

Selection. Font. Name = "tahoma"

You can use flags, information, and type.
. In a specific process, you can use the following example to determine whether the content is selected in the activity document. If no content is selected, skip the rest of the process.

If selection. type = wdselectionip then
Msgbox
Prompt: = "You have not selected any text! Exiting
Procedure ..."
Exit
Sub
End if

Even if you fold the selected content to the insertion point, the content is not empty. For example, the text attribute still returns the character to the right of the insertion point, which also appears in
The characters set of the selection object. However, calling methods such as cut or copy from the selected collapsed content will cause an error.

You can select a region that does not represent continuous text in the document (for example, when you use alt
). Because the behavior of the selected content is unpredictable, you may want to include a step in the code to first check the type of the selected content
And then perform any operation on it (selection. type =
Wdselectionblock ). Similarly, the selected content containing table cells can lead to unpredictable behavior. Information
The property indicates whether the selected content is in a table (selection. Information (wdwithintable) =
True ). The following example shows whether the selected content is normal (for example, it is not a row or column in a table, or a vertical text block). You can use this example to test the selected content, and then perform any operation on it.

If selection. Type <>
Wdselectionnormal then
Msgbox
Prompt: = "not a valid selection! Exiting procedure ..."
Exit
Sub
End if

Because many methods and attributes of the range object and selection object are the same, it is best to use
Range object to process documents. For more information about selection objects and range objects, see processing selection objects and Processing
Range object.

? 2006 Microsoft Corporation. All rights reserved.

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

Word developer reference
Process Selection object

Use Microsoft Office Word
When processing a document, you usually select the text first and then perform operations on the selected content, such as setting the text format or typing the text. In Microsoft Visual Basic
You do not need to select the text before modifying the text, but create a range object that references a specific area in the document. For information about defining a range object, see Process
Range object. However, if you want the code to respond or change the selected content, you can use the selection object.

If no text has been selected, you can use the select method to select the text associated with a specific object and create a selection
Object. For example, the following command selects the first word in the activity document.

Sub selectfirstword ()

Activedocument. Words (1). Select
End sub

For more information, see select text in the document.

If you have selected the text, you can use the selection attribute to return a selection
Object, which indicates the content currently selected in the document. Each document can have only one Selection
Object, which always accesses the selected content. The following example changes the section format in the selected content.

Sub formatselection ()

Selection. Paragraphs. leftindent = inchestopoints (0.5)
End sub

This example inserts the word "hello" after the selected content ".

Sub inserttextafterselection ()

Selection. insertafter text: = "hello"
End sub

This example applies the bold format to the selected text.

Sub boldselectedtext ()

Selection. Font. Bold = true
End sub

The macro recorder often creates and uses selection.
Macro of the object. The following example is created using a macro recorder. This macro selects the first two words in the activity document and applies the bold format 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 completes the same task without selecting text or using a 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 continuous area in the document. Each range object is defined by a starting character position and a ending character position.
Description

Similar to the usage of bookmarks in documents, a Range object is used to identify specific parts of a document in Visual Basic. But unlike bookmarks, Range
The object exists only when the process of defining the object is run. Range
The object is independent of the selected content. That is, you can define and process a range without changing the selected content. You can also define multiple ranges in the document, but each pane can have only one selected content.

You can use the range method to return a range object, which is defined by the specified start and end character positions. The following example returns the first 10
Range object.

Set myrange = activedocument. Range (START: = 0, end: = 10)

You can use the range attribute to return a range object, which is defined by the start and end points of another object. Range
Attributes can be applied to many objects (such as paragraph, Bookmark, and cell ). The following example returns a range that represents the first section of the activity document.
Object.

Set arange = activedocument. Paragraphs (1). Range

The following example returns a range object that represents the second to fourth sections of the activity document.

Set arange = activedocument. Range (_

Start: = activedocument. Paragraphs (2). range. Start ,_

End: = activedocument. Paragraphs (4). range. End)

For more information about processing range objects, see processing range objects.

? 2006 Microsoft Corporation. All rights reserved.

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

Word developer reference
Process range objects
Show all
Hide all

Use Microsoft Visual Basic
A common task is to specify a region in the document and perform some operations on the region, such as inserting text or applying format. For example, you may need to write a macro to find a word or phrase in a part of the document. This document can be used
Range object. After the range object is identified, you can apply the methods and attributes of the range object to modify the content of the region.

The range object references a continuous area in the document. Each range
Objects are defined by the start and end character positions. Similar to using bookmarks in documents, range is used in Visual Basic.
Objects can identify specific parts of a document. The range object can be as small as an insert point or as large as the entire document. But unlike bookmarks, Range
An object exists only when it is defined as a running process.

The START, end, And storytype attributes uniquely identify a range object. Return or set the start and end attributes
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. Storytype
Wdstorytype constants can represent 11 different article types.

Note
Range
The object has nothing to do with the selected content. That is, you can define and modify a region without changing the selected content. You can also define multiple areas in the document, and each document pane contains only one selected area.

Use the range method
You can use the range method of the Document Object to create a range object, which is located in the main text section.
(Article: text contained in a single text box or a string of connected text boxes .) And has a given start point and end point. The following example creates a range
Object starting from the first character and extending to the tenth character.

Sub setnewrange ()
Dim rngdoc
As range
Set rngdoc =
Activedocument. Range (START: = 0, end: = 10)
End sub

When you apply an attribute or method to a range object, you can see that a range object has been created. The following example shows the first 10
Characters in bold format.

Sub setboldrange ()
Dim rngdoc
As range
Set rngdoc =
Activedocument. Range (START: = 0, end: = 10)
Rngdoc. Bold
= True
End sub

If you need to reference a range object multiple times, you can use the set statement to set a variable whose value is the range object. However, if you only need
If an operation is performed on a range object, the object is not stored in a variable. The same results can be obtained by using only one command that identifies a region and modifies the bold attribute.

Sub boldrange ()

Activedocument. Range (START: = 0, end: = 10). Bold = true
End sub

Similar to bookmarks, a region can span a group of characters or mark a location in a document. Range in the following example
The start and end positions of the object are the same. This area does not contain any text. The following example inserts text at the beginning of the activity document.

Sub inserttextbeforerange ()
Dim rngdoc
As range
Set rngdoc =
Activedocument. Range (START: = 0, end: = 0)

Rngdoc. insertbefore "hello"
End sub

You can use the preceding character location numbers, or use the start and end attributes for selection, Bookmark, or range
To define the start and end positions of the region. The following example creates a range object, which starts from the beginning of the second paragraph and ends at the end of the third paragraph.

Sub newrange ()
Dim doc
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 other information and examples, see the range method.

Use the range attribute
Multiple objects have range attributes, such as paragraph, Bookmark, and cell. This attribute is used to return range
Object. The following example returns a range object that references the first section of the activity document.

Sub setparagraphrange ()
Dim
Rngparagraph as range
Set
Rngparagraph = activedocument. Paragraphs (1). Range
End sub

After obtaining the range object, you can use any of its attributes or methods to modify the range.
Object. In the following example, select the second section of the activity document and center the selected content.

Sub formatrange ()

Activedocument. Paragraphs (2). range. Select

Selection. paragraphformat. Alignment = wdalignparagraphcenter
End sub

To apply multiple attributes or methods to the same range object, use... End
Structure. The following example sets the text format of the First Section of the activity document.

Sub formatfirstparagraph ()
Dim
Rngparagraph as range
Set
Rngparagraph = activedocument. Paragraphs (1). Range
With
Rngparagraph

. Bold = true

. Paragraphformat. Alignment = wdalignparagraphcenter

With. Font

. Name = "stencel"

. Size = 15

End
End
With
End sub

For other information and examples, see the range attribute topic.

Redefinition of the range object
You can use the setrange method to redefine an existing range object. The following example defines a region as the selected content. Apply setrange
Method to redefine the region, so that it contains the currently selected content 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 other information and examples, see the range method of document.

Note
When debugging 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, which references the second and third sections of the active document, and then sets the font format of the selected content.

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 type of the selected content or part of the project.
NAME value description
Wdcommentsstory 4 annotation section.
Wdendnotecontinuationnoticestory 17 end note continuation mark part.
Wdendnotecontinuationseparatorstory 16 end note continuation separator part.
Wdendnoteseparatorstory 15 end note separator.
Wdendnotesstory 3 End note.
Wdevenpagesfooterstory 8 is an even part of the page footer.
Wdevenpagesheaderstory 6 is an even page header.
Wdfirstpagefooterstory 11 homepage footer.
Wdfirstpageheaderstory 10 homepage header.
Wdfootnotecontinuationnoticestory 14 footer continuation mark section.
Wdfootnotecontinuationseparatorstory 13 footer continuation separator section.
Wdfootnoteseparatorstory 12 footer separator section.
Wdfootnotesstory 2 footer section.
Wdmaintextstory 1 body.
Wdprimaryfooterstory 9 home page.
Wdprimaryheaderstory 7 master header.
Wdtextframestory 5 text framework section.

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

Word developer reference
Wdunits Enumeration
Specify the unit of measurement to be used.
NAME value description
Wdcell 12 cells.
Wdcharacter 1 character.
Wdcharacterformatting 13 character format.
Wdcolumn 9.
Wditem 16 option.
Wdline 5 is a line segment.
Wdparagraph 4 section.
Wdparagraphformatting 14 section format.
10 rows of wdrow.
Wdscreen 7 screen size.
Wdsection 8.
Wdsentence 3 sentence.
Wdstory 6.
Wdtable 15 is a table.
Wdwindow 11 window.
Wdword.

? 2006 Microsoft Corporation. All rights reserved.
========================================================== ======================================

Word developer reference
Wdselectiontype Enumeration
Specifies the selection type.
NAME value description
Wdnoselection 0 is not selected.
Wdselectionblock 6 columns are selected.
Select four columns for wdselectioncolumn.
Wdselectionframe 3 frame selection.
Wdselectioninlineshape 7 embedded shape selection.
Wdselectionip 1 embedded section selection.
Wdselectionnormal 2 standard or user-defined selection capacity.
Select 5 rows for wdselectionrow.
Select the wdselectionshape 8 shape.

? 2006 Microsoft Corporation. All rights reserved.

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

Word developer reference
Selection. Information attributes
Returns information about the specified content. Variant Type, read-only.
Syntax

Expression. Information (type)

The expression is required. One represents Selection
Object variable.

Parameters

Name required/optional data type description
Type: wdinformation information type.

Example

This example shows the current page number and the total page number of the active document.

Visual Basic for Applications
Msgbox "the selection is on page "&_

Selection. Information (wdactiveendpagenumber) &"
Page "_

&
Selection. Information (wdnumberofpagesindocument)

If the selected content is in a table, this table is selected in this example.

Visual Basic for Applications
If selection. Information (wdwithintable) Then _

Selection. Tables (1). Select

This example shows a message indicating the current section number.

Visual Basic for Applications
Selection. collapse direction: = wdcollapsestart
Msgbox "the insertion point is in section "&
_

Selection. Information (wdactiveendsectionnumber)

? 2006 Microsoft Corporation. All rights reserved.

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

Word developer reference
Wdinformation Enumeration
Specifies the type of information returned to specify the selected content or region.
NAME value description
Wdactiveendadjustedpagenumber 1
Return page number, which contains the activity ending of the specified selected content or area. If you set a start page number or make other manual adjustments, the adjusted page number (
Wdactiveendpagenumber is different ).
Wdactiveendpagenumber 3
Return page number, which contains the activity ending of the specified selected content or area. Starts with a document. Ignore any manual adjustments to the page number (
Wdactiveendadjustedpagenumber ).
Wdactiveendsectionnumber 2 returns the node number, which contains the activity ending of the specified selected content or region.
Wdatendofrowmarker 31 if the specified content or area is at the end of the table row, this parameter returns true.
Wdcapslock 21 returns true if Caps Lock is valid.
Wdendofrangecolumnnumber 17 returns the table column number, which contains the specified selected content or the end of the region.
Wdendofrangerownumber 14 returns the row number of the table, which contains the end of the specified selected content or area.
Wdfirstcharactercolumnnumber 9
Returns the position of the first character in the specified selected content or region. If the selected content or area is collapsed, the character number next to the selected content or area is returned (the number is the same as the number of character columns after the "column" in the status bar ).

Wdfirstcharacterlinenumber 10
Returns the position of the first character in the specified selected content or region. If the selected content or area is collapsed, the character number next to the selected content or area is returned (the number is the same as the number of lines after the "row" in the status bar ).

Wdframeisselected 11 returns true if the selected content or area is a complete text box or text box.
Wdheaderfootertype 33
Returns a value that indicates the type of the header or footer that contains the specified content or area. For more information, see tables in the "Annotations" section.
Wdhorizontalpositionrelativetopage 5
Returns the horizontal position of the selected content or region. This location is the distance between the left edge of the selected content or area and the left edge of the page, measured in lbs (1 lb = 20 Ti, 72 lbs
= 1 inch ). If the selected content or area is not displayed on the screen, this parameter returns-1.
Wdhorizontalpositionrelativetotextboundary 7
Returns the horizontal position of the selected content or area relative to the left edge of the nearest body boundary, in lbs (1 lb = 20 Ti, 72 lB = 1
). If the selected content or area is not displayed on the screen, this parameter returns-1.
Wdinclipboard 38 for information about this constant, see include in Microsoft Office Macintosh Edition
Language Reference help in.
Wdincommentpane 26 if the specified content or area is in the comment pane, this parameter returns true.
Wdinendnote 36 if the specified content or area is in the final note area of the page view or in the final note pane of the normal view, this parameter is returned
True.
Wdinfootnote 35 if the specified content or area is in the footer area of the page view or in the footer pane of the normal view, this parameter returns
True.
Wdinfootnoteendnotepane 25
If the specified content or area is in the footer or footer pane of the common view, or in the footer or footer area of the page view, this parameter returns
True. For more information, see the previous section about wdinfootnote
And wdinendnote.
Wdinheaderfooter 28 if the specified content or area is in the header or footer pane, or in the header or footer of the page view, this parameter returns
True.
Wdinmasterdocument 34 if the selected content or region is in the master document (that is, the document that contains at least one sub-document), this parameter returns
True.
Wdinwordmail 37 if the specified content or area is in the header or footer pane, or in the header or footer of the page view, this parameter returns
True.
Wdmaximumnumberofcolumns 18 returns the maximum number of table columns for any row in the selected content or region.
Wdmaximumnumberofrows 15 returns the maximum number of rows of tables in the specified selected content or region.
Wdnumberofpagesindocument 4 returns the number of pages of the document associated with the selected content or region.
Wdnumlock 22 returns true if num lock is valid.
Wdovertype 23 if rewrite mode is enabled, this parameter returns true. You can use the overtype attribute to change the state of the rewrite mode.
Wdreferenceoftype 32
Returns a value that indicates the position of the selected content relative to the footer, tail note, or annotation reference, as shown in the table in the "annotation" section.
Wdrevisionmarking 24 returns true if the revision function is enabled.
Wdselectionmode 20 returns a value indicating the current selected mode, as shown in the following table.
Wdstartofrangecolumnnumber 16 returns the table column number, which contains the starting point of the selected content or region.
Wdstartofrangerownumber 13 returns the row number of the table, which contains the starting point of the selected content or region.
Wdverticalpositionrelativetopage 6
Returns the vertical position of the selected content or area, that is, the distance between the top edge of the selected content and the top edge of the page, in lbs (1 lb = 20 Ti, 72 lB = 1)
). If the selected content is not displayed in the document window, this parameter returns-1.
Wdverticalpositionrelativetotextboundary 8
Returns the vertical position of the selected content or area relative to the upper edge of the nearest body boundary, in lbs (1 lb = 20 Ti, 72 lB = 1
). This parameter can be used to determine the insert point position in a text box or table. If the selected content is not displayed on the screen, this parameter returns-1.
Wdwithintable 12 if the selected content is in the table, this parameter returns true.
Wdzoompercentage 19 returned by percentage
The current magnification of the attribute.

Description

The following table lists the possible wdheaderfootertype values.

Type of the value header or footer
-1 none (the selected content or region is not in the header or footer)
0 (zero) Even page header
1. Odd page header (or the header when an odd or even page is not distinguished)
2 even page footer
3. Odd page footer (or footer that does not distinguish between odd and even pages)
4. First Header
5. The first footer

The following table lists the possible values of wdreferenceoftype.

Value description
-1 The selected content or area contains but is not limited to footer, end note, or annotation reference.
0 (0) the selected content or region is not prior to the footer, tail note, or annotation reference.
1 The selected content or area is located before the reference of the footer.
2. The selected content or area is located before the end note reference.
3. The selected content or region is before the annotation reference.

The following table lists the possible values of wdselectionmode.

Value Selection Mode
0 (0) General selection mode
1. Expand the selected mode ("extension" appears on the status bar)
Two column selection modes ("column" appears on the status bar)

? 2006 Microsoft Corporation. All rights reserved.

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

Word developer reference
Text in selected document

You can use the select method to select objects in the document. The select method can be used for multiple objects, such as bookmark, field, and range.
And table. The following example selects the first table in the activity document.

Sub selecttable ()

Activedocument. Tables (1). Select
End sub

The following example selects the first domain in the activity document.

Sub selectfield ()

Activedocument. Fields (1). Select
End sub

The following example selects the first four paragraphs in the activity document. The range method is used to create a range object that references the first four paragraphs, and then select
Method is applied 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 process selection objects.

? 2006 Microsoft Corporation. All rights reserved.

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.