Ad

Thursday, October 09, 2014

Word Adding Page Number and Number of Pages to A Header by .NET

Sometimes things on the internet are hard to find because most other questions are slightly related. One such instance I ran into is programattically adding in the page number and number of pages in a header. I’m sure the answer has been asked and answered somewhere on the internet, but I couldn’t find it.

My initial attempts came up way short. Using some of the examples overwrote the other text I needed in the header. So here is my code to get the job done.

Public Sub HeaderInformation(ByRef reportHeaderInfo As ReportHeaderInformation)
    ' Add info for header.
    Dim header As Word.HeaderFooter = oDoc.Sections.Last.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary)
    Dim headerRange As Word.Range = header.Range
    headerRange.Text = "File Name: " & reportHeaderInfo.FileName & vbTab & vbTab & "Date: " & DateTime.Now.ToString("MM-dd-yy")
    headerRange.Text += "Project: " & reportHeaderInfo.ProjectName & vbTab & vbTab & "Time: " & DateTime.Now.ToString("hh:mm:ss")
    headerRange.Text += "Subproject: " & reportHeaderInfo.SubProject & " , Subproject No:" & reportHeaderInfo.SubProjectNo & vbTab & vbTab & "  of  "

    headerRange = header.Range
    headerRange.SetRange(header.Range.Text.IndexOf("of") - 2, header.Range.Text.IndexOf("of") - 1)
    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage)

    headerRange = header.Range
    headerRange.SetRange(header.Range.End - 1, header.Range.End)
    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldNumPages)

End Sub

Note that I had to get a range within the header range and then add the page number and number of pages fields to the header. Make sure not to utilize the character count of the header range because it doesn’t count the field’s characters. This ends up having the field being inserted into the original field. Using the Range.End returns the actual end and not the end of the character count.

No comments:

LinkWithin

Blog Widget by LinkWithin

Ad