Текущая страница word vba

Задача оказалась не так тривиальна как кажется Прошу помощи
В вопросе определения текущего номера страницы все зависит от цели:

1. Если нужно определить номер станицы чисто для «себя», то есть для использования внутри своей программы, чтобы просто ориентироваться по тексту, то это да

Visual Basic
1
2
3
4
Sub Макрос1()
 MsgBox Selection.Information(wdActiveEndPageNumber)  'это номер с начала документа
 MsgBox Selection.Information(wdActiveEndAdjustedPageNumber) 'это номер по установленной нумерации страниц
End Sub

2. Если нужно же определить номер страницы текущего текста в окончательном документе, например в распечатанном документе (или например в сохраненным в pdf), то это уже совершенно другая задача.
Хитрость здесь в том, что предыдущий макрос возвращает номер страницы в текущем режиме просмотра документа (обычно это «разметка») и это номер может не совпасть с реальным номером страницы уже распечатанного документа, потому что включены просмотры кодов полей или в документе установлен предметный указатель и по всему документу идет разметка этих слов, которые занимают место на экране и сдвигают текст вниз.
Таким образом следующий макрос для некоторых строк вернет другие значения:

Visual Basic
1
2
3
4
5
6
Sub Макрос2()
 Application.PrintPreview = True
 MsgBox Selection.Information(wdActiveEndPageNumber)
 MsgBox Selection.Information(wdActiveEndAdjustedPageNumber)
 Application.PrintPreview = False
End Sub

Вопрос: Как получить реальный номер страницы?
То есть у меня стоит задача найти по тексту абзацы с некоторыми словами и сохранить в отдельном файле со ссылками на страницы. В документе есть предметный указатель со множеством слов и коды отображаются по всему тексту типа «опасные грузы { XE «опасные грузы»} -это вещества…» из-за которых и происходит смещение страниц.
Есть ли другое решение? нежели переключать режим на предпросмотр — это же будет моргать окна при выполнении.

во вложении пример документа — попробуйте определить номер станицы последней строки этими двумя макросами
Документ предоставлен КонсультантПлюс2.docx

Алексей задал вопрос:

Как программно определить номер текущей страницы? Единственное, до чего я додумался — по проценту скробара. Но правильно ли это?

В VBA есть две константы, по которым можно определить номер текущей страницы:

  • wdActiveEndPageNumber
  • wdActiveEndAdjustedPageNumber

Первая константа wdActiveEndPageNumber используется тогда, когда в документе нумерация начинается с первого номера (нормальная нумерация), а вторая — wdActiveEndAdjustedPageNumber — если пользователь использует свою нумерацию документа (не с первого по порядку листа документа).

Как я полагаю, в случае Алексея нужно узнать номер текущей страницы, на которой находится курсор ввода и нумерация страниц правильная. Вот примерный код:

Sub currentPage()
Dim pn As String
pn = Selection.Information(wdActiveEndPageNumber)
MsgBox pn
End Sub

Word VBA, Get Current Page Number

Aug 21, 2015 in VBA for Word

Using the code below you can get the current page number the cursor is on:

Sub main()
Dim intCurrentLine As Integer
intCurrentLine = _
    Selection.Range.Information(wdActiveEndPageNumber)
MsgBox (intCurrentLine)
End Sub

In the figure below the cursor is located at page 10:

Word VBA, Current Page Number

Result after running the code:

Word VBA, Current Page Number, Result

See also:

  • Word VBA, Get Current Line Number
  • Word VBA, End of File

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

(Note: See below for solution.)

I have been trying to retrieve the page numbers from pages that various headings reside on in a word document using VBA. My current code returns either 2 or 3, and not the correctly associated page numbers, depending on where and how I use it in my main Sub.

astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading)

For Each hds In astrHeadings
        docSource.Activate
        With Selection.Find
            .Text = Trim$(hds)
            .Forward = True
            MsgBox hds & ":" & Selection.Information(wdActiveEndPageNumber), vbOKOnly
        End With
        Selection.Find.Execute
Next

docSource is a test document I have set up with 10 headings over 3 pages. I have the headings retrieved from the getCrossReferenceItems method in use later in my code.

What I am attempting is to loop through the results from the getCrossReferenceItems method and use each them in a Find object on docSource and from this ascertain what page the result is on. The page numbers will then be used in a string later in my code. This string plus page number will be added to another document which is created at the beginning of my main sub, everything else works a treat but this code segment.

