none
Adding Sections to word document using VB.net RRS feed

  • Question

  • Hi, I am trying to Automate the Word document using vb.net

    I am facing problems when i try to define a section, insert section breaks and getting it updated in the table of contents.

    I will break down the steps that I am trying to do:

    1) Add Multiple sections to word document.

    2) Define the Section Heading.

    3) Add the text that I want to put under this section.

    4) Insert Section Break 

    5) Define another section, follow steps 2,3,4

    6) Update all the Section headings and page numbers in the Table of Contents in my first Page.

    Problems I am facing:

    1) I cannot add the text under the specific section

    2) when there is a Page break or Section break the numbers are not getting updated properly (See the Testing section as numbered below)

    For Eg: My Table of Contents/ Sections are numbered in the document as below

                1) Introduction

                2) Electrical Parts

                3) Mechanical Parts

                1) Testing 

    3) I have added a table under section Testing and issue is all the cells inside the table are getting numbered.

    4) How to define sub-sections numbered in a sequence 


      Dim oWord As Word.Application
      Dim oDoc As Word.Document
      Dim oTable As Word.Table
    
     'Start Word and open the document template.
            oWord = CreateObject("Word.Application")
            oWord.Visible = True
            oDoc = oWord.Documents.Add
            Dim oRng As Word.Range = oDoc.Content


    In the code below: - I cannot get the text added under the section (oRng.Text is not adding any text to the doc)

      '-----------------Define Section--------------------------------------------------
            oRng.Text = "Introduction"
            oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1
            oRng.ListFormat.ApplyNumberDefault()
            oRng.InsertAfter(vbCr)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.Style = Word.WdBuiltinStyle.wdStyleNormal
            oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading
    
            oRng.Text = "This document is to define the specification for Electronic Parts"
            oRng.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)


     '--------------Insert Table of Contents---------------------------------------------------------------
            With oDoc
                .TablesOfContents.Add(Range:=oWord.Selection.Range, _
                           RightAlignPageNumbers:=True, _
                           UseHeadingStyles:=True, _
                           IncludePageNumbers:=True, _
                           AddedStyles:="styleSection", _
                           UseHyperlinks:=False, _
                           HidePageNumbersInWeb:=True, _
                           UseOutlineLevels:=True)
                .TablesOfContents(1).Range.Font.Name = "Arial Narrow"
                .TablesOfContents(1).Range.Font.Size = 11
                .TablesOfContents(1).TabLeader = Word.WdTabLeader.wdTabLeaderDots
                .TablesOfContents.Format = Word.WdTocFormat.wdTOCSimple
            End With
    
            'Page Break after Table of Contents
            oWord.Selection.InsertBreak()
    
            'Update Table of Contents
            oDoc.TablesOfContents(1).Update()
            oDoc.TablesOfContents(1).UpdatePageNumbers()

    This is how it is seen in the document: TOC is not getting updated properly

    1..................................................................................................1

    2 Introduction..............................................................................2

    3 Electrical Parts..........................................................................3

    4 Mechanical Parts.......................................................................4

    1 Testing......................................................................................5

    Any help on this to get it sorted out would be great and much appreciated.

    Monday, May 12, 2014 5:34 PM

Answers

  • Hi,

    According to my investigation, you could insert list first, find the specified text and insert content.

    Please try the code below:

    Sub Main() Dim oWord As Word.Application Dim oDoc As Word.Document 'Start Word and open the document template. oWord = CreateObject("Word.Application") oWord.Visible = True oDoc = oWord.Documents.Add Dim oRng As Word.Range = oDoc.Content '-----------------Define Section-------------------------------------------------- oRng.Text = "Introduction" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oRng.Text = "Electrical Parts" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oRng.Text = "Mechanical Parts" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oRng.Text = "Testing" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oWord.Selection.Find.ClearFormatting() With oWord.Selection.Find .Text = "Electrical Parts" End With If oWord.Selection.Find.Execute() Then oWord.Selection.MoveRight(Word.WdUnits.wdCharacter, 1) oWord.Selection.TypeParagraph() oWord.Selection.TypeText("This document is to define the specification for Electronic Parts") End If '--------------Insert Table of Contents--------------------------------------------------------------- oWord.Selection.HomeKey(Word.WdUnits.wdStory, Nothing) With oDoc .TablesOfContents.Add(Range:=oWord.Selection.Range, _ RightAlignPageNumbers:=True, _ UseHeadingStyles:=True, _ IncludePageNumbers:=True, _ AddedStyles:="styleSection", _ UseHyperlinks:=False, _ HidePageNumbersInWeb:=True, _ UseOutlineLevels:=True) .TablesOfContents(1).Range.Font.Name = "Arial Narrow" .TablesOfContents(1).Range.Font.Size = 11 .TablesOfContents(1).TabLeader = Word.WdTabLeader.wdTabLeaderDots .TablesOfContents.Format = Word.WdTocFormat.wdTOCSimple End With 'Page Break after Table of Contents oWord.Selection.MoveLeft(Word.WdUnits.wdCharacter, 1) oWord.Selection.InsertBreak() oWord.Selection.TypeBackspace()
    oWord
    .Selection.MoveRight(Word.WdUnits.wdCharacter, 1)

    'Update Table of Contents 'oDoc.TablesOfContents(1).Update() 'oDoc.TablesOfContents(1).UpdatePageNumbers() End Sub

    The result:

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Tuesday, May 13, 2014 9:14 AM
    Moderator
  • Hi Uday

    One thing you should be doing is linking the styles you use to a Numbering (List) style, rather than trying to apply numbering directly - oRng.ListFormat.ApplyNumberDefault().

    If you have a List style that links levels with a specific style (Heading 1 for Level 1, for example) then the numbering will be applied automatically when the style is applied.

    If numbering needs to restart, then you should assign the style with the numbering to Level 2 and assign Level 1 with no numbering defined to a different style. Level 2 should be set to restart numbering when following a Level 1 paragraph. This approach is reliable and comparatively painless.

    >>In the code below: - I cannot get the text added under the section (oRng.Text is not adding any text to the doc)<<

    Most likely, some other assignment to oRng is overwriting what you wrote to the Range previously. You need to always collapse the Range before assigning additional content to it.


    Cindy Meister, VSTO/Word MVP, my blog

    • Marked as answer by Uday22 Tuesday, May 13, 2014 2:27 PM
    Tuesday, May 13, 2014 10:04 AM
    Moderator

