working with word document content objects - vb

Upload: lucy-figueroa-r

Post on 07-Jul-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/18/2019 Working With Word Document Content Objects - VB

    1/12

    Working with Word document content objectsPosted on Wednesday, August 7th, 2013 at 7:32 am by Ty Anderson.

    Follow Ty Anderson on Google+, Facebook.

    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 allcontent 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

    Recent Posts

    Office 365 API – Querying

    Exchange

    Office 365 API –

    Authentication & Setup

    Maptitude is the ideal

    MapPoint alternative for

    developers

    Office 365 for developers –

    What, How, Where?

    Add‐in Express sim‐ships

    with Visual Studio 2015 and

    Office 2016 Preview

    Categories

    Add‐in Express for Internet

    Explorer

    Add‐in Express for Office

    and .net

    Add‐in Express for Office

    and VCL

    ASP.NET MVC

    Google Apps Development

    HowTo samples

    Office 365 Development

    Office Development

    Outlook Security Manager

    VDProj to WiX Converter

    and WiX Designer

    Video HowTo samples

    List of authors

    Eugene Starostin

    Andrei Smolin

    Eugene Astafiev

    Dmitry Kostochko

    Fokke Post

    Sergey Grischenko

    Renat Tlebaldziyeu

    ADD‐IN EXPRESS BLOG

    COMPANY PRODUCTS SERVICES DOWNLOADS SUPPORT FORUMS LEARNING CENTER BLOG BUY

    searchSIGN IN |   SITEMAP

    http://-/?-https://plus.google.com/u/0/116245886154491887006/http://www.facebook.com/tyranthttps://www.add-in-express.com/support/index.phphttps://www.add-in-express.com/forum/https://www.add-in-express.com/learning-center/index.phphttps://www.add-in-express.com/creating-addins-blog/https://www.add-in-express.com/purchase/index.phphttps://www.add-in-express.com/creating-addins-blog/cat/convert-vdproj-wix/https://www.add-in-express.com/creating-addins-blog/cat/microsoft-office-development/https://www.add-in-express.com/creating-addins-blog/cat/office-365-sharepoint/https://www.add-in-express.com/creating-addins-blog/cat/google-apps-development/https://www.add-in-express.com/creating-addins-blog/cat/asp-net-mvc/https://www.add-in-express.com/creating-addins-blog/cat/add-in-express-vcl/https://www.add-in-express.com/creating-addins-blog/cat/add-in-express-net/https://www.add-in-express.com/creating-addins-blog/cat/add-in-express-for-internet-explorer/http://-/?-https://www.add-in-express.com/creating-addins-blog/2015/05/28/add-in-express-sim-ship-visual-studio-2015-office2016/https://www.add-in-express.com/creating-addins-blog/2015/05/28/add-in-express-sim-ship-visual-studio-2015-office2016/https://www.add-in-express.com/creating-addins-blog/2015/06/02/office365-for-developers/https://www.add-in-express.com/creating-addins-blog/2015/06/09/office365-api-authentication-setup/https://www.add-in-express.com/creating-addins-blog/2015/07/13/office-365-api-querying-exchange/https://www.add-in-express.com/creating-addins-blog/author/ty-anderson/https://www.add-in-express.com/https://www.add-in-express.com/creating-addins-blog/https://www.add-in-express.com/creating-addins-blog/author/sergey-grischenko/https://www.add-in-express.com/creating-addins-blog/author/andrei-smolin/https://www.add-in-express.com/support/index.phphttp://-/?-https://www.add-in-express.com/forum/https://www.add-in-express.com/creating-addins-blog/author/sergey-grischenko/https://www.add-in-express.com/creating-addins-blog/2013/07/08/word-addin-development-application-base-objects/https://www.add-in-express.com/creating-addins-blog/2015/05/28/add-in-express-sim-ship-visual-studio-2015-office2016/https://www.add-in-express.com/creating-addins-blog/cat/add-in-express-vcl/https://www.add-in-express.com/creating-addins-blog/author/ty-anderson/https://www.add-in-express.com/creating-addins-blog/cat/microsoft-office-development/https://www.add-in-express.com/creating-addins-blog/author/ty-anderson/https://www.add-in-express.com/creating-addins-blog/cat/howto-samples/https://www.add-in-express.com/learning-center/index.phphttp://-/?-https://www.add-in-express.com/creating-addins-blog/cat/asp-net-mvc/https://plus.google.com/u/0/116245886154491887006/https://www.add-in-express.com/https://www.add-in-express.com/creating-addins-blog/author/renat-tlebaldziyeu/https://www.add-in-express.com/creating-addins-blog/author/eugene-starostin/https://www.add-in-express.com/creating-addins-blog/author/andrei-smolin/https://www.add-in-express.com/creating-addins-blog/2015/07/13/office-365-api-querying-exchange/https://www.add-in-express.com/creating-addins-blog/cat/office-365-sharepoint/https://www.add-in-express.com/creating-addins-blog/http://-/?-https://www.add-in-express.com/creating-addins-blog/cat/outlook-security-manager/https://www.add-in-express.com/custom-development/index.phphttps://www.add-in-express.com/creating-addins-blog/2015/06/02/office365-for-developers/https://www.add-in-express.com/creating-addins-blog/2015/06/09/office365-api-authentication-setup/https://www.add-in-express.com/creating-addins-blog/cat/convert-vdproj-wix/https://www.add-in-express.com/creating-addins-blog/cat/video-howto-samples/https://www.add-in-express.com/creating-addins-blog/cat/add-in-express-for-internet-explorer/https://www.add-in-express.com/creating-addins-blog/author/dmitry-kostochko/https://www.add-in-express.com/creating-addins-blog/cat/google-apps-development/https://www.add-in-express.com/creating-addins-blog/https://www.add-in-express.com/products/index.phphttp://www.facebook.com/tyranthttps://www.add-in-express.com/creating-addins-blog/cat/add-in-express-net/https://www.add-in-express.com/creating-addins-blog/author/fokke-post/https://www.add-in-express.com/sitemap.phphttps://www.add-in-express.com/purchase/index.phphttps://www.add-in-express.com/creating-addins-blog/author/eugene-astafiev/https://www.add-in-express.com/downloads/index.phphttps://www.add-in-express.com/creating-addins-blog/2015/06/04/maptitude-mappoint-alternative-developers/

  • 8/18/2019 Working With Word Document Content Objects - VB

    2/12

    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.Paragra phs.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

    Pieter van der

    Westhuizen

    Ty Anderson

    Fedor Shihantsov

    Sally Peck

    Eric Legault

    Maurice Calvert

    Alexander Solomenko

    Tags

    .NET Access Appsfor Office ASP.NET

    C#  COM add‐

    ins CommandBars

    DelphiDeployment

    Excel Google add‐

    ons IE add‐ons

    InfoPath MAPI Object

    model Office

    Office 365

    Office 2013 Office

    2016 Outlook

    Outlook regionsOutlook security PIAs

    PowerPoint Project

    Ribbon RTD

    servers

    SharePoint smart

    tags task panes

    VB.NET VBA Visio

    Visual Studio

    VSTO WiX Word

    XLL

    https://www.add-in-express.com/creating-addins-blog/tag/access/https://www.add-in-express.com/creating-addins-blog/tag/wix/https://www.add-in-express.com/creating-addins-blog/tag/outlook-security/https://www.add-in-express.com/creating-addins-blog/author/alexander-solomenko/https://www.add-in-express.com/creating-addins-blog/tag/sharepoint/https://www.add-in-express.com/creating-addins-blog/tag/commandbars/https://www.add-in-express.com/creating-addins-blog/author/ty-anderson/https://www.add-in-express.com/creating-addins-blog/tag/powerpoint/https://www.add-in-express.com/creating-addins-blog/tag/visio/https://www.add-in-express.com/creating-addins-blog/tag/pias/https://www.add-in-express.com/creating-addins-blog/tag/office/https://www.add-in-express.com/creating-addins-blog/author/pieter-van-der-westhuizen/https://www.add-in-express.com/creating-addins-blog/tag/mapi/https://www.add-in-express.com/creating-addins-blog/tag/vba/https://www.add-in-express.com/creating-addins-blog/tag/word/http://msdn.microsoft.com/en-us/library/office/ff836079.aspxhttps://www.add-in-express.com/creating-addins-blog/tag/office-2013/https://www.add-in-express.com/creating-addins-blog/tag/delphi/https://www.add-in-express.com/creating-addins-blog/tag/vbnet/https://www.add-in-express.com/creating-addins-blog/tag/office-365/https://www.add-in-express.com/creating-addins-blog/author/maurice-calvert/https://www.add-in-express.com/creating-addins-blog/tag/net/https://www.add-in-express.com/creating-addins-blog/author/eric-legault/https://www.add-in-express.com/creating-addins-blog/tag/asp-net/https://www.add-in-express.com/creating-addins-blog/tag/rtd-servers/https://www.add-in-express.com/creating-addins-blog/tag/outlook-regions/https://www.add-in-express.com/add-in-net/tour.phphttps://www.add-in-express.com/creating-addins-blog/tag/outlook/https://www.add-in-express.com/add-in-net/tour.phphttps://www.add-in-express.com/creating-addins-blog/tag/com-add-ins/https://www.add-in-express.com/creating-addins-blog/tag/deployment/https://www.add-in-express.com/creating-addins-blog/tag/office-2007-ribbon/https://www.add-in-express.com/creating-addins-blog/tag/office-object-model/https://www.add-in-express.com/creating-addins-blog/tag/excel/https://www.add-in-express.com/creating-addins-blog/tag/infopath/https://www.add-in-express.com/creating-addins-blog/tag/visual-studio/https://www.add-in-express.com/creating-addins-blog/tag/xll/https://www.add-in-express.com/creating-addins-blog/tag/c/https://www.add-in-express.com/creating-addins-blog/tag/apps-for-office/https://www.add-in-express.com/creating-addins-blog/author/sally-peck/https://www.add-in-express.com/creating-addins-blog/tag/smart-tags/https://www.add-in-express.com/creating-addins-blog/tag/google-addons/https://www.add-in-express.com/creating-addins-blog/tag/project/https://www.add-in-express.com/creating-addins-blog/tag/office-2016/https://www.add-in-express.com/creating-addins-blog/author/fedor-shihantsov/https://www.add-in-express.com/creating-addins-blog/tag/task-panes/https://www.add-in-express.com/creating-addins-blog/tag/ie-add-ons/https://www.add-in-express.com/creating-addins-blog/2013/07/08/word-addin-development-application-base-objects/#objectshttps://www.add-in-express.com/creating-addins-blog/tag/vsto/

  • 8/18/2019 Working With Word Document Content Objects - VB

    3/12

      Dim  str As String  = ""

      Dim  i As Integer

     

    rng = curDoc.Content

      i = rng.Sentences.Count()

     

    Do Until  i = 0

      str = str & rng.Sentenc es.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.

  • 8/18/2019 Working With Word Document Content Objects - VB

    4/12

    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

  • 8/18/2019 Working With Word Document Content Objects - VB

    5/12

    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 textTo 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

  • 8/18/2019 Working With Word Document Content Objects - VB

    6/12

    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

    https://www.add-in-express.com/creating-addins-blog/2013/08/23/custom-xml-parts-word-addins/https://www.add-in-express.com/add-in-net/index.phphttps://www.add-in-express.com/creating-addins-blog/wp-upload/samples/DocumentContent.ziphttps://www.add-in-express.com/creating-addins-blog/2013/08/27/word-document-properties-bookmarks-content-controls-quick-parts/https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/https://www.add-in-express.com/creating-addins-blog/2013/07/26/customizing-word-ribbons-toolbars/https://www.add-in-express.com/creating-addins-blog/2013/07/29/custom-word-task-panes/https://www.add-in-express.com/creating-addins-blog/2013/07/18/customizing-word-menu-bar-context-menus/https://www.add-in-express.com/creating-addins-blog/2013/07/08/word-addin-development-application-base-objects/https://www.add-in-express.com/creating-addins-blog/2013/08/19/working-multiple-word-documents/https://www.add-in-express.com/creating-addins-blog/2013/07/17/customizing-word-user-interface/

  • 8/18/2019 Working With Word Document Content Objects - VB

    7/12

    Building custom task panes for Word 2013 –

    2003

    Working with Word document designs, styles

    and printing

    Part 11: Populating Word documents with data from external sources

    Part 12: Working with Microsoft Word templates

    .NET, VB.NET, Word

    Filed under Add‐in Express for Office and .net, HowTo samples

    23 Comments

    Ron

    November 15, 2013 at 9:55 am

    Good as far as i t goes, but I create:

    word_doc.sections(1).headers.text = “dog”

    then

    word_doc.sections(2).headers.text = “cat”

    all headers in the document are “cat”

    Cannot figure out why

    Dmitry Kostochko (Add‐in Express Team)

    November 15, 2013 at 12:30 pm

    Hello Ron,

    According to MSDN, the HeadersFooters collection does not have the Text property:

    http://msdn.microsoft.com/en‐us/library/office/ff197925.aspx

    So, I cannot figure out how your code works.

    Shai

    December 6, 2013 at 8:47 am

    Thanks for the post and really been helpful. I wonder how can I delete a page from a word doc. for example I want

    to delete page #3 from a 5 page document. I am populating data on a word template. Every page has a picture and

    some statements and putting data from different database tables. But in case there is no data in a particular page

    because the underlying database table has no record of it, want to delete that page. I know which page to delete

    but do not know how to delete. Please help.

    Ty Anderson

    December 6, 2013 at 5:30 pm

    Hello Shai!

    You want to use the Range object.

    First navigate to the page you want to delete using the GoTo command.

    Then set a Range to reference the entire page.

    Last, delete it by calling Range.Delete.

    Here is some code that can get you started.

    With WordApp.ActiveDocument

    Set Rng = .GoTo(What:=wdGoToPage, Name:=iPage)

    Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:=”\page”)

    Rng.Delete

    End With

    You can check if the page is blank by checking the range’s Word count.

    https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-102241https://www.add-in-express.com/creating-addins-blog/cat/howto-samples/https://www.add-in-express.com/creating-addins-blog/2013/08/15/word-document-designs-styles-printing/https://www.add-in-express.com/creating-addins-blog/cat/add-in-express-net/https://www.add-in-express.com/creating-addins-blog/tag/vbnet/http://msdn.microsoft.com/en-us/library/office/ff197925.aspxhttps://www.add-in-express.com/creating-addins-blog/tag/net/https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-90833https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-90776https://www.add-in-express.com/creating-addins-blog/2013/07/29/custom-word-task-panes/https://www.add-in-express.com/creating-addins-blog/2013/08/30/populating-word-documents-data-external-sources/https://www.add-in-express.com/creating-addins-blog/2013/09/06/working-with-word-templates/https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-101990https://www.add-in-express.com/creating-addins-blog/tag/word/

  • 8/18/2019 Working With Word Document Content Objects - VB

    8/12

    If Rng.Words.Count = 0 then Rng.Delete

    Good luck.

    Ty

    Dustin C.

    December 18, 2013 at 9:34 pm

    Quick question: I consistently have reports that are actually aggregates of individual reports. This is outside of my

    control (right now), but I would l ike to break them up into their individual documents through some of the methods

    you listed above. One nice part is that the individual reports consistently have “END OF REPORT” near the end of 

    the document (two l ines above the end of the page, to be specific). My thought was to try to key off of that phrase,

    somehow drop the cursor down, and split the documents off that way. As I am somewhat of a novice to these

    objects, I was wondering if you could maybe shed some light?

    Thanks,

    Dustin

    Andrei Smolin (Add‐in Express Team)

    December 20, 2013 at 4:19 am

    Hello Dustin,

    The best way is to record a VBA macro while performing the actions in the Word UI that you need your add‐in to

    perform. Start with searching the “END OF REPORT” string, then select the report, cut it, create a new document,paste the contents, etc. The point is: the recorded macro shows the members of the Word object model involved in

    the process. Then you’ll be able to convert the macro to the programming language that you use. While working on

    this, you may find useful to look into the Reference and Concepts sections at http://msdn.microsoft.com/en‐

    us/library/office/ee861527.aspx.

    Ty Anderson

    December 27, 2013 at 3:14 pm

    Hi Dustin,

    I did a little bit of research and found this article:

    How to programmatically save each page or section of a document as a separate file

    I think the samples it provides will serve as a good start.

    You have two options here

    1 – Prepare the document by manually inserting sections after the END OF REPORT l ine.

    2 – Use the Word object model to scan each page to locate END OF REPORT. When you find it, use the Selection

    object to include all content above END OF REPORT, select it, and save it.

    Good luck,

    Ty

    Victor

    April 4, 2014 at 1:13 am

    Hi Anderson,

    Thank you for porting this ,i t’s really use‐full to me. And i have a problem to binding data using Xml Mapping

    custom xml nodes .

    I have template in that i added custom xml nodes, and i bind the data based on Xml nodes using vb.net . like below

    For Each XMlnode As Word.ContentControl In wordDoc.ContentControls

    If XMlnode.XMLMapping.CustomXMLNode.BaseName = “Desc” Then

    OperList.Add(XMlnode.XMLMapping.CustomXMLNode.BaseName)

    Next

    wordDoc.ActiveWindow.Selection.InsertRowsBelow()

    when i try to insert new row in a table using above line command ,it is insert but xml‐nodes not carried to new row

    How can i approach to print data in multiple row using xml nodes .

    http://n/ahttps://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-176158http://msdn.microsoft.com/en-us/library/office/ee861527.aspxhttp://support.microsoft.com/kb/306348https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-113966https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-109549https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-110154http://www.add-in-express.com/

  • 8/18/2019 Working With Word Document Content Objects - VB

    9/12

    please help me ..

    Thank you .

    Ty Anderson

    April 8, 2014 at 12:12 am

    Hi Victor,

    Thanks for raising this question.

    Please allow me a couple of days to respond.

    Ty

    Victor

    April 10, 2014 at 12:43 am

    Hi Anderson ,

    Thank you for g iving response to my problem.

    i will wait for your answer …

    Thank you .

    Ty Anderson

    April 16, 2014 at 12:14 am

    Victor,

    What version of Word are you targeting?

    Also, can you send your code and document to me to look at further?

    What you are doing makes sense but I need more context.

    Are you trying to create repeating content controls in a pre Word 2013 version of Word? See below:

    Repeating section content controls represented in the object model

    Kavitha

    April 23, 2014 at 10:27 am

    Hi Ty Anderson,

    I am struct at repeating data in word 2013.

    can you please find my word document at below link:

    https://onedrive.live.com/redir?resid=D935E20D58C2FDAF%21107

    and XML file : https://onedrive.live.com/redir?

    resid=D935E20D58C2FDAF!112&authkey=!ACL29rLRh6Yg0lA&ithint=file%2c.XML

    In word document CARRIER INFORMATION section i have to loop the data. But first row only it is printing.in second

    row i don’t have the xml nodes….so it i s not printing.

    But i need to print all lines in CARRIER INFORMATION.

    Let me know how can i print all lines.

    Kavitha

    April 24, 2014 at 2:25 am

    Hi Ty Anderson,

    Can i have samples of using Repeating section content controls in VB.Net.

    i have find related code in VBA

    http://gregmaxey.mvps.org/word_tip_pages/contentcontrol_enhancements_word_2013.html

    I have one more doubt. I have word document template with office 2013.I f i g ive this to customer who is using

    office 2010. how then cam manage custom xml nodes.

    Ty Anderson

    http://gregmaxey.mvps.org/word_tip_pages/contentcontrol_enhancements_word_2013.htmlhttps://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-181996https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-198087http://msdn.microsoft.com/en-us/library/office/jj889465(v=office.15).aspx#WordCC_RepeatingSectionhttps://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-180203https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-197201https://onedrive.live.com/redir?resid=D935E20D58C2FDAF!112&authkey=!ACL29rLRh6Yg0lA&ithint=file%2c.XMLhttps://onedrive.live.com/redir?resid=D935E20D58C2FDAF%21107https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-187741

  • 8/18/2019 Working With Word Document Content Objects - VB

    10/12

    April 29, 2014 at 8:46 am

    Hi Kavitha

    Thank you for the sample code. I will take a look.

    Ty

    Ty Anderson

    May 7, 2014 at 6:30 am

    Hi Kavitha,

    I reviewed your document and I think you need to look at how you setup the repeating content controls in the

    document. I don’t see a repeating section content control in the Bill of Lading document.

    Please review these articles:

    http://www.techrepublic.com/article/pro‐tip‐nest‐content‐controls‐using‐word‐2013s‐new‐repeating‐section‐

    content‐control/# .

    http://msdn.microsoft.com/en‐us/library/office/jj889465(v=office.15).aspx

    For a code sample, this might help:

    http://social.msdn.microsoft.com/Forums/en‐US/4e9fd33f‐b13a‐4a7d‐90b9‐48a96a33a71e/how‐can‐i‐loop‐the‐

    repeating‐section‐content‐controls‐using‐vbnet?forum=worddev

    Ty

    Charles Hurst

    June 4, 2014 at 2:21 am

    Hi Ty,

    Thanks for the post it was an insightful read on my current project.

    I’m having one issue where by my code is currently stripping out any Header content and replacing with whatever

    the user selects from my Pop up.

    Is there anyway to insert text in to Word Header with a merge (preferably on top) without deleting all current

    content?

    Thanks in advance,

    Charles

    Dmitry Kostochko (Add‐in Express Team)

    June 5, 2014 at 5:55 am

    Hi Charles,

    Yes, it is possible. Please have a look at the following MSDN article:

    http://msdn.microsoft.com/en‐us/library/ms178795.aspx

    It demonstrates how to get a Range object of the main Header. Using the Range object you will be able to get and

    set its Text.

    Ajith. S

    December 9, 2014 at 5:21 am

    Hi Anderson

    Your article on ‘Working with Word document content objects’ is very informative.

    My concern is programmatically using Inter.Word library how can i enable a search.

    The search results should be displayed in the navigation pane, showing all the details of the matches found.

    Kindly help.

    Thanks in advance

    Ty Anderson

    December 10, 2014 at 6:04 pm

    Hello Ajith

    https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-205260http://msdn.microsoft.com/en-us/library/office/jj889465(v=office.15)https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-278918https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-281529http://social.msdn.microsoft.com/Forums/en-US/4e9fd33f-b13a-4a7d-90b9-48a96a33a71e/how-can-i-loop-the-repeating-section-content-controls-using-vbnet?forum=worddevhttps://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-307832https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-307144http://msdn.microsoft.com/en-us/library/ms178795.aspxhttp://www.techrepublic.com/article/pro-tip-nest-content-controls-using-word-2013s-new-repeating-section-content-control/#https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-216280

  • 8/18/2019 Working With Word Document Content Objects - VB

    11/12

    Unfortunately, Word does not provide an API object for the Navigation pane.

    It is possible however to build your own pane that mimics the search behavior you want to automate.

    You can execute searches using the Find object:

    http://msdn.microsoft.com/en‐us/library/office/ff839118(v=office.15).aspx

    Ty

    Vijay Nanda

    February 14, 2015 at 3:31 pm

    Hi Anderson,

    I want to write a small programme using VB 6.0 and MS Word 2007 wherein I want to create a document (My

    Report.doc) which can be edited, reformatted, displayed and printed. The full details are as under:

    There are 12 conditions. if condition No. 1 is met some pre‐bookmarked portion from the already existed MS Word

    File (C:\My File.doc) is to be copied, a New Word Document is opened with the name “My Report.doc” and the

    copied portion is pasted on it.

    For example,

    If K = 1 Then (read pre bookmarked portion from the World File (C:\My File.doc) Open a New Word Document and

    copy paste the selected portion in this New Word Document (My Report.doc).

    Elseif K = 2

    Then (read selected portion from the World File (C:\My File.doc) Open a New Word Document and copy paste the

    selected portion in this New Word Document (My Report.doc).

    ……and so on till K = 12 is tested. (Only one option will be true hence only one MS Word File (My Report.doc) will be

    Opened.

    Similarly L, M, N, O, P, Q, R,S & T are to be tested (12 Times each) and the entire information is to be deposited in

    one single MS Word File (My Report.doc).

    Note :

    (Text in the C:\My File is simple text divided into paragraphs. There are no Tables/Fields etc.)

    I shall be grateful, if you could help me in making this programme using VB 6.0 and MS Word 2007 for my personal

    use.

    With Kind Regards

    Vijay Nanda

    Ty Anderson

    February 18, 2015 at 10:23 pm

    Hello Vijay,

    I can’t help you write the app with VB6 but I can point you to some useful links:

    http://word.mvps.org/faqs/macrosvba/WorkWithBookmarks.htm

    http://www.vbexplorer.com/VBExplorer/office_vb.asp

    Is VB6 a strict requirement? If so, why?

    Ty

    Ravikumar

    May 10, 2015 at 11:49 am

    Hi,

    how to get the total count of characters from beginning of the document to the current cursor position. i want to

    get total characters from starting to cursor edit point, not the total characters in the document.

    Please help

    Thanks.

    Ty Anderson

    May 12, 2015 at 12:59 pm

    https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-331840https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-332992http://msdn.microsoft.com/en-us/library/office/ff839118(v=office.15)http://www.vbexplorer.com/VBExplorer/office_vb.asphttps://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-352640https://www.add-in-express.com/creating-addins-blog/2013/08/07/word-document-content-objects/comment-page-1/#comment-351951http://word.mvps.org/faqs/macrosvba/WorkWithBookmarks.htm

  • 8/18/2019 Working With Word Document Content Objects - VB

    12/12

    Hi Ravikumar,

    To count the characters is simple. You only need to check this:

    Dim currentPosition As Long

    currentPosition = Selection.Range.Start

    The Selection.Range.Start is the position of the cursor.

    The integer value that .Start returns, is the number of characters that precedes it within the document.

    I hope this helps.

    Ty

    Post a comment

      Name

      E‐mail address (will not be published)

      Website

    Submit Comment

    © 2004–2015 Add‐in Express LtdAll rights reserved. Privacy Policy

    Microsoft and the Office logo are trademarks or registered trademarks of MicrosoftCorporation in the United States and/or other countries. All other trademarks areproperty of their respective owners.

    Have any questions? Ask us right now!

    Products & technologies

    Office add‐ins in .net

    Office addins in Delphi

    VDProj to WiX Converter

    Advanced Outlook Regions for VSTOOutlook forms and views

    Website

    Links

    Add‐in Express Blog

    Samples

    HowTo samples for developers

    Sample add‐ins for Excel, Word, Outlook

    Developer Guides

    Add‐in Express for Office and .net

    Add‐in Express for Office and Delphi

    Add‐in Express for Internet Explorer

    Outlook Security ManagerRibbon Designer for SharePoint & Office

    365

     

    Add‐in Express FeedbackIf you have any questions or other feedback about

    the blog posts or our products, please write to us

    using this form.

    https://www.add-in-express.com/https://www.add-in-express.com/docs/sharepoint-office365-ribbon-designer.phphttps://www.add-in-express.com/add-in-delphi/index.phphttps://www.add-in-express.com/outlook-regions/index.phphttps://www.add-in-express.com/docs/internet-explorer-extensions.phphttps://www.add-in-express.com/vdproj-wix-converter/index.phphttps://www.add-in-express.com/outlook-extension/index.phphttps://www.add-in-express.com/add-in-net/index.phphttps://www.add-in-express.com/docs/outlook-security-manager.phphttps://www.add-in-express.com/support/add-in-express-howto.phphttps://www.add-in-express.com/docs/net.phphttps://www.add-in-express.com/docs/vcl.phphttps://www.youtube.com/user/AddinExpresshttps://www.add-in-express.com/creating-addins-blog/https://www.add-in-express.com/links/index.phphttps://www.add-in-express.com/privacy-policy.phphttps://profiles.google.com/106597507483024743032https://www.facebook.com/add-in-expresshttps://www.add-in-express.com/free-addins/index.phphttps://www.add-in-express.com/bitrix/rss.php?ID=19&LANG=en&TYPE=downloadshttps://twitter.com/#!/addinexpress