Ideally what I need this segment to do is fill a second array with the associated page numbers from each Find result.

Problems Solved

Thanks Kevin you have been a great help here, I now have exactly what I need from the output of this Sub.

docSource is a test document I have set up with 10 headings over 3 pages.
docOutline is a new document which will act as a Table of Contents document.

I have had to use this Sub over Word’s built-in TOC features because:

  1. I have multiple documents to include, I could use the RD field to include these but

  2. I have another Sub which generates custom decimal page numbering in each document 0.0.0 (chapter.section.page representative) that, for the whole document package to make sense, need to be included in the TOC as page numbers. There probably is another way of doing this but I came up blank with Word’s built-in features.

This will become a Function to be included in my page numbering Sub. I am currently 3/4 of the way to completing this little project, the last quarter should be straightforward.

Revised and cleaned final Code

Public Sub CreateOutline()
' from http://stackoverflow.com/questions/274814/getting-the-headings-from-a-word-document
    Dim docOutline As Word.Document
    Dim docSource As Word.Document
    Dim rng As Word.Range
    Dim strFootNum() As Integer
    Dim astrHeadings As Variant
    Dim strText As String
    Dim intLevel As Integer
    Dim intItem As Integer
    Dim minLevel As Integer
    Dim tabStops As Variant

    Set docSource = ActiveDocument
    Set docOutline = Documents.Add

    minLevel = 5  'levels above this value won't be copied.

    ' Content returns only the
    ' main body of the document, not
    ' the headers and footer.
    Set rng = docOutline.Content
    astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading)

    docSource.Select
    ReDim strFootNum(0 To UBound(astrHeadings))
    For i = 1 To UBound(astrHeadings)
        With Selection.Find
            .Text = Trim(astrHeadings(i))
            .Wrap = wdFindContinue
        End With

        If Selection.Find.Execute = True Then
            strFootNum(i) = Selection.Information(wdActiveEndPageNumber)
        Else
            MsgBox "No selection found", vbOKOnly
        End If
        Selection.Move
    Next

    docOutline.Select

    With Selection.Paragraphs.tabStops
        '.Add Position:=InchesToPoints(2), Alignment:=wdAlignTabLeft
        .Add Position:=InchesToPoints(6), Alignment:=wdAlignTabRight, Leader:=wdTabLeaderDots
    End With

    For intItem = LBound(astrHeadings) To UBound(astrHeadings)
        ' Get the text and the level.
        ' strText = Trim$(astrHeadings(intItem))
        intLevel = GetLevel(CStr(astrHeadings(intItem)))
        ' Test which heading is selected and indent accordingly
        If intLevel <= minLevel Then
                If intLevel = "1" Then
                    strText = " " & Trim$(astrHeadings(intItem)) & vbTab & "1" & "." & "2" & "." & strFootNum(intItem) & vbCr
                End If
                If intLevel = "2" Then
                    strText = "   " & Trim$(astrHeadings(intItem)) & vbTab & "1" & "." & "2" & "." & strFootNum(intItem) & vbCr
                End If
                If intLevel = "3" Then
                    strText = "      " & Trim$(astrHeadings(intItem)) & vbTab & "1" & "." & "2" & "." & strFootNum(intItem) & vbCr
                End If
                If intLevel = "4" Then
                    strText = "         " & Trim$(astrHeadings(intItem)) & vbTab & "1" & "." & "2" & "." & strFootNum(intItem) & vbCr
                End If
                If intLevel = "5" Then
                    strText = "            " & Trim$(astrHeadings(intItem)) & vbTab & "1" & "." & "2" & "." & strFootNum(intItem) & vbCr
                End If
            ' Add the text to the document.
            rng.InsertAfter strText & vbLf
            docOutline.SelectAllEditableRanges
            ' tab stop to set at 15.24 cm
            'With Selection.Paragraphs.tabStops
            '    .Add Position:=InchesToPoints(6), _
            '    Leader:=wdTabLeaderDots, Alignment:=wdAlignTabRight
            '    .Add Position:=InchesToPoints(2), Alignment:=wdAlignTabCenter
            'End With
            rng.Collapse wdCollapseEnd
        End If
    Next intItem
End Sub