All replies

  • Hi,

    According to my investigation, you could insert list first, find the specified text and insert content.

    Please try the code below:

    Sub Main() Dim oWord As Word.Application Dim oDoc As Word.Document 'Start Word and open the document template. oWord = CreateObject("Word.Application") oWord.Visible = True oDoc = oWord.Documents.Add Dim oRng As Word.Range = oDoc.Content '-----------------Define Section-------------------------------------------------- oRng.Text = "Introduction" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oRng.Text = "Electrical Parts" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oRng.Text = "Mechanical Parts" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oRng.Text = "Testing" oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1 oRng.ListFormat.ApplyNumberDefault() oRng.InsertAfter(vbCr) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.Style = Word.WdBuiltinStyle.wdStyleNormal oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading oWord.Selection.Find.ClearFormatting() With oWord.Selection.Find .Text = "Electrical Parts" End With If oWord.Selection.Find.Execute() Then oWord.Selection.MoveRight(Word.WdUnits.wdCharacter, 1) oWord.Selection.TypeParagraph() oWord.Selection.TypeText("This document is to define the specification for Electronic Parts") End If '--------------Insert Table of Contents--------------------------------------------------------------- oWord.Selection.HomeKey(Word.WdUnits.wdStory, Nothing) With oDoc .TablesOfContents.Add(Range:=oWord.Selection.Range, _ RightAlignPageNumbers:=True, _ UseHeadingStyles:=True, _ IncludePageNumbers:=True, _ AddedStyles:="styleSection", _ UseHyperlinks:=False, _ HidePageNumbersInWeb:=True, _ UseOutlineLevels:=True) .TablesOfContents(1).Range.Font.Name = "Arial Narrow" .TablesOfContents(1).Range.Font.Size = 11 .TablesOfContents(1).TabLeader = Word.WdTabLeader.wdTabLeaderDots .TablesOfContents.Format = Word.WdTocFormat.wdTOCSimple End With 'Page Break after Table of Contents oWord.Selection.MoveLeft(Word.WdUnits.wdCharacter, 1) oWord.Selection.InsertBreak() oWord.Selection.TypeBackspace()
    oWord
    .Selection.MoveRight(Word.WdUnits.wdCharacter, 1)

    'Update Table of Contents 'oDoc.TablesOfContents(1).Update() 'oDoc.TablesOfContents(1).UpdatePageNumbers() End Sub

    The result:

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Tuesday, May 13, 2014 9:14 AM
    Moderator
  • Hi Uday

    One thing you should be doing is linking the styles you use to a Numbering (List) style, rather than trying to apply numbering directly - oRng.ListFormat.ApplyNumberDefault().

    If you have a List style that links levels with a specific style (Heading 1 for Level 1, for example) then the numbering will be applied automatically when the style is applied.

    If numbering needs to restart, then you should assign the style with the numbering to Level 2 and assign Level 1 with no numbering defined to a different style. Level 2 should be set to restart numbering when following a Level 1 paragraph. This approach is reliable and comparatively painless.

    >>In the code below: - I cannot get the text added under the section (oRng.Text is not adding any text to the doc)<<

    Most likely, some other assignment to oRng is overwriting what you wrote to the Range previously. You need to always collapse the Range before assigning additional content to it.


    Cindy Meister, VSTO/Word MVP, my blog

    • Marked as answer by Uday22 Tuesday, May 13, 2014 2:27 PM
    Tuesday, May 13, 2014 10:04 AM
    Moderator
  • Hi Cindy, Thanks for your reply. This is now clear.

    As I am trying to Automate/format a word document, I was wondering is there any tutorials or examples that explains clearly so as to learn the Word Automation as and when I do the demo projects ?!  

    MSDN & the forum has been so helpful so far but if there is a specific set of designed structured tutorials available for this it would be great for beginners to start with.

    Tuesday, May 13, 2014 10:51 AM
  • Hi,

    According to my investigation, you could insert list first, find the specified text and insert content.

    Please try the code below:

    Sub Main()
            Dim oWord As Word.Application
            Dim oDoc As Word.Document
            'Start Word and open the document template.
            oWord = CreateObject("Word.Application")
            oWord.Visible = True
            oDoc = oWord.Documents.Add
            Dim oRng As Word.Range = oDoc.Content
            '-----------------Define Section--------------------------------------------------
            oRng.Text = "Introduction"
            oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1
            oRng.ListFormat.ApplyNumberDefault()
            oRng.InsertAfter(vbCr)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.Style = Word.WdBuiltinStyle.wdStyleNormal
            oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading
    
            oRng.Text = "Electrical Parts"
            oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1
            oRng.ListFormat.ApplyNumberDefault()
            oRng.InsertAfter(vbCr)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.Style = Word.WdBuiltinStyle.wdStyleNormal
            oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading
    
            oRng.Text = "Mechanical Parts"
            oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1
            oRng.ListFormat.ApplyNumberDefault()
            oRng.InsertAfter(vbCr)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.Style = Word.WdBuiltinStyle.wdStyleNormal
            oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading
    
            oRng.Text = "Testing"
            oRng.Style = Word.WdBuiltinStyle.wdStyleHeading1
            oRng.ListFormat.ApplyNumberDefault()
            oRng.InsertAfter(vbCr)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.Style = Word.WdBuiltinStyle.wdStyleNormal
            oRng.Style = Word.WdBuiltinStyle.wdStyleNoteHeading
    
            oWord.Selection.Find.ClearFormatting()
            With oWord.Selection.Find
                .Text = "Electrical Parts"
            End With
            If oWord.Selection.Find.Execute() Then
                oWord.Selection.MoveRight(Word.WdUnits.wdCharacter, 1)
                oWord.Selection.TypeParagraph()
                oWord.Selection.TypeText("This document is to define the specification for Electronic Parts")
            End If
    
            '--------------Insert Table of Contents---------------------------------------------------------------
            oWord.Selection.HomeKey(Word.WdUnits.wdStory, Nothing)
            With oDoc
                .TablesOfContents.Add(Range:=oWord.Selection.Range, _
                           RightAlignPageNumbers:=True, _
                           UseHeadingStyles:=True, _
                           IncludePageNumbers:=True, _
                           AddedStyles:="styleSection", _
                           UseHyperlinks:=False, _
                           HidePageNumbersInWeb:=True, _
                           UseOutlineLevels:=True)
                .TablesOfContents(1).Range.Font.Name = "Arial Narrow"
                .TablesOfContents(1).Range.Font.Size = 11
                .TablesOfContents(1).TabLeader = Word.WdTabLeader.wdTabLeaderDots
                .TablesOfContents.Format = Word.WdTocFormat.wdTOCSimple
            End With
            'Page Break after Table of Contents
            oWord.Selection.MoveLeft(Word.WdUnits.wdCharacter, 1)
            oWord.Selection.InsertBreak()
            oWord.Selection.Delete(Word.WdUnits.wdCharacter, 1)
            'Update Table of Contents
            'oDoc.TablesOfContents(1).Update()
            'oDoc.TablesOfContents(1).UpdatePageNumbers()
        End Sub

    The result:

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Hi George, Thanks for your reply.

    Your code works fine updating the correct section numbers.

    But, the usage of following line of code

     oWord.Selection.Delete(Word.WdUnits.wdCharacter, 1)

    Replaces the Table of Contents on the first page with the actual sections.

    So there is only one page as a end result.




    • Edited by Uday22 Tuesday, May 13, 2014 2:32 PM
    Tuesday, May 13, 2014 10:52 AM
  • Hi,

    Thanks for your feedback.

    Yes, I got it.

    Since I record a macro to delete a blank row (Press "Delete"), then I got:

    Selection.Delete Unit:=wdCharacter, Count:=1

    But When I executed the code both in VBA or VB.NET, it would delete the blank row and the previous page.

    In this case, there was only one page as a end result as you mentioned.

    Please change the code above to:

    oWord.Selection.TypeBackspace()
    oWord.Selection.MoveRight(Word.WdUnits.wdCharacter, 1)

    It would press "BackSpace" to delete the blank.

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, May 14, 2014 2:07 AM
    Moderator
  • Hi Uday

    No, unfortunately there isn't any tutorial such as you describe. Word has so many features and capabilities, and people such varying requirements, that it's very difficult to make tutorials - what one person needs, another does not, etc...


    Cindy Meister, VSTO/Word MVP, my blog

    Wednesday, May 14, 2014 2:32 PM
    Moderator