Vba word range information

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Range.Information property (Word)

vbawd10.chm157155641

vbawd10.chm157155641

word

Word.Range.Information

967e9a22-5f98-e4bd-557c-7367cb7c5d2b

06/08/2017

medium

Range.Information property (Word)

Returns information about the specified range. Read-only Variant.

Syntax

expression. Information( Type )

expression Required. A variable that represents a Range object.

Parameters

Name Required/Optional Data type Description
Type Required wdInformation The information type.

Example

If the tenth word is in a table, this example selects the table.

If ActiveDocument.Words(10).Information(wdWithInTable) Then _ 
 ActiveDocument.Words(10).Tables(1).Select

[!includeSupport and feedback]

Microsoft Word Information Property VBA, C#, Vb.Net example

Information

a widely used property to determine selection type information within a Selection or a Range. Followings are the constants derived from WdInformation enum which can be validated with Information property:

  • wdActiveEndAdjustedPageNumber: It returns the number of the page that contains active boundary of the given selection or range in a document. Can be represented using 1
  • wdActiveEndPageNumber: It returns the number of the page that contains the active boundary of the given selection or range in a document, counting from the beginning of the document. Can be represented using 3
  • wdActiveEndSectionNumber: It returns the number of the section that contains the active boundary of the given selection or range in a document. Can be represented using 2
  • wdAtEndOfRowMarker: it returns boolean True if the specified selection or range is at the end of row in a table. Can be represented using 2
  • wdCapsLock: it returns boolean True if Caps Lock button of keyboard is ON. Can be represented using 21
  • wdEndOfRangeColumnNumber: It returns column number of a table that contains the end of the given selection or range in a document. Can be represented using 17
  • wdEndOfRangeRowNumber: It returns row number of a table that contains the end of the given selection or range. It can be represented using 14
  • wdFirstCharacterColumnNumber: It returns position of the character in the given selection or range. Can be represented using 9
  • wdFirstCharacterLineNumber: It returns position of first character in the given selection or range in a document. Can be represented using 10
  • wdFrameIsSelected: It returns a boolean True if the selection or range is made to full frame or text box. Can be represented using 11
  • wdHeaderFooterType: It returns header or footer type value that contains the given selection or range. Can be represented using 33
  • wdHorizontalPositionRelativeToPage: It returns horizontal position of the given selection or range. Can be represented using 5
  • wdHorizontalPositionRelativeToTextBoundary: It returns relative horizontal position of the given selection or range which is close to left edge of the closest text boundary enclosing it. Can be represented using 7
  • wdInBibliography: It returns a boolean True if the given selection or range is in a bibliography. Can be represented using 42
  • wdInCitation: It returns a boolean True if given selection or range is in a citation. Can be represented using 43
  • wdInClipboard: It reference to clipboard object. Can be represented using 38
  • wdInCommentPane: It returns a boolean True if given selection or range is in a comment pane area. Can be represented using 26
  • wdInContentControl: It returns a boolean True if given selection or range is within content control. Can be represented using 46
  • wdInCoverPage: it returns a boolean True if given selection or range is on the cover page of the document. Can be represented using 41
  • wdInEndnote: It returns a boolean True if given selection or range is in an endnote area section in a document. Can be represented using 36
  • wdInFieldCode: It returns a boolean True if given selection or range is in a field. Can be represented using 44
  • wdInFieldResult: it returns a boolean True if given selection or range is in a field result section. Can be represented using 45
  • wdInFootnote: it returns a boolean True if given selection or range is in a Footnote area section of a document. Can be represented using 45
  • wdInFootnoteEndnotePane: It returns a boolean True if given selection or range is in the footnote or EndNote Pane. Can be represented using 25
  • wdInHeaderFooter: It returns a boolean True if the selection or range is in the header or footer pane or in a header or footer section. Can be represented using 28
  • wdInMasterDocument: It returns a boolean True if the selection or range is in a master document means document should contain at least one sub-document. Can be represented using 34
  • wdInWordMail: It returns a boolean True if the selection or range is in the Mail section. Can be represented using 37
  • wdMaximumNumberOfColumns: It returns highest column number of a table. Can be represented using 18
  • wdMaximumNumberOfRows: It returns highest row number in a table. Can be represented using 15
  • wdNumberOfPagesInDocument: It returns total number of pages available in a document. Can be represented using 4
  • wdNumLock: It returns boolean True if Number Lock is ON in the keyboard. Can be represented using 22
  • wdReferenceOfType: It returns relation with footnote or endnote. Can be represented using 32
  • wdOverType: It returns boolean True if Overtype mode is ON. Can be represented using 23
  • wdRevisionMarking: It check if track revision in the document is in effect or not. Can be represented using 24
  • wdSelectionMode: It can be used to track current selection mode in a document. Can be represented using 20
  • wdStartOfRangeColumnNumber: It returns the column number of a table that contains in the starting of the selection or range. Can be represented using 16
  • wdStartOfRangeRowNumber: It returns the row number of a table that contains in the starting of the selection or range. Can be represented using 13
  • wdVerticalPositionRelativeToPage: It returns relative vertical position of the selection or range. Can be represented using 6
  • wdVerticalPositionRelativeToTextBoundary: It returns relative vertical position of the selection or range. Can be represented using 8
  • wdWithInTable: It returns a boolean True if the selection is within table. Can be represented using 12
  • wdZoomPercentage: It returns the current percentage of magnification in the document. Can be represented using 19

