错误"字符串参数太长".在microsoft.office.interop.word.find.execute

use*_*351 5 c# asp.net office-interop

我想用C#创建一个世界文档.所以这是我替换word文档变量的代码.

 private void FindAndReplace(Microsoft.Office.Interop.Word.Application WordApp, object findText, object replaceWithText) 
 {
    try {
        object matchCase = true;
        object matchWholeWord = true;
        object matchWildCards = false;
        object matchSoundsLike = false;
        object nmatchAllWordForms = false;
        object forward = true;
        object format = false;
        object matchKashida = false;
        object matchDiacritics = false;
        object matchAlefHamza = false;
        object matchControl = false;
        object read_only = false;
        object visible = true;
        object replace = 2;
        object wrap = 1;

        WordApp.Selection.Find.Execute(ref findText,
        ref matchCase, ref matchWholeWord,
        ref matchWildCards, ref matchSoundsLike,
        ref nmatchAllWordForms, ref forward,
        ref wrap, ref format, ref replaceWithText,
        ref replace, ref matchKashida,
        ref matchDiacritics, ref matchAlefHamza,
        ref matchControl);
    } catch (Exception error) {
        lblerror.Visible = true;
        lblerror.Text = error.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是在这里如果"replaceWithText"过于孤立就会出现错误而且它说

String parameter too long.
Run Code Online (Sandbox Code Playgroud)

那么如何更换长串呢?

ale*_*lex 5

而不是使用Find.Execute()替换:找到文本,获取其位置,插入新文本.这不会限制你在新字符串的长度.

替换特定文本的示例

// Find text 
Range range = doc.Content;
range.Find.Execute(findText);
range.Text = "new text...";
Run Code Online (Sandbox Code Playgroud)

在特定文本后添加新文本的示例

// Find text 
Range range = doc.Content;
range.Find.Execute(findText);
// Define new range 
range = doc.Range(range.End + 1, range.End + 1);
range.Text = "new text...";
Run Code Online (Sandbox Code Playgroud)


小智 0

只需将长字符串拆分为例如子字符串数组、字符数组(无论您想要什么)并多次调用 FindAndReplace(..) (对于所有新生成的数组项)。