Selection 对象 (Word)Selection object (Word)

代表窗口或窗格中的当前所选内容。所选内容代表文档中选定(或突出显示)的区域,如果文档中没有选定任何内容,则代表插入点。每个文档窗格只能有一个 Selection 对象,并且在整个应用程序中只能有一个活动的 Selection 对象。Represents the current selection in a window or pane. A selection represents either a selected (or highlighted) area in the document, or it represents the insertion point if nothing in the document is selected. There can be only one Selection object per document window pane, and only one Selection object in the entire application can be active.

备注Remarks

可以使用 Selection 属性返回 Selection 对象。如果 Selection 属性未使用对象限定符,则 Microsoft Word 返回活动文档窗口的活动窗格中的选定内容。以下示例从活动文档中复制当前选定内容。Use the Selection property to return the Selection object. If no object qualifier is used with the Selection property, Microsoft Word returns the selection from the active pane of the active document window. The following example copies the current selection from the active document.

Selection.Copy

以下示例删除 Documents 集合中第三个文档的所选内容。访问该文档的当前所选内容时,该文档无需处于活动状态。The following example deletes the selection from the third document in the Documents collection. The document does not have to be active to access its current selection.

Documents(3).ActiveWindow.Selection.Cut

以下示例复制活动文档第一个窗格中的所选内容,并将其粘贴到第二个窗格中。The following example copies the selection from 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

Text 属性是 Selection 对象的默认属性。使用此属性可设置或返回当前所选内容中的文本。以下示例将当前所选内容中的文本赋给变量 strTemp。如果最后一个字符是段落标记,则删除该字符。The Text property is the default property of the Selection object. Use this property to set or return the text in the current selection. The following example assigns the text in the current selection to the variable strTemp, removing the last character if it is a paragraph mark.

Dim strTemp as String 
 
strTemp = Selection.Text 
If Right(strTemp, 1) = vbCr Then _ 
 strTemp = Left(strTemp, Len(strTemp) - 1)

Selection 对象有多种方法和属性,可用于折叠、扩展或以其他方式更改当前所选内容。以下示例将插入点移至文档末尾并选择最后三行。The Selection object has various methods and properties with which you can collapse, expand, or otherwise change the current selection. The following example moves the insertion point to the end of the document and selects the last three lines.

Selection.EndOf Unit:=wdStory, Extend:=wdMove 
Selection.HomeKey Unit:=wdLine, Extend:=wdExtend 
Selection.MoveUp Unit:=wdLine, Count:=2, Extend:=wdExtend

Selection 对象有多种方法和属性,可用于编辑文档中的所选文字。以下示例选择活动文档中的第一句,并用新段落替换该句。The Selection object has various methods and properties with which you can edit selected text in a document. The following example selects the first sentence in the active document and replaces it with a new paragraph.

Options.ReplaceSelection = True 
ActiveDocument.Sentences(1).Select 
Selection.TypeText "Material below is confidential." 
Selection.TypeParagraph

以下示例删除 Documents 集合中第一个文档的最后一段,并将其粘贴到第二个文档的开头。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

Selection 对象有多种方法和属性,可用于更改当前所选内容的格式。以下示例将当前所选内容的字体从 Times New Roman 更改为 Tahoma。The Selection object has various methods and properties with which you can 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"

可以使用 FlagsInformationType 等属性返回有关当前所选内容的信息。您可以在某个过程中使用以下示例来确定活动文档中是否选择了内容,如果未选择,则跳过该过程的其余部分。Use properties like Flags, Information, and Type to return information about the current selection. You can use the following example in a procedure to determine whether there is anything selected in the active document; if there is not, the rest of the procedure is skipped.

If Selection.Type = wdSelectionIP Then 
 MsgBox Prompt:="You have not selected any text! Exiting procedure..." 
 Exit Sub 
End If

即使将所选内容折叠到插入点,相应内容也不一定为空。例如, Text 属性仍将字符返回到插入点右侧,此字符也会出现在 Selection 对象的 Characters 集合中。但是,从折叠的所选内容调用 CutCopy 等方法将引起错误。Even when a selection is collapsed to an insertion point, it is not necessarily empty. For example, the Text property will still return the character to the right of the insertion point; this character also appears in the Characters collection of the Selection object. However, calling methods like Cut or Copy from a collapsed selection causes an error.