Private Function GetLevel(strItem As String) As Integer
    ' from http://stackoverflow.com/questions/274814/getting-the-headings-from-a-word-document
    ' Return the heading level of a header from the
    ' array returned by Word.

    ' The number of leading spaces indicates the
    ' outline level (2 spaces per level: H1 has
    ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.

    Dim strTemp As String
    Dim strOriginal As String
    Dim intDiff As Integer

    ' Get rid of all trailing spaces.
    strOriginal = RTrim$(strItem)

    ' Trim leading spaces, and then compare with
    ' the original.
    strTemp = LTrim$(strOriginal)

    ' Subtract to find the number of
    ' leading spaces in the original string.
    intDiff = Len(strOriginal) - Len(strTemp)
    GetLevel = (intDiff / 2) + 1
End Function

This code is now producing (What it should be according to my headings specification found in test-doc.docx):

This is heading one                  1.2.1
  This is heading two                1.2.1
    This is heading two.one          1.2.1
    This is heading two.three        1.2.1
This is heading one.two              1.2.2
     This is heading three           1.2.2
        This is heading four         1.2.2
           This is heading five      1.2.2
           This is heading five.one  1.2.3
           This is heading five.two  1.2.3

In Addition to this I have solved the ActiveDocument switching issue by using docSource.select and docOutline.Select statements instead of using.Active.

Thanks again Kevin, greatly appreciated :-)

Phil

dimonbk
Начинающий
Начинающий
 
Сообщения: 23
Зарегистрирован: 03.01.2006 (Вт) 14:57

Как определить номер текущей страницы в Word документе

Подскажите как присвоить переменной номер текущей страницы программно?

Все будет хорошо


GSerg
Шаман
Шаман
 
Сообщения: 14286
Зарегистрирован: 14.12.2002 (Сб) 5:25
Откуда: Магадан

Сообщение GSerg » 03.01.2006 (Вт) 15:21

«При помощи оператора =» — так и хочется мне ответить на этот корявый вопрос…

Для начала уточним.

Какую страницу считать текущей, если выделен фрагмент текста, занимающий несколько страниц?

Как только вы переберёте все варианты решения и не найдёте нужного, тут же обнаружится решение, простое и очевидное для всех, кроме вас


dimonbk
Начинающий
Начинающий
 
Сообщения: 23
Зарегистрирован: 03.01.2006 (Вт) 14:57

Сообщение dimonbk » 03.01.2006 (Вт) 18:05

Я немного некорректно задал вопрос. Как присваивать значения я знаю, я не знаю как определить номер текущей страницы, т.е. страницы, в которой находится курсор. Заранее спасибо!

Все будет хорошо


GSerg
Шаман
Шаман
 
Сообщения: 14286
Зарегистрирован: 14.12.2002 (Сб) 5:25
Откуда: Магадан

Сообщение GSerg » 03.01.2006 (Вт) 19:26

= selection.information(wdActiveEndPageNumber)

Как только вы переберёте все варианты решения и не найдёте нужного, тут же обнаружится решение, простое и очевидное для всех, кроме вас


dimonbk
Начинающий
Начинающий
 
Сообщения: 23
Зарегистрирован: 03.01.2006 (Вт) 14:57

Сообщение dimonbk » 04.01.2006 (Ср) 2:21

Спасибо GSerq!

Все будет хорошо



Вернуться в VBA

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 0

Формулировка задачи:

Всем доброго времени суток.
Подскажите, как определить номер текущей страницы в документе MSWord 2003

Код к задаче: «Как определить номер текущей страницы документа»

textual

MsgBox Selection.Information(wdActiveEndPageNumber)

Полезно ли:

11   голосов , оценка 4.455 из 5

Для большинства операций в документе Word вы обнаружите, что операция выбора выполняется чаще. Вы можете легко выбрать слово, абзацы, но если вам нужно выделить всю текущую страницу, на которой находится курсор, из длинного документа, как вы можете сделать, чтобы повысить эффективность выбора? Это руководство познакомит вас с некоторыми способами выбора текущей страницы.

Выбрать текущую страницу вручную в Word

Выбрать текущую страницу по закладке в Word

Выберите текущую страницу с помощью VBA

Выберите текущую страницу с помощью Kutools for Word


стрелка синий правый пузырь Выбрать текущую страницу вручную в Word

Удивительный! Используйте эффективные вкладки в Word (Office), например Chrome, Firefox и New Internet Explorer!

