Search code examples
vb.netms-wordheaderfooter

How to insert more then one items in a word header/footer via vb.net?


i use vb.net an the namespace "Imports Microsoft.Office.Interop.Word". I have word-document and i want to create a header and/or a footer in these. For example a footer like "Date: [CurrentDate] Page:[CurrentPage]". At the moment I only write ONE field with success. If I write/add the next field, the first field will be deleted. Like "replace" and not "add". What's wrong with code?

    For Each section As Section In _wordDoc.Application.ActiveDocument.Sections
        Dim footerRange As Range = section.Footers(WdHeaderFooterIndex.wdHeaderFooterPrimary).Range

        footerRange.Fields.Add(footerRange, WdFieldType.wdFieldFileName)
        footerRange.Fields.Add(footerRange, WdFieldType.wdFieldDate)
        ' footerRange.Fields.Add(footerRange, "Page")
        footerRange.Fields.Add(footerRange, WdFieldType.wdFieldPage)
        'footerRange.Fields.Add(footerRange, "-")
        footerRange.Fields.Add(footerRange, WdFieldType.wdFieldNumPages)
        footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight
    Next

The second problem is, how to add simple Text to the header/footer?


Solution

  • i found a solution:

            footerRange = section.Footers(WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            footerRange.InsertAfter("Page ")
            footerRange.SetRange(footerRange.End + 1, footerRange.End + 1)
            footerRange.Fields.Add(footerRange, WdFieldType.wdFieldPage)
            footerRange = section.Footers(WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            footerRange.InsertAfter(" of ")
            footerRange.SetRange(footerRange.End + 1, footerRange.End + 1)
            footerRange.Fields.Add(footerRange, WdFieldType.wdFieldNumPages)