用户可以选择文档中不代表连续文本的区域(例如,在使用 Alt 键和鼠标时)。由于这种所选内容的行为不可预知,因此,您可能希望在代码中包含一个步骤,先检查所选内容的 Type 属性,然后再对它执行任意操作 ( Selection.Type = wdSelectionBlock)。同样,包含表格单元格的所选内容也会导致不可预知的行为。 Information 属性将指示所选内容是否在某个表中 ( Selection.Information(wdWithinTable) = True)。以下示例确定所选内容是否正常(例如,它不是表中的行或列,也不是垂直文本块,等等),您可以先用该示例对当前所选内容进行测试,然后再对它执行任意操作。It is possible for the user to select a region in a document that does not represent contiguous text (for example, when using the ALT key with the mouse). Because the behavior of such a selection can be unpredictable, you may want to include a step in your code that checks the Type property of a selection before performing any operations on it ( Selection.Type = wdSelectionBlock). Similarly, selections that include table cells can also lead to unpredictable behavior. The Information property will tell you if a selection is inside a table ( Selection.Information(wdWithinTable) = True). The following example determines if a selection is normal (for example, it is not a row or column in a table, it is not a vertical block of text); you could use it to test the current selection before performing any operations on it.

If Selection.Type <> wdSelectionNormal Then 
 MsgBox Prompt:="Not a valid selection! Exiting procedure..." 
 Exit Sub 
End If

由于 Range 对象与 Selection 对象的许多方法和属性都相同,因此,如果没有必要对当前所选内容进行实际更改,最好使用 Range 对象来处理文档。Because Range objects share many of the same methods and properties as Selection objects, using Range objects is preferable for manipulating a document when there is not a reason to physically change the current selection. 有关 Selection 对象和 Range 对象的详细信息,请参阅处理 Selection 对象处理 Range 对象For more information about Selection and Range objects, see Working with the Selection object and Working with Range objects.

方法Methods

名称Name
BoldRunBoldRun
CalculateCalculate
ClearCharacterAllFormattingClearCharacterAllFormatting
ClearCharacterDirectFormattingClearCharacterDirectFormatting
ClearCharacterStyleClearCharacterStyle
ClearFormattingClearFormatting
ClearParagraphAllFormattingClearParagraphAllFormatting
ClearParagraphDirectFormattingClearParagraphDirectFormatting
ClearParagraphStyleClearParagraphStyle
CollapseCollapse
ConvertToTableConvertToTable
CopyCopy
CopyAsPictureCopyAsPicture
CopyFormatCopyFormat
CreateAutoTextEntryCreateAutoTextEntry
CreateTextboxCreateTextbox
CutCut
DeleteDelete
DetectLanguageDetectLanguage
EndKeyEndKey
EndOfEndOf
EscapeKeyEscapeKey
ExpandExpand
ExportAsFixedFormatExportAsFixedFormat
ExtendExtend
GoToGoTo
GoToEditableRangeGoToEditableRange
GoToNextGoToNext
GoToPreviousGoToPrevious
HomeKeyHomeKey
InRangeInRange
InsertAfterInsertAfter
InsertBeforeInsertBefore
InsertBreakInsertBreak
InsertCaptionInsertCaption
InsertCellsInsertCells
InsertColumnsInsertColumns
InsertColumnsRightInsertColumnsRight
InsertCrossReferenceInsertCrossReference
InsertDateTimeInsertDateTime
InsertFileInsertFile
InsertFormulaInsertFormula
InsertNewPageInsertNewPage
InsertParagraphInsertParagraph
InsertParagraphAfterInsertParagraphAfter
InsertParagraphBeforeInsertParagraphBefore
InsertRowsInsertRows
InsertRowsAboveInsertRowsAbove
InsertRowsBelowInsertRowsBelow
InsertStyleSeparatorInsertStyleSeparator
InsertSymbolInsertSymbol
InsertXMLInsertXML
InStoryInStory
IsEqualIsEqual
ItalicRunItalicRun
LtrParaLtrPara
LtrRunLtrRun
MoveMove
MoveDownMoveDown
MoveEndMoveEnd
MoveEndUntilMoveEndUntil
MoveEndWhileMoveEndWhile
MoveLeftMoveLeft
MoveRightMoveRight
MoveStartMoveStart
MoveStartUntilMoveStartUntil
MoveStartWhileMoveStartWhile
MoveUntilMoveUntil
MoveUpMoveUp
MoveWhileMoveWhile
NextNext
NextFieldNextField
NextRevisionNextRevision
NextSubdocumentNextSubdocument
PastePaste
PasteAndFormatPasteAndFormat
PasteAppendTablePasteAppendTable
PasteAsNestedTablePasteAsNestedTable
PasteExcelTablePasteExcelTable
PasteFormatPasteFormat
PasteSpecialPasteSpecial
PreviousPrevious
PreviousFieldPreviousField
PreviousRevisionPreviousRevision
PreviousSubdocumentPreviousSubdocument
ReadingModeGrowFontReadingModeGrowFont
ReadingModeShrinkFontReadingModeShrinkFont
RtlParaRtlPara
RtlRunRtlRun
SelectSelect
SelectCellSelectCell
SelectColumnSelectColumn
SelectCurrentAlignmentSelectCurrentAlignment
SelectCurrentColorSelectCurrentColor
SelectCurrentFontSelectCurrentFont
SelectCurrentIndentSelectCurrentIndent
SelectCurrentSpacingSelectCurrentSpacing
SelectCurrentTabsSelectCurrentTabs
SelectRowSelectRow
SetRangeSetRange
ShrinkShrink
ShrinkDiscontiguousSelectionShrinkDiscontiguousSelection
SortSort
SortAscendingSortAscending
SortByHeadingsSortByHeadings
SortDescendingSortDescending
SplitTableSplitTable
StartOfStartOf
ToggleCharacterCodeToggleCharacterCode
TypeBackspaceTypeBackspace
TypeParagraphTypeParagraph
TypeTextTypeText
WholeStoryWholeStory

属性Properties

名称Name
ActiveActive
ApplicationApplication
BookmarkIDBookmarkID
BookmarksBookmarks
BordersBorders
CellsCells
CharactersCharacters
ChildShapeRangeChildShapeRange
ColumnsColumns
ColumnSelectModeColumnSelectMode
CommentsComments
CreatorCreator
DocumentDocument
EditorsEditors
EndEnd
EndnoteOptionsEndnoteOptions
EndnotesEndnotes
EnhMetaFileBitsEnhMetaFileBits
ExtendModeExtendMode
FieldsFields
FindFind
FitTextWidthFitTextWidth
FlagsFlags
FontFont
FootnoteOptionsFootnoteOptions
FootnotesFootnotes
FormattedTextFormattedText
FormFieldsFormFields
FramesFrames
HasChildShapeRangeHasChildShapeRange
HeaderFooterHeaderFooter
HTMLDivisionsHTMLDivisions
HyperlinksHyperlinks
InformationInformation
InlineShapesInlineShapes
IPAtEndOfLineIPAtEndOfLine
IsEndOfRowMarkIsEndOfRowMark
LanguageDetectedLanguageDetected
LanguageIDLanguageID
LanguageIDFarEastLanguageIDFarEast
LanguageIDOtherLanguageIDOther
NoProofingNoProofing
OMathsOMaths
OrientationOrientation
PageSetupPageSetup
ParagraphFormatParagraphFormat
ParagraphsParagraphs
ParentParent
PreviousBookmarkIDPreviousBookmarkID
RangeRange
RowsRows
SectionsSections
SentencesSentences
ShadingShading
ShapeRangeShapeRange
StartStart
StartIsActiveStartIsActive
StoryLengthStoryLength
StoryTypeStoryType
StyleStyle
TablesTables
TextText
TopLevelTablesTopLevelTables
TypeType
WordOpenXMLWordOpenXML
WordsWords
XMLXML

另请参阅See also

Word 对象模型引用Word Object Model Reference

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.