Подробнее Скачать бесплатно

Есть два простых способа выбрать текущую страницу вручную.

Метод 1: Щелкните левой кнопкой мыши в начале страницы и перетащите курсор в конец страницы, чтобы выбрать текущую страницу.

Метод 2: Щелкните в начале первого символа на текущей странице. Тогда держи Shift и щелкните в конце содержимого на текущей странице.


стрелка синий правый пузырь Выбрать текущую страницу по закладке в Word

1. Поместите курсор на страницу, которую хотите выбрать.

2. Нажмите Вставить > закладка применять закладка Диалог.

3. Когда закладка появится диалоговое окно, введите в поле « page» и нажмите Перейти к, то он автоматически выберет текущую страницу, на которой находится курсор. Смотрите скриншот:


стрелка синий правый пузырь Выберите текущую страницу с помощью VBA

1: Нажмите Alt + F11 для открытия Microsoft Visual Basic для приложений окно;

2: нажмите Модули от Вставить вкладку, скопируйте и вставьте следующий код VBA в Модули окно;

3: нажмите Run  или нажмите F5 применить VBA.

Код VBA при выборе текущей страницы:

Sub selectcurrentpage ()
ActiveDocument.Bookmarks (» page»). Range.Select
End Sub


стрелка синий правый пузырь Выберите текущую страницу с помощью Kutools for Word

Kutools for Word‘s Выбрать текущую страницу Утилита может быстро выбрать текущую страницу.

Kutools for Word, удобная надстройка, включает группы инструментов, облегчающих вашу работу и расширяющих ваши возможности обработки текстовых документов. Бесплатная пробная версия на 45 дней! Get It Now!

1. Установите курсор на страницу, которую вы хотите выбрать в качестве текущей.

2. Затем примените эту утилиту, нажав Кутулс > Разделы > Выбрать текущую страницу, см. снимок экрана:

3. После нажатия Выбрать текущую страницу, выбирается страница, на которой находится курсор.

Щелкните здесь, чтобы узнать больше о выборе текущей страницы.


Относительные статьи:

  • Выбрать определенные страницы в Word
  • Выберите диапазон страниц в Word


Рекомендуемые инструменты для повышения производительности Word

выстрел kutools word kutools tab 1180x121

выстрел kutools word kutools plus tab 1180x120

Kutools For Word — Более 100 расширенных функций для Word, сэкономьте 50% времени

  • Сложные и повторяющиеся операции можно производить разово за секунды.
  • Вставляйте сразу несколько изображений из папок в документ Word.
  • Объединяйте и объединяйте несколько файлов Word из папок в одну в желаемом порядке.
  • Разделите текущий документ на отдельные документы в соответствии с заголовком, разрывом раздела или другими критериями.
  • Преобразование файлов между Doc и Docx, Docx и PDF, набор инструментов для общих преобразований и выбора и т. Д.

Комментарии (0)


Оценок пока нет. Оцените первым!

Ty Anderson

Posted on Wednesday, August 7th, 2013 at 7:32 am by .

Microsoft Word is about the authoring of documents. Documents contain pages, paragraphs, sentences and more. Today, I want to wade into the waters of manipulating Word document content. The plan is to get your feet wet by providing an overview of the key objects along with code samples.

Continuing the fine tradition of all Office applications (OneNote being the exception), Word has an extensive and mature object model. My goal is to show “a way” to accomplish some tasks in Microsoft Word. These samples are not necessarily, “the way” to do it. There is more than one way to achieve the same results.

Today, we are concerned with the structure of a Word document… not its stylings and presentation (I’ll concern ourselves with that topic next).

  • Word document content objects
  • Accessing document content objects with code
  • Working with familiar Word content objects

Document content objects

Let’s look at the objects that combine together to construct a Word document.

  • Document :: The document represents a single, solitary Word document. This is the parent object for all content within a Word document file. It lives in an appropriately named collection called Documents. I covered the document object in a previous article – Word application and base objects.
  • Section :: Documents can contain multiple sections. This is how you apply different formatting, layout, and header/footer options to a Word document… by creating sections and formatting them differently.
  • Page :: Represents a single page within a document. A page can reside within a Range.
  • Paragraph :: A single paragraph of content. A paragraph can reside within a Selection, Document, or Range and is accessible via the Paragraphs collection object. Paragraphs also contain the formatting for content residing above it. Don’t ponder over that last sentence too much, I will explain it further in my next article.
  • Sentence :: This object does not exist… strange as that might seem. Instead, there is the Paragraphs collection object. This collection contains a collection of Range objects, which in turn, contain all the sentences for the Range. Confused? The code samples will help bring focus to the picture.
  • Selection :: This object contains the content selected either by the user or via code. It also is the insertion point if no selection exists. The insertion point is where the cursor blinks in the Word UI to inform the user of their location within the document.
  • Range :: Think of this object like real-estate. It contains a contiguous section of a document. Perhaps its two most popular properties are Start and End. They contain ranges starting and ending character positions within the Word document.

