c# – Replace a variable within a Word file

Question:

I'm trying to make in C# (Windows Form application) print a Word .doc but changing some @Nome type @Nome for a string .

In short, I have a contract and I need to print it. Informing specific fields, I already have a template Word file and I just need to fill it in with the data.

I'm doing it like this:

public void PreencherPorReplace(string CaminhoDocMatriz)
{
    //Objeto a ser usado nos parâmetros opcionais
    object missing=System.Reflection.Missing.Value;

    Word.Application oApp=new Word.Application() ;

    object template = CaminhoDocMatriz;

    Word.Document oDoc = oApp.Documents.Add(ref template , ref missing,
                                            ref missing, ref missing);

    //Troca o conteúdo de alguns tags
    Word.Range oRng= oDoc.Range(ref missing ,ref missing );

    object FindText = "@Nome";
    object ReplaceWith="Teste";
    object MatchWholeWord = true;
    object Forward = false;

    oRng.Find.Execute( ref FindText, ref missing, ref MatchWholeWord,
                       ref missing, ref missing, ref missing, ref Forward,
                       ref missing, ref missing, ref ReplaceWith, ref missing,
                       ref missing, ref missing, ref missing, ref missing);


    oApp.Visible = true;
}

However, it only replaces the @Nome 1 time.

Answer:

The syntax of the Find.Execute method is:

bool Execute(
    ref Object FindText,
    ref Object MatchCase,
    ref Object MatchWholeWord,
    ref Object MatchWildcards,
    ref Object MatchSoundsLike,
    ref Object MatchAllWordForms,
    ref Object Forward,
    ref Object Wrap,
    ref Object Format,
    ref Object ReplaceWith,
    ref Object Replace,
    ref Object MatchKashida,
    ref Object MatchDiacritics,
    ref Object MatchAlefHamza,
    ref Object MatchControl
)

In the replace parameter, specify the wdReplaceAll constant:

object replace = WdReplace.wdReplaceAll;

//...

oRng.Find.Execute( ref FindText , ref missing,ref MatchWholeWord , 
                   ref missing,ref missing,ref missing,ref Forward,
                   ref missing,ref missing,ref ReplaceWith ,ref replace,
                   ref missing,ref missing,ref missing,ref missing);
Scroll to Top