3
votes

I am trying to create a Word addin. How can I programmatically replace text in paragraphs? I need to replace: \r to \t\r in line.

First attempt:

Globals.ThisAddIn.Application.ActiveDocument.Paragraphs[nr].Range.Text = 
    Globals.ThisAddIn.Application.ActiveDocument
    .Paragraphs[nr].Range.Text.Replace("\r", "\t\r");

Its good only for text, but if I have links or content in paragraphs its doesn't work.

Second attempt:

Globals.ThisAddIn.Application.ActiveDocument.Paragraphs[nr].Range.Find.Execute("\r");
Globals.ThisAddIn.Application.Selection.Text = "\t"

This fails like 1

Third attempt:

Globals.ThisAddIn.Application.Selection.Find
    .Execute("\r", Wrap: Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue);

Word.Find findObject = Application.Selection.Find;
//   findObject.ClearFormatting();
findObject.Text = "\r";
//   findObject.Replacement.ClearFormatting();
findObject.Replacement.Text = "\t\r"

object replaceAll = Word.WdReplace.wdReplaceAll;
findObject.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);

This fails one more, because delete 1 paragraph (put text from paragraph[1] and paragraph[2] to one paragraph)

1
Take a moment to read through the editing help in the help center. Formatting on Stack Overflow is different than other sites. The better your post looks, the easier it will be for users to help you. - gunr2171
Can you elaborate on how your code "doesn't work" or "fails"? What were you expecting, and what actually happened? If you got an exception, post the line it occurred on and the exception details. - gunr2171

1 Answers

0
votes

For the future readers:

It is possible using OpenXml. OpenXml can be extracted right from addin's code. This approach is universal, it allows to manipulate with a document faster and more precisely.