返回集合中的对象 (Word)Returning an Object from a Collection (Word)

Item方法返回集合中的单个对象。The Item method returns a single object from a collection. 下面的示例将docFirst变量设置为**document** 对象, 该对象代表**Documents** 集合中的第一个文档。The following example sets the docFirst variable to a Document object that represents the first document in the Documents collection.

Sub SetFirstDoc() 
    Dim docFirst As Document 
    Set docFirst = Documents.Item(1) 
End Sub

Item方法是大多数集合的默认方法, 因此可以通过省略Item关键字编写相同的语句, 使其更加简洁。The Item method is the default method for most collections, so you can write the same statement more concisely by omitting the Item keyword.

Sub SetFirstDoc() 
    Dim docFirst As Document 
    Set docFirst = Documents(1) 
End Sub

命名的对象Named Objects

尽管通常可以使用Item方法指定整数值, 但通过名称返回对象可能会更方便。Although you can usually specify an integer value with the Item method, it may be more convenient to return an object by name. 下列示例将焦点切换到名为 Sales.doc 的文档。The following example switches the focus to a document named Sales.doc.

Sub ActivateDocument() 
    Documents("Sales.doc").Activate 
    MsgBox ActiveDocument.Name 
End Sub

下面的示例选定活动文档中的第一个书签标记的文本。The following example selects the text marked by the first bookmark in the active document.

Sub SelectBookmark() 
    ActiveDocument.Bookmarks(1).Select 
    MsgBox Selection.Text 
End Sub

并非所有的集合都可用名称进行索引。Not all collections can be indexed by name. 若要确定有效的集合索引值,请参阅该集合对象的主题。To determine the valid collection index values, see the collection object topic.

预定义的索引值Predefined Index Values

一些集合具有可用于返回单独的对象的预定义索引值。Some collections have predefined index values that you can use to return single objects. 每个预定义的索引值由一个常量表示。Each predefined index value is represented by a constant. 例如, 可以使用 border 属性指定一个**WdBorderType** 常量**** , 以返回单个**Border** 对象。For example, you specify a WdBorderType constant with the Borders property to return a single Border object.

下面的示例在所选内容的第一段下方添加一条 0.75 磅粗的单线型边框。The following example adds a single 0.75-point border below the first paragraph in the selection.

Sub AddBorderToFirstParagraphInSelection() 
    With Selection.Paragraphs(1).Borders(wdBorderBottom) 
        .LineStyle = wdLineStyleSingle 
        .LineWidth = wdLineWidth300pt 
        .Color = wdColorBlue 
    End With 
End Sub

支持和反馈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.