There are more “content” objects than these but the list above are the major objects that provide access to everything else.

Accessing Word document content objects with code

I want to give you a lot of VB.NET code samples today. I’ll start with the Range object and keep going as long as I have paper. By the end of the samples, my hope is you will have a general idea of how to access and edit content within a Word document.

The Range object

The Word object model is extensive and more than a little complex. The best way to figure out how to make things happen via code is to learn to think like Word thinks. The quickest way to achieve this goal is to master the Range and the Selection objects. I covered the selection object in this article so I will focus on the Range object. Just know that together, these two objects allow you to select and find Word content.

Enumerate paragraphs in a range

This method loops through all the paragraphs in the active document and reverses their order in a new document.

Private Sub EnumerateParagraphs()
    Dim curDoc As Word.Document = WordApp.ActiveDocument
    Dim newDoc As Word.Document
    Dim rng As Word.Range
    Dim str As String = ""
    Dim i As Integer
 
    rng = curDoc.Content
    i = rng.Paragraphs.Count()
 
    Do Until i = 0
        str = str & rng.Paragraphs.Item(i).Range.Text & vbCrLf
        i = i - 1
    Loop
 
    newDoc = WordApp.Documents.Add
    newDoc.Range().Text = str
 
    Marshal.ReleaseComObject(rng)
    Marshal.ReleaseComObject(curDoc)
    Marshal.ReleaseComObject(newDoc)

The key is the use of the Range object and all the document content. The code first grabs all the document content and assigns it to a Range variable (rng). Then the code finds out how many paragraphs exist and loops backwards to create a string. This string is then inserted into a new document. It’s a good bar trick that only works in nerd bars.

Select the current page range

In this sample, we use a Range object that’s buried deeper in the Word object model. The reason for this sample is that I want to point out that the Range object is darn near everywhere within Word.

Private Sub SelectedPageRange()
    Dim curDoc As Word.Document
    curDoc = WordApp.ActiveDocument
 
    curDoc.Bookmarks("page").Range.Select()
 
    Marshal.ReleaseComObject(curDoc)
 
End Sub

In this procedure, I employ the predefined “page” bookmark. This is a standard Word bookmark that always exists and allows easy selection of the page containing the current focus (or selection).

You can learn more about predefined bookmarks at MSDN.

Enumerate sentences in a range

This one is similar to paragraphs but we switch sentences for paragraphs. The idea is the same… create a new document that contains the sentences in reverse order.

Private Sub EnumerateSentences()
    Dim curDoc As Word.Document = WordApp.ActiveDocument
    Dim newDoc As Word.Document
    Dim rng As Word.Range
    Dim str As String = ""
    Dim i As Integer
 
    rng = curDoc.Content
    i = rng.Sentences.Count()
 
    Do Until i = 0
        str = str & rng.Sentences.Item(i).Text
        i = i - 1
    Loop
 
    newDoc = WordApp.Documents.Add
    newDoc.Range().Text = str.ToUpper
 
    Marshal.ReleaseComObject(rng)
    Marshal.ReleaseComObject(curDoc)
    Marshal.ReleaseComObject(newDoc)
End Sub

To mix it up, the final document’s text is upper case. I know, this is dazzling trickery.

The takeaway is that the Range object contains a section of the Word document. Within it are major items like paragraphs and sentences.

The Section object

Documents can contain multiple sections. Sections allow you to define different page layouts and header/footer schemes.

Enumerate sections

You can loop through document sections by accessing the Sections collection. This collection resides directly beneath the Document object.

