0
votes

I'm trying to replace parts of text in the footer. I'm using Range.Find to find the text and replace it. During the debugging I've set up some breakpoints so I can check the Range.Text of the footer before and after the change. It seems to be doing its job. When I check the Rang.Text in the Locals window, the text is changed how I want it to change. The problem is that it doesn't update the document.

When I try it a second time, the Range.Text still has the changes I made but it won't update the document.

I've tried doing this with the main body of the document and it works just fine. I'm not sure what I'm missing here.

I'm trying it on some saved documents. I do have to unprotect the footer so that I doesn't give me an exception when I try to find and replace the text.

Anyone know if there is some sort of security I'm missing?

Here is my code:

Word.Range docRange = currentDoc.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
docRange.Find.ClearFormatting();
docRange.Find.Text = find;
docRange.Find.Replacement.ClearFormatting();
docRange.Find.Replacement.Text = replace;

object replaceAll = Word.WdReplace.WdReplaceAll;
docRange.Find.Execute(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                      ref replaceAll, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

If you need any more code, let me know.

EDIT: I tried moving the footer to a new document, saving it and then opening the new document with the debugger and it seems to work fine with the new document. Still doesn't work with the original document though.

1

1 Answers

1
votes

I was able to fix my problem. I'm not too sure of the actual problem was, but my guess was that the footer was formatted very oddly. So I decided to change the code to go through every Footer in the Footer section and that seemed to have resolved my problem.

Here is what I changed the code to for anyone else, hope it helps:

foreach (Word.Section wordSection in currentDoc.Sections)
{
    foreach (Word.HeaderFooter wordFooter in wordSection.Footers)
    {
        Word.Range docRange = wordFooter.Range; 

        docRange.Find.ClearFormatting();
        docRange.Find.Text = find;
        docRange.Find.Replacement.ClearFormatting();
        docRange.Find.Replacement.Text = replace;

        object replaceAll = Word.WdReplace.wdReplaceAll;
        docRange.Find.Execute(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                  Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                  ref replaceAll, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    }
}

If someone could hint at why it was necessary to do these loops, it would be helpful though.