VBA Selection within table

Public Function CheckSelectionIsTable() As Boolean
    'Declare variable to bind selection
    Dim oSelection As Selection
    'Bind Selection
    Set oSelection = Selection
    If Selection.Information(wdWithInTable) = True Then
        MsgBox "Selection is in Table"
    Else
        MsgBox "Not a table"
    End If
End Function

VBA Number of rows in a table:

Public Function CheckTotalNumberOfRowsInTable() As Boolean
    'Declare variable to bind selection
    Dim oSelection As Selection
    'Bind Selection
    Set oSelection = Selection
    If Selection.Information(wdWithInTable) = True Then
        MsgBox Selection.Information(wdMaximumNumberOfRows)
    Else
        MsgBox "No table to perform action"
    End If
End Function

Output

C# Selection within Table:

private void btnCheckTableSelection_Click(object sender, RibbonControlEventArgs e)
{            
    //Bind selection object
    wordApp.Selection oSelection = Globals.ThisAddIn.Application.Selection;

    //Check if selection within table
    if (Convert.ToBoolean(oSelection.Information[wordApp.WdInformation.wdWithInTable])==true)
    {
        MessageBox.Show("Selection is in Table");
    }
    else
    {
        MessageBox.Show("Selection not in a table");
    }
}

C# Number of rows in a Table

private void btnShowTotalRows_Click(object sender, RibbonControlEventArgs e)
{            
    //Bind selection object
    wordApp.Selection oSelection = Globals.ThisAddIn.Application.Selection;

    if (Convert.ToBoolean(oSelection.Information[wordApp.WdInformation.wdWithInTable])==true)
    {
        MessageBox.Show(Convert.ToInt32(oSelection.Information[wordApp.WdInformation.wdMaximumNumberOfRows]).ToString());
    }
    else
    {
        MessageBox.Show("No table to perform action");
    }
}

VB.Net Selection within table:

Private Sub btnSelectionInTable_Click(sender As Object, e As RibbonControlEventArgs) Handles btnSelectionInTable.Click
    'Declare variable to bind selection
    Dim oSelection As word.Selection
    'Bind Selection
    oSelection = Globals.ThisAddin.Application.Selection
    
    'Check if selection within table
    If oSelection.Information(WdInformation.wdWithInTable) = True Then
        MsgBox "Selection is in Table"
    Else
        MsgBox "Not a table"
    End If
