我正在编写一个 VB.net 应用程序,该应用程序以 Word 文档为模板,并查找并替换文档中的多个标签。我可以对正文执行此操作,但无法使其适用于文档页脚中的文本。我怎样才能做到这一点?
Imports Microsoft.Office.Interop
Dim oWord As Word.Application
Dim oDoc As Word.Document
Public Sub Create_Report()
Dim clientName As String = InputBox("Enter the [Client Contact's Name] for the report:")
Dim empName As String = InputBox("Enter the [Employee's Name] for the report:")
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add("template.dotx")
ReplaceTemplateText("<<<Contact>>>", clientName)
ReplaceTemplateText("<<<Employee>>>", empName )
oDoc.SaveAs("report.docx")
oDoc.Close()
oWord.Quit()
MsgBox("Report Complete", MsgBoxStyle.OkOnly)
End Sub
Public Sub ReplaceTemplateText(findWord As String, replaceWord As String)
'Replace text in the Template document with input text
'Body
oDoc.Content.Find.Execute(FindText:=findWord, ReplaceWith:=replaceWord, Replace:=Word.WdReplace.wdReplaceAll)
'Footer
???
End Sub
最佳答案
Word文档有很多“故事”,Document.Content
就是其中之一,并且是文档的主体。为了解决其他“故事”,有必要访问这些范围
。
使文档页眉和页脚的工作变得复杂的是,可以存在三种不同类型的页眉和页脚,其中有两种类型可以特定于文档的每个部分
。大多数文档只有一个部分,但一旦页面方向发生变化、报纸栏数或页边距发生变化,文档就会获得额外的部分。默认情况下,它们的页眉和页脚是“链接的”,因此它们都是相同的。但如果它们需要不同(例如,横向比纵向更宽,因此位置可以改变),则需要取消页眉和页脚的链接,并分别搜索它们。
因此,您可能不需要循环遍历各个部分,或循环中的所有三个 Range.Find
,但为了完整起见,我将它们包括在内。
Public Sub ReplaceTemplateText(findWord As String, replaceWord As String)
'Replace text in the Template document with input text
'Body
oDoc.Content.Find.Execute(FindText:=findWord, ReplaceWith:=replaceWord, Replace:=Word.WdReplace.wdReplaceAll)
'Footer
Dim sec as Word.Section
Dim rngFooter as Word.Range
For Each sec in oDoc.Section
Set rngFooter = sec.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
'Do rngFooter.Find.Execute
Set rngFooter = sec.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range
'Do rngFooter.Find.Execute
Set rngFooter = sec.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range
'Do rngFooter.Find.Execute
Next
End Sub
关于vb.net - 如何在 VB.net 应用程序中查找并替换 Word 文档页脚中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57189839/