简体   繁体   中英

How to Insert a Table as a Word Header using vb.net

I am trying to insert a table to the header of word but instead of placing it in header the table is being created in the body of the page

I have tried this,

Dim objApp As Word.Application
    Dim objDoc As Word.Document
    objApp = New Word.Application()
    objDoc = objApp.Documents.Open(TextBox1.Text)
    objDoc.Sections(1).PageSetup.DifferentFirstPageHeaderFooter = True
    objDoc.Sections(1).Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.Tables.Add(Range:=objApp.Selection.Range, NumRows:=3, NumColumns:=1)
    objDoc.Save()
    objDoc.Close()
    objApp.Quit()
    Dim oWord = New Microsoft.Office.Interop.Word.Application
    Dim Dir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    oWord.Documents.Open(TextBox1.Text)
    Dim oDoc = oWord.ActiveDocument

    oWord.Visible = True

    Dim tbl As Word.Table = oDoc.Tables(1)

    tbl.Cell(1, 1).Range.Text = "Content"
    tbl.Cell(2, 1).Range.Text = "Content"
    tbl.Cell(3, 1).Range.Text = "Total Exp:"
    oDoc.Save()
    oDoc.Close()
    oWord.Quit()

Any Help will be really appreciated.

ojDoc.Sections(1).
   Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.
   Tables.Add(Range:=objApp.Selection.Range, NumRows:=3, NumColumns:=1)

You're trying to anchor the new table at the selection, but that is likely not to be inside the header.
This seems to work:

Dim r As Word.Range = objDoc.Sections(1).
    Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range
r.Tables.Add(Range:=r, NumRows:=3, NumColumns:=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM