使用VB.NET更新Word交叉引用

时间:2013-11-06 16:38:06

标签: .net vb.net ms-word office-interop

我想使用VB.net应用程序更新现有Word文档的所有交叉引用。

例如,我的word文档(.docm)(我在/ - / /之间写评论以便理解):

我的文件标题:测试更新
/ - 这个标题在BOOKMARK中名为“TITLE1” - /

文件标题是:{REF TITLE1 \ h}
/ - {REF TITLE1 \ h}是交叉引用的代码,引用书签“TITLE1” - /
/ - 此文本位于我的文档的标题中 - /

我使用VB.net应用程序来更改文档标题:
在我的代码下面:

Imports Microsoft.Office.Interop

Public Sub UpdateWord()
    Dim oWord As Word.Application
    Dim oDoc As Word.Document

    'Start Word and open the document template.
    oWord = CreateObject("Word.Application")
    oWord.Visible = False
    oDoc = oWord.Documents.Open(Path_Word_Document)

    oDoc.Bookmarks.Item("TITLE1").Range.Text = "My New Title"  

    oWord.Documents.Save()
    oWord.Documents.Close()
    oWord.Quit()
End Sub  

当我启动此子时,我的文档标题已更新,但交叉引用保留旧标题值。

您知道如何更新我的VB.net sub中的交叉引用。

由于

我在Win7上使用MS Word 2010,Visual Studio 2010(.NET Framework 3.5)。

1 个答案:

答案 0 :(得分:2)

最后我找到了解决方案。

请让我展示代码:

Imports Microsoft.Office.Interop

Public Sub UpdateWord()
    Dim oWord As Word.Application
    Dim oDoc As Word.Document
    Dim oHeader As Word.HeaderFooter
    Dim oSection As Word.Section

    'Start Word and open the document template.
    oWord = CreateObject("Word.Application")
    oWord.Visible = False
    oDoc = oWord.Documents.Open(Path_Word_Document)

    For Each oSection In oDoc.Sections
        For Each oHeader In oSection.Headers
            If oHeader.Exists Then
                For Each oField In oHeader.Range.Fields
                    oField.Update()
                Next oField
            End If
        Next oHeader
    Next oSection


    oWord.Documents.Save()
    oWord.Documents.Close()
    oWord.Quit()
End Sub  

感谢Varocarbas的帮助。