Word Interop 替换只能工作一次

Word Interop replacement only works once

所以我得到了我的 VB.NET 项目,该项目旨在用它们的值替换模板文档中的一堆参数。这是一个示例文档: 现在我的问题是我的替换功能只能使用一次。在这里:

Private Sub AppliquerParametre(Parameter As String, Value As String)
    Try
        objWordApp.Selection.Find.Execute(FindText:=Parameter, ReplaceWith:=Value)
    Catch ex As Exception
        MessageBox.Show("Une erreur est survenue lors de la génération du fichier : " _
            & vbCrLf & ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

这是结果:

虽然我的代码应该可以正确执行所有操作:

    OuvrirFichier(Options.DossierModeles & Options.NomModelePV) 'Open template

    AppliquerParametre("$parcelleDepartement$", Dossier.Parcelle.Departement) 'Apply some parameters
    AppliquerParametre("$parcelleCommune$", Dossier.Parcelle.Commune)
    AppliquerParametre("$parcelleSection$", Dossier.Parcelle.SectionCadastrale)
    AppliquerParametre("$parcelleNumero$", Dossier.Parcelle.NumeroParcelle)
    AppliquerParametre("$parcelleNom$", GenererListeProprietaires(", ")) 'And last field is kind of special but the problem is not here

    ExporterFichier(Options.DossierTravail & Dossier.NumeroDossier & "\PV.doc", WdSaveFormat.wdFormatDocument) 'We "save the file as" in the working directory

你知道为什么它不起作用吗?

好的所以我找到了问题所在并找到了解决方法。基本上,当您第一次替换内容时,选择(又名 "zone",Word Interop App 将通过 Find 属性 进行搜索)被重置,这使得它无法找到我们的内容寻找下一次。这是一个插图(粗体是选择):

开业时:
我的文档 $field1$ $field2$

我用我的功能替换:
我的文档值 1 $field2$

并且我的文档不再被选中。所以解决方案就是添加

 objWordApp.Documents(1).Content.Select()

替换函数开头。它会起作用的!