Returning an Object from a Collection (Word)
The Item method returns a single object from a collection. 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
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
Although you can usually specify an integer value with the Item method, it may be more convenient to return an object by name. 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. For example, you specify a WdBorderType constant with the Borders property to return a single Border object.
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
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기