Thomas Kowalski Thomas Kowalski - 2 months ago 6 Question

Word Interop replacement only works once

So I've got my VB.NET project which is intended to replace a bunch of parameters in a template document by their value. Here is an example document :You have here a an example of template
Now my problem is that my replacement function only works once. Here it is :

Private Sub AppliquerParametre(Parameter As String, Value As String)
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

This is the result :


While my code should do everything properly :

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

Would you know why it doesn't work?


OK So I found what was the problem and found how to fix it. Basically, when you first replace the content, the selection (aka the "zone" where the Word Interop App will make its search by the Find property) is reset, which makes it can't find what we are looking for the next time. Here is an illustration (bold is selection) :

On opening :
my document $field1$ $field2$

I replace with my function :
my document value1 $field2$

And my document is no more selected. So the solution is just to add


At the beginning of the replacement function. And it will work !