2013-02-14 50 views
0

我試圖替換頁腳中的部分文字。我使用Range.Find來查找文本並將其替換。在調試過程中,我設置了一些斷點,以便在更改之前和之後檢查頁腳的Range.Text。它似乎在做它的工作。當我在Locals窗口中檢查Rang.Text時,文本被改變了,我希望它改變。問題是它不更新文檔。替換後文字不會更新

當我第二次嘗試時,Range.Text仍然有我所做的更改,但它不會更新文檔。

我試過這樣做與文檔的主體,它工作得很好。我不確定我在這裏錯過了什麼。

我試圖在一些保存的文件上。我必須解除頁腳的保護,以便在我嘗試查找和替換文本時不會給予例外。

任何人都知道我是否缺少某種安全性?

這裏是我的代碼:

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); 

如果您需要更多的代碼,讓我知道。

編輯:我試着將頁腳移動到一個新文檔,保存它,然後用調試器打開新文檔,它似乎與新文檔一起工作正常。儘管如此,仍然 不適用於原始文檔。

回答

1

我能解決我的問題。我不太確定實際問題是什麼,但我的猜測是頁腳格式非常奇怪。所以我決定更改代碼來遍歷頁腳部分的每個頁腳,這似乎解決了我的問題。

這是我改變了代碼,爲其他人,希望它有助於:

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); 
    } 
} 

如果有人能在爲什麼有必要做這些循環暗示,這將是有益的,但。