Private Sub EnumerateSections()
    Dim curDoc As Word.Document
    Dim newDoc As Word.Document
    Dim str As String = ""
    Dim i As Integer
 
    curDoc = WordApp.ActiveDocument
 
    For i = 1 To curDoc.Sections.Count
        str = str & "SECTION " & i & vbCr
        str = str & vbTab & "start = " & curDoc.Sections(i).Range.Start
        str = str & vbTab & "end = " & curDoc.Sections(i).Range.End & vbCrLf
    Next
 
    newDoc = WordApp.Documents.Add
    newDoc.Range().Text = str
 
    Marshal.ReleaseComObject(curDoc)
    Marshal.ReleaseComObject(newDoc)
End Sub

This procedure builds a string that 1) lists each document section and 2) contains the section’s Start and End character position. Notice the use of the Range object to read this information.

Create a new section

When building Word documents via code, you will likely need to create a new section. This procedure will do the trick.

Private Sub CreateSection()
    Dim curDoc As Word.Document
    curDoc = WordApp.ActiveDocument
 
    curDoc.Sections.Add(WordApp.Selection.Range)
 
    Marshal.ReleaseComObject(curDoc)
End Sub

This sample inserts a section break at the current selection (or cursor) location. Again, notice the use of the Range property. You can easily grab a different range within the document and pass it as the location of the page break.

The Page object

The page object resides in a “funny” location. Not “ha ha” funny… more like “why the hell is it here?” funny. You access document pages via the Document.ActiveWindow.Panes collection. Why? Because these are the rules.

Enumerate pages

Someday you might want to loop through all document pages and perform some very specific business logic on them. This code does exactly that.

Private Sub EnumeratePages()
    Dim curDoc As Word.Document
    Dim newDoc As Word.Document
    Dim pgs As Word.Pages
    Dim str As String = ""
    Dim i As Integer
 
    curDoc = WordApp.ActiveDocument
    pgs = curDoc.ActiveWindow.Panes(1).Pages
 
    For i = 1 To pgs.Count
        str = "PAGE " & i & vbCr
        str = str & vbTab & "height = " & pgs.Item(i).Height
        str = str & vbTab & "width = " & pgs.Item(i).Width & vbCrLf
    Next
 
    newDoc = WordApp.Documents.Add
    newDoc.Range().Text = str
 
    Marshal.ReleaseComObject(pgs)
    Marshal.ReleaseComObject(curDoc)
    Marshal.ReleaseComObject(newDoc)
End Sub

Here, the business logic is to create a string that contains the height and width of each page and then display it in a new document. Your business logic will probably be more complex than this. Consider this procedure a starter kit for processing document pages.

Insert a page break

To create a page, you create a page break.

Private Sub InsertPageBreak()
    Dim sel As Word.Selection
    sel = WordApp.Selection
 
    sel.InsertBreak(Type:=Word.WdBreakType.wdPageBreak)
 
    Marshal.ReleaseComObject(sel)
End Sub

I start by referencing the current insertion point via the Selection object. I then invoke the InsertBreak method and specify a page break. Walla! We have a new page.

Working with familiar (some) Word content objects

Now that you know the basics of working with the Range, Section, and Page objects, let’s look at working with typical Word content like tabless, comments, & text.

Insert a table

I use tables all the time. I can see how it would be useful to have a procedure that inserts a table exactly how I like it.

Private Sub InsertTable(rowCount As Integer, columnCount As Integer)
    Dim curDoc As Word.Document = WordApp.ActiveDocument
    Dim table As Word.Table
 
    table = curDoc.Tables.Add(WordApp.Selection.Range, rowCount, columnCount)
    table.Cell(1, 1).Range.Text = "Hello Table"
 
    Marshal.ReleaseComObject(table)
    Marshal.ReleaseComObject(curDoc)
End Sub

In this case, I like a table with 1 column and 7 rows and 0 formatting. The Tables collection resides under the Document object. To add a new table, you call the collection’s Add method and specify its location (via a Range object), number of rows, and number of columns.

Enumerate comments

Authoring a quality document of any type (blog, article, report, proposal, etc.) is a collaborative effort. Comments are key to the collaborative process. If you receive your document after this process and it is littered with helpful comments for improving it… the following code will come in handy.

Private Sub EnumerateComments()
    Dim curDoc As Word.Document = WordApp.ActiveDocument
 
    For i = 1 To curDoc.Comments.Count
        curDoc.Comments.Item(i).Range.Text = _
            curDoc.Comments.Item(i).Range.Text & vbCrLf & _
            "Corrected. It's all good now!"
    Next
 
    Marshal.ReleaseComObject(curDoc)