End Sub

VB.Net Number of rows in a table:

Private Sub btnNumberOfRowsInfo_Click(sender As Object, e As RibbonControlEventArgs) Handles btnNumberOfRowsInfo.Click
     'Declare variable to bind selection
    Dim oSelection As word.Selection
    'Bind Selection
    oSelection = Globals.ThisAddin.Application.Selection
    
    'Verify selection in table 
    If oSelection.Information(WdInformation.wdWithInTable) = True Then
        MsgBox oSelection.Information(WdInformation.wdMaximumNumberOfRows)
    Else
        MsgBox "No table to perform action"
    End If
End Sub

Please leave your comments or queries under comment section also please do subscribe to out blogs to keep your self upto date.

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
  

Здравствуйте дорогие читатели блога scriptcoding.ru. Сегодня мы рассмотрим работу с классом Range, который относится к объектном модели Word. Данный класс отвечает за работу с текстом в ворде, а точнее, за его выбор.

В отличии от Selection, Range позволяет не выделить, а выбрать заданный диапазон текста в ворде. Использовать Range более выгодно, чем Selection, так как получить выбор можно только программно, это работает нам на руку, так как пользователь не сможет повлиять на работу макроса или программного кода. Поясню: допустим, мы хотим обработать текст в ворде с помощью объекта Selection, выделив нужный диапазон. Если пользователь во время обработки щелкнет мышью и снимет выделение, то наш макрос потерпит поражение. В случае с Range такой неприятности не произойдет, поэтому и рекомендуется использовать вместо Selection.

Получить доступ к объекту можно несколькими способами:

Одноименный метод объекта Document – данный метод принимает два необязательных параметра, которые задают начальное и конечное значение выбора при работе с текстом в Word. Если вызвать метод без параметров, то будет выбрано содержимое всего документа, например:

' Выбираем весь текст
set oRange = oDoc(1).Range()
'Делаем шрифт жирным
oRange.Bold = true

Или такой вариант:

'Выбираем первые 10 символов
set oRange = oDoc(1).Range(0,10)

Одноименное свойство – данное свойство предусмотрено для большинства классов Word (Bookmark, Selection, Table, Row, Cell, Paragraph и так далее). В данном случае мы получаем Range для заданного класса, автоматически произойдет выбор содержимого данного класса (абзац, выделение, закладка и так далее).

Метод SetRange() – Данный метод предоставляет сам объект Range, и он позволяет переопределить выбор текста в ворде, например:

set oRange1 = oDoc(1).Range()
oRange1.SetRange 1,10
oRange1.Bold = true

Содержание

  1. Класс Range – выбираем текст в ворде
  2. Свойства – работа с текстом в ворде
  3. Методы – работа с текстом в Word

Класс Range – выбираем текст в ворде

Свойства – работа с текстом в ворде

Выбираем текст в ворде

Свойства, которые позволяет задать или получить значение константы:

Case– Регистр текста в ворд, константа WdCharacterCase:

  • wdNextCase — -1 – Как в предложении
  • wdLowerCase — 0 — Нижний регистр
  • wdUpperCase — 1 — Верхний регистр
  • wdTitleWord — 2 – Начало слова с заглавной буквы
  • wdTitleSentence — 4 — в режиме ввода предложения
  • wdToggleCase — 5 – Инвертировать регистр

CharacterWidth — Ширина символов, константа WdCharacterWidth:

  • wdWidthFullWidth — 7 – Полная ширина.
  • wdWidthHalfWidth — 6 – Половина ширины (нормальный режим).

HorizontalInVertical– Расположение текста в ворде, константа WdHorizontalInVerticalType:

  • wdHorizontalInVerticalNone — 0 – Форматирование отсутствует
  • wdHorizontalInVerticalFitInLine — 1 – Горизонтальное направление
  • wdHorizontalInVerticalResizeLine — 2 – Вертикальное направление

