Programmatically replace formatted text in paragraphs (links, content)

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

with \t\r

in a string.

First try:

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

      

It's only good for text, but if I have links or content in paragraphs it doesn't work.

Second try:

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

      

It's not 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 will not succeed, because paragraph 1 is deleted (put the text from paragraph [1] and paragraph [2] in one paragraph)

+3


source to share


1 answer


For future readers:



It is possible to use OpenXml. OpenXml can be extracted directly from the addin code. This approach is universal, it allows for faster and more accurate manipulation of the document.

0


source







All Articles