title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range object (Word) |
vbawd10.chm2398 |
vbawd10.chm2398 |
word |
Word.Range |
15a7a1c4-5f3f-5b6e-60e9-29688de3f274 |
05/23/2019 |
medium |
Range object (Word)
Represents a contiguous area in a document. Each Range object is defined by a starting and ending character position.
Remarks
Similar to the way bookmarks are used in a document, Range objects are used in Visual Basic procedures to identify specific portions of a document. However, unlike a bookmark, a Range object only exists while the procedure that defined it is running. Range objects are independent of the selection. That is, you can define and manipulate a range without changing the selection. You can also define multiple ranges in a document, while there can be only one selection per pane.
Use the Range method to return a Range object defined by the given starting and ending character positions. The following example returns a Range object that refers to 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 defined by the beginning and end of another object. The Range property applies to many objects (for example, Paragraph, Bookmark, and Cell). The following example returns a Range object that refers to the first paragraph in the active document.
Set aRange = ActiveDocument.Paragraphs(1).Range
The following example returns a Range object that refers to the second through 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 Range objects, see Working with Range objects.
Methods
- AutoFormat
- Calculate
- CheckGrammar
- CheckSpelling
- CheckSynonyms
- Collapse
- ComputeStatistics
- ConvertHangulAndHanja
- ConvertToTable
- Copy
- CopyAsPicture
- Cut
- Delete
- DetectLanguage
- EndOf
- Expand
- ExportAsFixedFormat
- ExportAsFixedFormat2
- ExportFragment
- GetSpellingSuggestions
- GoTo
- GoToEditableRange
- GoToNext
- GoToPrevious
- ImportFragment
- InRange
- InsertAfter
- InsertAlignmentTab
- InsertAutoText
- InsertBefore
- InsertBreak
- InsertCaption
- InsertCrossReference
- InsertDatabase
- InsertDateTime
- InsertFile
- InsertParagraph
- InsertParagraphAfter
- InsertParagraphBefore
- InsertSymbol
- InsertXML
- InStory
- IsEqual
- LookupNameProperties
- ModifyEnclosure
- Move
- MoveEnd
- MoveEndUntil
- MoveEndWhile
- MoveStart
- MoveStartUntil
- MoveStartWhile
- MoveUntil
- MoveWhile
- Next
- NextSubdocument
- Paste
- PasteAndFormat
- PasteAppendTable
- PasteAsNestedTable
- PasteExcelTable
- PasteSpecial
- PhoneticGuide
- Previous
- PreviousSubdocument
- Relocate
- Select
- SetListLevel
- SetRange
- Sort
- SortAscending
- SortByHeadings
- SortDescending
- StartOf
- TCSCConverter
- WholeStory
Properties
- Application
- Bold
- BoldBi
- BookmarkID
- Bookmarks
- Borders
- Case
- Cells
- Characters
- CharacterStyle
- CharacterWidth
- Columns
- CombineCharacters
- Comments
- Conflicts
- ContentControls
- Creator
- DisableCharacterSpaceGrid
- Document
- Duplicate
- Editors
- EmphasisMark
- End
- EndnoteOptions
- Endnotes
- EnhMetaFileBits
- Fields
- Find
- FitTextWidth
- Font
- FootnoteOptions
- Footnotes
- FormattedText
- FormFields
- Frames
- GrammarChecked
- GrammaticalErrors
- HighlightColorIndex
- HorizontalInVertical
- HTMLDivisions
- Hyperlinks
- ID
- Information
- InlineShapes
- IsEndOfRowMark
- Italic
- ItalicBi
- Kana
- LanguageDetected
- LanguageID
- LanguageIDFarEast
- LanguageIDOther
- ListFormat
- ListParagraphs
- ListStyle
- Locks
- NextStoryRange
- NoProofing
- OMaths
- Orientation
- PageSetup
- ParagraphFormat
- Paragraphs
- ParagraphStyle
- Parent
- ParentContentControl
- PreviousBookmarkID
- ReadabilityStatistics
- Revisions
- Rows
- Scripts
- Sections
- Sentences
- Shading
- ShapeRange
- ShowAll
- SpellingChecked
- SpellingErrors
- Start
- StoryLength
- StoryType
- Style
- Subdocuments
- SynonymInfo
- Tables
- TableStyle
- Text
- TextRetrievalMode
- TextVisibleOnScreen
- TopLevelTables
- TwoLinesInOne
- Underline
- Updates
- WordOpenXML
- Words
- XML
See also
- Word Object Model Reference
[!includeSupport and feedback]
Show All
Working with Range Objects
A common task when using Visual Basic is to specify an area in a document and then do something with it, such as insert text or apply formatting. For example, you may want to write a macro that locates a word or phrase within a portion of a document. The portion of the document can be represented by a Range
object. After the Range object is identified, methods and properties of the Range object can be applied in order to modify the contents of the range.
A Range object refers to a contiguous area in a document. Each Range object is defined by a starting and ending character position. Similar to the way bookmarks are used in a document, Range objects are used in Visual Basic procedures to identify specific portions of a document. A Range object can be as small as the insertion point or as large as the entire document. However, unlike a bookmark, a Range object only exists while the procedure that defined it is running.
The Start, End
and StoryType
properties uniquely identify a Range object. The Start and End properties return or set the starting and ending character positions of the Range object. The character position at the beginning of the document is zero, the position after the first character is one, and so on. There are eleven different story types represented by the WdStoryType constants of the StoryType property.
Note Range objects are independent of the selection. That is, you can define and modify a range without changing the current selection. You can also define multiple ranges in a document, while there is only one selection per document pane.
Using the Range method
The Range
method is used to create a Range object in the specified document. The Range method (which is available from the Document
object) returns a Range object located in the main story given a start and end point. The following example creates a Range object that is assigned to a variable.
Sub SetNewRange()
Dim rngDoc As Range
Set rngDoc = ActiveDocument.Range(Start:=0, End:=10)
End Sub
The variable refers to the first ten characters in the active document. You can see that the Range object has been created when you apply a property or method to the Range object stored in a variable. The following example applies bold formatting to the first ten characters in the active document.
Sub SetBoldRange()
Dim rngDoc As Range
Set rngDoc = ActiveDocument.Range(Start:=0, End:=10)
rngDoc.Bold = True
End Sub
When you need to refer to a Range object multiple times, you can use the Set statement to set a variable equal to the Range object. However, if you only need to perform a single action on a Range object, there’s no need to store the object in a variable. The same results can be achieved using just one instruction that identifies the range and changes the Bold
property.
Sub BoldRange()
ActiveDocument.Range(Start:=0, End:=10).Bold = True
End Sub
Like a bookmark, a range can span a group of characters or mark a location in a document. The Range object in the following example has the same starting and ending points. The range does not include 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 define the beginning and end points of a range using the character position numbers as shown above, or use the Start and End properties with objects such as Selection, Bookmark, or Range. The following example creates a Range object beginning at the start of the second paragraph and ending after 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
The Range property appears on multiple objects, such as Paragraph, Bookmark, and Cell, and 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 have a 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 then centers the selection.
Sub FormatRange()
ActiveDocument.Paragraphs(2).Range.Select
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
End Sub
If you need to apply numerous properties or methods to the same Range object, you can use the With…End With structure. The following example formats the text in the first paragraph of 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
property topic.
Redefining a Range object
Use the SetRange
method to redefine an existing Range object. The following example defines a range as the current selection. The SetRange method then redefines the range so that it refers to current selection plus the next ten 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 SetRange method.
Note When debugging your macros, you can use the Select
method to ensure that a Range object is referring to the correct range of text. For example, the following example selects a Range object, which refers the second and third paragraphs in the active document, and then formats the font of 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
Range
Refers an area in a document to perform actions, like insert text or apply formatting. For example, you may want to write a macro that locates a word or phrase within a portion of a document. The portion of the document can be represented by a Range. After the Range object is identified, methods and properties of the Range object can be applied to modify the contents of the range.
Note: Range object is not as Selection object in Word. There is only one selection per document but Ranges can be multiple.
Create/Add Range
Sub SetNewRange() Dim rngDoc As Range Set rngDoc = ActiveDocument.Range(Start:=0, End:=10) End Sub
Bold property
Sub SetRangeToBold() Dim rngDoc As Range Set rngDoc = ActiveDocument.Range(Start:=0, End:=10) rngDoc.Bold = True End Sub
InsertBefore
Sub InsertTextBeforeRange() Dim rngDoc As Range Set rngDoc = ActiveDocument.Range(Start:=0, End:=0) rngDoc.InsertBefore "Hello " End Sub
Output
Paragraph with Range
Sub GetNewRange() 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
List objects which exposes Range
- Selection
- Document
- Paragraph
- Bookmark
- Cell
Alignment
Sub FormattingRange() ActiveDocument.Paragraphs(2).Range.Select Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter End Sub
SetRange
Sometimes you add or delete contents from your document which are referenced under a Range object. Since Range object is predefined and holding reference before change would not know what has been added or deleted from given range. To fit Range back to amended range Word offers SetRange method by which you can expand or shrink your range object. The SetRange method then redefines the range so that it refers to the current selection plus the next 10 characters.
Code example
Sub ResizeRange() Dim rngParagraph As Range 'Get current range Set rngParagraph = Selection.Range 'Extend range by 10 chars rngParagraph.SetRange Start:=rngParagraph.Start, End:=rngParagraph.End + 10 End Sub
Next>>Working with Tables in Word VBA
Последнее время я часто сталкиваюсь с его использованием. На изученных мною ресурсах, посвященных VBA для Word, почему-то мало внимания уделяется такому важному представителю объектной модели. С его помощью можно, поистине, творить чудеса с документом.
Этот объект гораздо удобнее Selection, потому что позволяет не выделять нужную область на экране, а работать прямо с представлением документа в памяти. Это заметно ускоряет работу макросов, которые, по правде сказать, не отличаются быстродействием. При отладке программ бывает полезно воспользоваться методом Range.Select, чтобы убедиться, что вы работаете с нужным вам диапазоном.
Что же это за объект? Сразу хочу предупредить, что писать я буду, основываясь на своем понимании найденного и прочитанного в других источниках. В дословном переводе Range означает «Диапазон». Применительно к Word — это означает диапазон свойств или методов, доступных для того или иного объекта. Например, как узнать текст второго абзаца в документе? Вот так:
1 | ActiveDocument.Paragraphs(2).Range.Text |
Стоит отметить, что это вернет весь текст в абзаце с символом конца абзаца (¶). Его можно удалить функцией Replace заменив символ vbCr на пустую строку.
Но главная фишка объекта Range совсем не в этом. А в том, что его можно передвигать и изменять в размерах практически произвольно (в пределах документа, естественно). У каждого объекта Range есть два свойства: Range.Start и Range.End. Начальный и конечный символ диапазона, считая от начала документа. Начало и конец диапазона можно задавать, указывая эти свойства напрямую, а можно такой конструкцией:
1 2 | Dim oRng As Range Set oRng = ActiveDocument.Range(20, 50) |
Изменить размер уже существующего диапазона можно с помощью метода SetRange, в котором указать номер символа, с которого диапазон начинается, и каким заканчивается. Этот метод используется тогда, когда нужно изменить уже существующий диапазон. Этот метод ничего не возвращает, а работает со своим родительским объектом
1 2 3 | Dim oRng As Range Set oRng = ActiveDocument.Range oRng.SetRange 20, 50 |
С помощью Range можно получить такие объекты документа, для которых не предусмотрено коллекций, как, например, для абзацев (коллекция Paragraphs). Такими «бесхозными» объектами являются строки и страницы. Кто знает другие, пусть напишет.
Как получить страницу из документа со всем ее содержимым? Коллекции Pages не существует, что же делать? Вот здесь и понадобится Range и его метод GoTo
1 2 3 4 5 6 7 8 9 10 11 12 13 | Sub TestGoTo() Dim oRng As Range 'Даем в переменную oRng начало третьей страницы в документе. Set oRng = ThisDocument.Range.GoTo(wdGoToPage, wdGoToNext, , "3") MsgBox "Третья страница начинается с " & oRng.Start & " символа.", 64, "Метод GoTo" 'Расширяем диапазон oRng на всю третью страницу Set oRng = ThisDocument.Range(oRng.Start, oRng.GoToNext(wdGoToPage).Start) MsgBox "На третьей странице находится " & oRng.Paragraphs.Count & " абзацев.", 64, "Метод GoTo" 'Берем 10 строку с третьей страницы Set oRng = oRng.GoTo(wdGoToLine, wdGoToNext, 10) Set oRng = ThisDocument.Range(oRng.Start, oRng.GoToNext(wdGoToLine).Start) MsgBox "В десятой строке третьей страницы содержится " & oRng.Characters.Count & " символов.", 64, "Метод GoTo" End Sub |
Таким образом можно, например, сохранить каждую страницу документа в файл. На одном форуме я выкладывал пример такого макроса, нашлись даже добровольцы, которые довели его почти до совершенства.
2006 г. Word и его объекты
|