vb.netvisual-studiointeropoffice-interop

I was able to display the page numbers of the Word file created by my software. But I can't show it exactly where I want


this is my code:

            ' Add a new paragraph to the third cell in the first row of the table for the ReviewDate value
            Dim newParagraph7 As Word.Paragraph = oTableHeader.Cell(1, 3).Range.Paragraphs.Add()
            newParagraph7.Range.Text = "Review Date: " & ReviewDate
            newParagraph7.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight

            ' Add a new paragraph (newParagraph8) to the header range
            Dim newParagraph8 As Word.Paragraph = headerRange.Paragraphs.Add()
            newParagraph8.Range.Text = "Page Number: "
            ' Align the new paragraph to the right
            newParagraph8.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight
            ' Insert the field code for the current page number
            Dim pageNumberField As Word.Field = newParagraph8.Range.Fields.Add(Range:=newParagraph8.Range, Type:=Word.WdFieldType.wdFieldPage, Text:="\* ARABIC")
            pageNumberField.Code.Text = pageNumberField.Code.Text & " \* MERGEFORMAT"

            ' Repaginate the document
            doc.Repaginate()

My problem is that I want to be able to show page numbers exactly in the paragraph after newParagraph7. But this code is shown outside the table and somewhere else. And I can't get it into oTableHeader.Cell(1, 3)

This code is supposed to show a table in the header of a word file created by my software. And my goal is to show the number of pages dynamically by build-in Word with Office.Interop


Solution

  • Have you tried Dim newParagraph8 As Word.Paragraph = oTableHeader.Cell(1, 3).Range.Paragraphs.Add() to ensure that both the Review Date and the Page Number are within the same cell.

            Dim cellRange As Word.Range = oTableHeader.Cell(1, 3).Range
    
            Dim ReviewDate As String = DateTime.Now.ToString("d MMMM yyyy")
            Dim newParagraph7 As Word.Paragraph = cellRange.Paragraphs.Add()
            newParagraph7.Range.Text = "Review Date: " & ReviewDate
            newParagraph7.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight
    
            ' Move the range to the end of the cell to add the next paragraph
            cellRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
    
            Dim newParagraph8 As Word.Paragraph = cellRange.Paragraphs.Add()
            newParagraph8.Range.Text = "Page Number: "
            newParagraph8.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight
    
            cellRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
    
            Dim pageNumberField As Word.Field = cellRange.Fields.Add(Range:=cellRange, Type:=Word.WdFieldType.wdFieldPage)
            pageNumberField.Code.Text = pageNumberField.Code.Text & " \* MERGEFORMAT"