Word Automation inserting Page Numbers

Posted on 2009-02-09
Last Modified: 2012-08-14
Hi to all,

I created a Visual Basic .Net application using Visual Studio 2008. This application creates one word document from files in a selected folder and then numbers the pages. All is working just fine, but I am having issues numbering the pages correctly. The code below shows what I am doing to number the pages, but some pages are not correct. For instance: after page 4 comes page 6 and so on. Can anyone please let me know what I am doing wrong and if possible give me code to use the built in "Building Blocks" that comes with office 2007.

Public Shared Sub InsertPageNumbers(ByVal myWordApplication As Word.Application)



            Dim NumberOfSections As Integer = myWordApplication.ActiveDocument.Sections.Count

            Dim i As Integer = 1

            Do Until i = NumberOfSections

                Dim rng As Word.Range = myWordApplication.ActiveDocument.Sections(i).Footers _


                rng.Fields.Add(rng, , "NumPages", False)

                rng.Fields.Add(rng, , "        Page ", False)

                rng.InsertBefore(vbTab & "        Page ")


                i += 1


        End Sub

Open in new window

Question by:ALawrence007
    LVL 19

    Expert Comment

    You'll find some good code samples here:

    Hopefully that will help

    Dawn Crosier-Bleuel
    Word MVP

    Author Comment


    Thanks for the reply. The link you posted is very helpful and I used the contents in that post, but I keep on getting the following error when I use that (or any building blocks) code.

    'Microsoft.Office.Interop.Word.BuildingBlockTypes' cannot be indexed because it has no default property.

    Do you maybe have an idea what might cause this?


    LVL 19

    Expert Comment

    Do you have more than one set of building blocks in your building blocks folder? If so, you may need to loop until you find the proper one.

    You might also want to post the code that you are using to see whether there is something that might stick out.

    Dawn Crosier-Bleuel
    Word MVP
    i = 1
    For Each atemp In Templates
        If atemp = "Building Blocks.dotx" Then Set strMasterTemplate = Templates(i)
        Debug.Print atemp
        i = i + 1
    Next atemp

    Open in new window

    LVL 19

    Expert Comment

    I just ran through Jodie's code and did not get any errors. So it's got to be something extra that you are doing in your code. I am using straight Word, and not .Net.

    Dawn Crosier-Bleuel
    Word MVP

    Author Comment


    Thanks for the reply. The only thing I can think of is the fact that all the documents are located on a file server on a share. This file server has word 2007 installed. If that is not the issue, I included my code using building blocks below:

    Public Shared Sub BuildingPageNumbers(ByVal myWordApplication As Word.Application)
    'With myWordApplication
    '    .ActiveDocument.AttachedTemplate.BuildingBlockEntries("Plain Number 2").Insert _
    '    (myWordApplication.Selection.Range, True)
    '    .Selection.TypeText("Page ")
    '    .ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument
    'End With
    'MSDN Code
    Dim wordDocument As Word.Document = Nothing
    Dim wordTemplate As Word.Template = Nothing
    Dim wordBuildingBlock As Word.BuildingBlock
    Dim paramBBType As Word.WdBuildingBlockTypes = Word.WdBuildingBlockTypes.wdTypePageNumberBottom
    Dim paramBBCategory As String = "Simple"
    Dim paramBBName As String = "Plain Number 2"
    wordTemplate = myWordApplication.Templates(1)
    Dim TemplateName As String = wordTemplate.Name
    wordBuildingBlock = _
    wordTemplate.BuildingBlockTypes.Item(paramBBType) _
    wordBuildingBlock.Insert(wordDocument.Sections(1) _
    End Sub

    Open in new window


    Accepted Solution


    I found an easier way using OpenXMLDeveloper. You need to create a word document (ONLY Word 2007). Insert the footer you want, save the file and then open it as a ZIP file. Get the footer1.xml file and then copy that to an area where you can get to it. Use the code below to create a footer in your document.

    Thanks for the help though

     Public Sub WDAddFooter(ByVal docName As String, ByVal footerContent As Stream)
            ' Given a document name, and a stream containing valid Footer content,
            ' add the stream content as a Footer in the document and remove the original Footer
            Const wordmlNamespace As String = ""
            Const relationshipNamespace As String = ""
            Dim wdDoc As WordprocessingDocument = WordprocessingDocument.Open(docName, True)
            Using (wdDoc)
                ' Delete existing Footer part
                ' Create a new Footer part.
                Dim FooterPart As FooterPart = wdDoc.MainDocumentPart.AddNewPart(Of FooterPart)()
                Dim rId As String = wdDoc.MainDocumentPart.GetIdOfPart(FooterPart)
                Dim footerDoc As XmlDocument = New XmlDocument
                footerContent.Position = 0
                ' Write the Footer out to its part.
                ' Manage namespaces to perform Xml XPath queries.
                Dim nt As NameTable = New NameTable
                Dim nsManager As XmlNamespaceManager = New XmlNamespaceManager(nt)
                nsManager.AddNamespace("w", wordmlNamespace)
                ' Get the document part from the package.
                ' Load the XML in the part into an XmlDocument instance.
                Dim xdoc As XmlDocument = New XmlDocument(nt)
                ' Find the node containing the document layout.
                Dim targetNodes As XmlNodeList = xdoc.SelectNodes("//w:sectPr", nsManager)
                For Each targetNode As XmlNode In targetNodes
                    ' Delete any existing references to Footer.
                    Dim footerNodes As XmlNodeList = targetNode.SelectNodes("./w:footerReference", nsManager)
                    For Each footerNode As System.Xml.XmlNode In footerNodes
                    ' Create the new Footer reference node.
                    Dim node As XmlElement = xdoc.CreateElement("w:footerReference", wordmlNamespace)
                    Dim attr As XmlAttribute = node.Attributes.Append(xdoc.CreateAttribute("r:id", relationshipNamespace))
                    attr.Value = rId
                    targetNode.InsertBefore(node, targetNode.FirstChild)
                ' Save the document XML back to its part.
            End Using
        End Sub

    Open in new window

    LVL 19

    Expert Comment

    Very Cool! Thanks for sharing that. I really need to get with it with XML :)

    Dawn Crosier-Bleuel
    Word MVP

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Introduction This tutorial provides instructions on how to properly format your Word document using the inbuilt tools provided. The benefits of using these tools means your documents are more accessible and easily portable to other applications an…
    I would like to show you some basics you can do with Mailings in MS Word. It´s quite handy feature you can use for creating envelopes, labels, personalized letters etc. First question could be what is this feature good for? Mailing can really he…
    The viewer will learn how to make their project stand out over others by learning how to change colors and shapes, add spaces, change directions, and add bullets to their charts.
    This video shows where to find the word count, how to display it, and what it breaks down to in Microsoft Word.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    7 Experts available now in Live!

    Get 1:1 Help Now