End Sub

Here, I loop through the Comments collection. This collection also resides directly under the Document object. For each comment, I insert a comment below the existing comment text.

Create a comment

Creating a comment is straight-forward. The approach below utilizes the current selection’s range as the insertion point.

Private Sub CreateComment(commentText As String)
    WordApp.Selection.Comments.Add(WordApp.Selection.Range, commentText)
End Sub

The text for the comment needs to be passed as the procedure’s parameter.

You can also create comments by calling Document.Comments.Add. If you do that, you need to pass a Range to specify where to insert the comment.

Delete all comments

Deleting all comments is delightfully easy. There is a method that takes care of them.

Private Sub DeleteComments()
    Dim curDoc As Word.Document = WordApp.ActiveDocument
 
    curDoc.DeleteAllComments()
 
    Marshal.ReleaseComObject(curDoc)
End Sub

There is no need to loop through the Comments collection.

Insert text

To insert text, you can utilize the Selection and Range objects.

Private Sub InsertText(textToInsert As String)
    WordApp.Selection.InsertAfter(textToInsert)
    'WordApp.Selection.InsertBefore(textToInsert)
    'WordApp.ActiveDocument.Range.InsertAfter(textToInsert)
End Sub

In this sample, I utilize the current selection to insert the passed string after the current selection. I’ve include commented code to show how you can chose to InsertBefore. Also, I’ve shown how to do the same with the Range object.

Find text

Finding text is a core competency in Word solution development. This sample performs search and replace.

Private Sub FindText()
    Dim rng As Word.Range
    rng = WordApp.ActiveDocument.Content
 
    With rng.Find
        .ClearFormatting()
        .Execute(FindText:="Hello Table", _
                 ReplaceWith:="Found Table", _
                 Replace:=Word.WdReplace.wdReplaceAll)
    End With
 
    Marshal.ReleaseComObject(rng)
End Sub

The procedure sets a Range object that contains all document Content. It then executes a Find & Replace action to replace the text inserted in the InsertTable method from earlier.

Copy and paste text

If you have text in a Word document, you will need to move it around.

Private Sub CopyAndPasteText()
    Dim curDoc As Word.Document = WordApp.ActiveDocument
    Dim rng As Word.Range
    'Dim sel As Word.Selection
    rng = curDoc.Range(curDoc.Paragraphs(1).Range.Start, _
                       curDoc.Paragraphs(3).Range.End)
    rng.Copy()
    'sel = curDoc.Range(curDoc.Paragraphs(1).Range, _
    '                    curDoc.Paragraphs(3).Range.End)
    'sel.Copy()

    WordApp.Selection.GoTo(What:=Word.WdGoToItem.wdGoToBookmark, _
                           Name:="EndOfDoc")
    WordApp.Selection.Paste()
 
    Marshal.ReleaseComObject(rng)
    Marshal.ReleaseComObject(curDoc)
End Sub

This method stores the first 3 paragraphs in a Range object, copies them, moves to the end of the document, and pastes the paragraphs. I’ve included commented code that shows how you could perform the copy using a Selection object.

***

We have now delved into the waters of Word document content manipulation. We’ll continue looking at scenarios in future articles!

Available downloads:

This sample Word add-in was developed using Add-in Express for Office and .net:

VB.NET Word Document Content add-in

Word add-in development in Visual Studio for beginners:

  • Part 1: Word add-in development – Application and base objects
  • Part 2: Customizing Word UI – What is and isn’t customizable
  • Part 3: Customizing Word main menu, context menus and Backstage view
  • Part 4: Creating custom Word ribbons and toolbars: VB.NET, C#
  • Part 5: Building custom task panes for Word 2013 – 2003
  • Part 6: Working with Word document content objects
  • Part 8: Working with multiple Microsoft Word documents
  • Part 9: Using custom XML parts in Word add-ins
  • Part 10: Working with Word document properties, bookmarks, content controls and quick parts
  • Part 11: Populating Word documents with data from external sources
  • Part 12: Working with Microsoft Word templates

Понравилась статья? Поделить с друзьями:
  • Текущая стоимость в excel это
  • Текущая стоимость аннуитета формула excel
  • Текущая приведенная стоимость excel
  • Текущая дата на листе excel
  • Текущая дата в excel это