Cannot find/replace text in Word header RRS feed

  • Question

  • In a nutshell, I have a template docx and we have unique key words to search for to replace text with the text required to send out this document.

    I have created a quick project to show this and the problem I do not understand on how to overcome.

    I am using VS2010 C# and Word 2007.

    In my word doc I simply have a header and body, with the text '%@R' as the specific text if both section.   I have tried changing the specific text but that did not work either.  On a side note, in Office 2003, this worked with no issue, so it is on the upgrade to Office 2007.


    Now when I run my small code snippet provided, the body text is updated, but the header is not.

     Word.Application oWordApp = new Word.Application();
                Word.Document oWordDoc = new Word.Document();
                Word.Application wA = new Word.Application();
                    oWordDoc = oWordApp.Documents.Open(@"C:\TestHeader.docx", Visible: true, ReadOnly: false);
                    Word.Range oWR = oWordDoc.Range(oWordDoc.Sections[1].Range.Start, oWordDoc.Sections[1].Range.End);
                    oWR.Find.Text = "%@R";
                    oWR.Find.Replacement.Text = "Jeff";
                    oWR.Find.Execute(Replace: Word.WdReplace.wdReplaceAll, Format: true, MatchCase: true);//, MatchWholeWord: true);
                    Word.HeaderFooter objHeader = oWordDoc.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
                    objHeader.Range.Find.Text = "%@R1".Trim();
                    objHeader.Range.Find.Replacement.Text = "Crystal";
                    objHeader.Range.Find.Execute(Replace: Word.WdReplace.wdReplaceAll, Format: true, MatchCase: true, MatchWholeWord: true);               
                catch (Exception r)

    Does anyone see what the problem witht the header insert?  I've looked and researched and cannot see what the difference is.



    Friday, April 5, 2013 2:11 PM

All replies

  • Try removing the ".Trim()" on this line:  objHeader.Range.Find.Text = "%@R1".Trim();

    Kind Regards, Rich ...

    Friday, April 5, 2013 3:51 PM
  • The MSDN article will helpful for you.
    Wednesday, April 10, 2013 6:13 AM
  • A couple of suggestions which mean you don't need to search the header:

    1. Format the string in the body of the document with a unique style, then use a STYLEREF field in the header to replicate the content;

    2. Create a custom document property and update that with your code. In the document, use DOCPROPERTY fields to replicate the custom document property values. Issuing .Fields.Update and a print preview toggle on/off should be enough to update the fields. If, as described in (1) you use a STYLEREF field linked to a Style applied to the DOCPROPERTY field in the body of the document, you don't need the print preview toggle on/off.

    Paul Edstein
    [MS MVP - Word]

    Wednesday, April 10, 2013 6:55 AM