Orientation— Направление ворд текста, константа WdTextOrientation:

  • wdTextOrientationHorizontal — 0 – Горизонтально, по умолчанию.
  • wdTextOrientationVerticalFarEast — 1 – Вертикально вниз от верхней части, справа налево.
  • wdTextOrientationUpward — 2 — Вверх под углом.
  • wdTextOrientationDownward — 3 – Вниз под углом.
  • wdTextOrientationHorizontalRotatedFarEast — 4 — Горизонтально, но справа налево (только для языков с данным типом письма).
  • wdTextOrientationVertical — 5 — Вертикально вниз от верхней части, слева направо.

HighlightColorIndex– Цвет выделения текста в ворде, константа WdColorIndex.

LanguageIDOther– Язык текста в ворд, константа, WdLanguageID.

Style– Стиль, константа WdBuiltinStyle.

Underline– Тип подчеркивания, константа WdUnderline.

работаем с текстами в word

Свойства, которые позволяют задать или получить логическое значение:

Bold– Делает шрифт жирным (true).

Italic— Делает шрифт курсивом (true).

GrammarChecked– Проверка грамматики.

LanguageDetected– Определение языка.

работаем с текстами в ворде

Прочие свойства (чтение и запись), только последнее доступно только для чтения.

Startи End– Начальная и конечная позиция для выбора.

FitTextWidth— Ширина текста в текущих единицах измерения.

ID— Имя идентификатора (строковое значение) для указанного диапазона.

Text– Позволяет вставить (в место, где находится курсор), заменить (выбранную область), или получить текст в ворде для заданного диапазона.

