替换值大于256个字符的单词后,无法替换任何后续单词

时间:2014-12-06 15:23:03

标签: c# ms-word office-interop

以下方法在替换值大于256个字符的单词后无法替换任何后续单词

我的预感是,以下行会破坏我的搜索并替换后续单词的上下文:

wordApp.Application.Selection.Text = (string)replaceValue;

public void ReplaceTextInWordDoc(Application wordApp, Object searchValue, Object replaceValue)
{
    object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
    object missing = System.Reflection.Missing.Value;
    wordApp.Application.Selection.Find.ClearFormatting();
    wordApp.Application.Selection.Find.Text = (string)searchValue;
    wordApp.Application.Selection.Find.Replacement.ClearFormatting();

    if (replaceValue.ToString().Length < 256) // Normal execution
    {
        wordApp.Application.Selection.Find.Replacement.Text = (string)replaceValue;
        wordApp.Application.Selection.Find.Execute(
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref replaceAll, ref missing, ref missing, ref missing, ref missing);
    }
    else  // Some real simple logic!!
    {
        wordApp.Application.Selection.Find.Execute(
        ref searchValue, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);

        wordApp.Application.Selection.Text = (string)replaceValue;//****
    }
}


private void Translate(Dictionary<string, string> requestMap, Application wordApp)
{
    foreach (var entry in requestMap)
    {
        ReplaceTextInWordDoc(wordApp, entry.Key, entry.Value);
    }
}

1 个答案:

答案 0 :(得分:0)

更改&#34;否则//一些真正的简单逻辑&#34;使用以下代码阻止

                       int loop = (replaceValue.Length / 150) + ((replaceValue.Length % 150) == 0 ? 0 : 1);

                        for (int k = 0; k < loop; k++)
                        {
                            int length = k == (loop - 1) ? (replaceValue.Length - k * 150) : 150;
                            string replaceV = replaceValue.Substring(k * 150, length);

                            object toReplace = replaceText;

                            if (k == (loop - 1))
                            {
                                srng.Find.Replacement.Text = replaceV;
                            }
                            else
                            {
                                srng.Find.Replacement.Text = replaceV + replaceText;
                            }

                            srng.Find.Execute(
                                ref missing, ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref replaceAll, ref missing,
                                ref missing, ref missing, ref missing);


                        }