Information(type) — Информация об указанном диапазоне (параметр type содержит значение константы WdInformation. Только чтение.

Методы – работа с текстом в Word

обработка текста в ворде

CheckGrammar() — Начинает проверку орфографии и грамматики для указанного диапазона.

Set Range2 = Documents("MyDocument.doc").Sections(2).Range
Range2.CheckGrammar

CheckSynonyms() — Отображает диалоговое окно «Тезаурус«.

Collapse(Direction) — Убирает выделение.

Direction – Дополнительный параметр, который задает направление от позиции курсора. Может быть одним из следующих значений константы WdCollapseDirection: wdCollapseEnd — 0 или wdCollapseStart — 1. Значение по умолчанию wdCollapseStart.

ComputeStatistics(Statistic) – Позволяет получить статистику для заданного выбора. Параметр Statistic содержит значения константы WdStatistic.

Copy(), Delete(), Cut() – Копирование, удаление и вырезание выбранного диапазона.

Paste() – Вставка содержимого буфера обмена.

CopyAsPicture() – Копирование текста в ворде как изображения.

Select() – Выделение текущего выбора.

SetRange(Start, End) – Позволяет задать начальную и конечную позицию для выбора, вернет новый объект Range.

Relocate(Direction) — Переставляет местами абзацы в выбранном диапазоне.

Direction – Обязательный параметр, который задает направление, содержит значение константы WdRelocate:

  • wdRelocateDown — 1 — Ниже следующего видимого абзаца.
  • wdRelocateUp — 0 — Выше предыдущего видимого абзаца.

Методы с префиксом Insert…и Move… и метод ConvertToTable() используются также классом Selection, поэтому я не стал их описывать, просто ознакомьтесь со статьей «Объект Word Selection — выделение фрагмента текста в ворде, методы #1»

Ниже я привел два примера программного кода на языке VBScript и JScript, в них я просто выбираю каждый символ в тексте и задаю для него цвет выделения. Работа с текстами в Word. Причем так, что бы цвета периодически менялись.

Программный код на языке VBSCRIPT:

' ----------------------------------------------------------------------------
' Работа с текстом в ворде
' Выделение разными цветами
' Range1.vbs
' ----------------------------------------------------------------------------
Option Explicit
 
dim oWord, oDoc, oSel, i, oPars, MyText, oRange, j
 
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents
oDoc.Add()
Set oSel = oWord.Selection
Set oPars = oSel.Paragraphs
oWord.Visible = True
 
MyText = "Работа с текстом в Word "
 
' Вставляем текст
For i=0 to 4
   oSel.TypeText MyText & MyText & MyText & MyText & MyText & MyText & MyText
   oSel.TypeParagraph
Next
 
' Создаем ссылку
' Заодно выбираем весь текст в ворде
set oRange = oDoc(1).Range()
i = 1:j = 0
 
' Обрабатываем каждый символ
Do While i <= oRange.End
   With oRange
      ' выбираем один символ
      .SetRange i, i+1
      ' если выбран последний цвет
      if j = 17 then
         j = 0
         ' Меняем цвет выделения
         .HighlightColorIndex = j
         j = j + 1
      else
         .HighlightColorIndex = j
         j = j + 1
      end if
      i = i + 1
   End With
Loop

Программный код на языке JSCRIPT:

// ----------------------------------------------------------------------------
// Работа с текстом в ворде
// Выделение разными цветами
// Range1.js
// ----------------------------------------------------------------------------
 
var oWord1, oDoc1, oSel1, oPars1, MyText1 = "Работа с текстом в Word. ", oRange1;
 
oWord1 = WScript.CreateObject("Word.Application");
oDoc1 = oWord1.Documents;
oDoc1.Add();
oSel1 = oWord1.Selection;
oPars1 = oSel1.Paragraphs;
oWord1.Visible = true;
 
// Вставляем текст
for (i=0; i<=4; i++){
    oSel1.TypeText(MyText1 + MyText1 + MyText1 + MyText1 + MyText1 + MyText1 + MyText1);
    oSel1.TypeParagraph();
}
 
// Создаем ссылку 
// Заодно выбираем весь текст в ворде
oRange1 = oDoc1(1).Range();
 
var i = 1, j = 0;
// Обрабатываем каждый символ
while (i <= oRange1.End){ 
    with(oRange1){
        // выбираем один символ
        SetRange(i, i+1);
        // если выбран последний цвет
        if (j == 17){ 
            j = 0;
            // Меняем цвет выделения
            HighlightColorIndex = j;
            j++;
        }else{
            HighlightColorIndex = j;
            j ++;
        }
        i++
    }
}

Хорошо, с программированием закончили, теперь можно дать некоторые пояснения. И так, оба примера работают с текстом в Word одинаково. Имена переменных практически идентичны, только для JSCRIPT я к имени переменных добавил 1. В самом начале происходит подключение основных классов для доступа к приложению Microsoft Word, создание нового документа — «Коллекция Documents«, делаем документ видимым. Далее в цикле FOR — «Урок 9 по JScript — оператор цикла for» и «Урок 6 по VBScript: Циклы for…next и for each…next» происходит работа с текстом в ворд, а именно – добавление несколько раз содержимого переменной MyText.

результат работы с текстом в ворде

Переменная oRange будет содержать ссылку н6а класс, используя цикл WHILE — «Урок 7 по VBScript: Циклы do…loop и while…wend» и «Урок 10 по JScript: Цикл while и do…while«, мы начинаем обрабатывать каждый символ и менять его цвет, естественно, что количество возможных цветов ограничено. Поэтому нам приходится дополнительно добавить переменные i и j. Ну и все, результат работы можно увидеть на рисунке выше.

Последнее время я часто сталкиваюсь с его использованием. На изученных мною ресурсах, посвященных 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

Таким образом можно, например, сохранить каждую страницу документа в файл. На одном форуме я выкладывал пример такого макроса, нашлись даже добровольцы, которые довели его почти до совершенства.

Понравилась статья? Поделить с друзьями:
  • Vba word print from to
  • Vba word выделить ячейку таблицы
  • Vba word paste table
  • Vba word выделить текст в ячейке
  • Vba word paragraphformat alignment