Jammy
Jammy

Reputation: 789

C# word automation find and replace long text field

I have a function to find and replace a text placeholder inside a word document. Which works fine for short text strings. Does nothing however when attempting to replace with larger text strings i.e. a paragraph of text.

DocReplaceField(ref Word.Document objDoc, string Field, string Value)
{
   object missing = System.Reflection.Missing.Value;

   Word.Range range = objDoc.Content;

   object findtext = Field;
   object f = false;
   object findreplacement = Value;
   object findforward = false;
   object findformat = true;
   object findwrap = WdFindWrap.wdFindContinue;
   object findmatchcase = false;
   object findmatchwholeword = false;
   object findmatchwildcards = false;
   object findmatchsoundslike = false;
   object findmatchallwordforms = false;
   object findreplace = WdReplace.wdReplaceAll;

   range.Find.Execute(
       findtext,
       findmatchcase,
       findmatchwholeword,
       findmatchwildcards,
       findmatchsoundslike,
       findmatchallwordforms,
       findforward,
       findwrap,
       findformat,
       findreplacement,
       findreplace,
       missing,
       missing,
       missing,
       missing);
}

This works find if i try replacing "[placeholder]" with "Something" but how do i replace "[placeholder]" with

"Nullam non lorem sapien, et imperdiet sapien. Curabitur vestibulum justo eu enim bibendum vulputate. Integer vel velit non elit molestie auctor non ut nisi. Suspendisse potenti. Donec augue nulla, vestibulum a pulvinar id, scelerisque quis mauris. Integer eget ullamcorper velit. Sed at purus sit amet felis pulvinar dictum at non neque. Praesent laoreet mauris id sem venenatis pellentesque."

for example

UPDATE:

The issue seems to be that word's find and replace cannot replace with more than 255 characters. The search is matching the placeholder but cannot actually replace the text. Does anyone have an example of calling the find to locate the placeholder but then manually selecting the text and inserting new text. Instead of using the word find and replace.

Upvotes: 2

Views: 7882

Answers (6)

Disha Bhatt
Disha Bhatt

Reputation: 74

Word.Application.Selection.Find.Execute does not support more than 255 characters in replace text .

Hence , we need to first select the word we want to replace than replace the selected text with the desired text.

object missing = System.Reflection.Missing.Value;

  wordApp.Application.Selection.Find.Execute(findText, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,
                                 missing, missing, missing);


            wordApp.Application.Selection.Text = (String)(replaceText);
            wordApp.Application.Selection.Collapse();

Upvotes: 1

Dylan
Dylan

Reputation: 147

Here is a quick and short solution to your problem. If the range.Find.Execute method does not work for more than 255 characters than you can simply scan the document manually and search for the text, than issue the replacement from the string of text.

To use the code below you must include the following:

Using Word = Microsoft.Office.Interop.Word;
Using System.Text.RegularExpressions;   //This is used for Regex

You need to add in the Microsoft Word object library. Below is the code from start to finish.

string filePath = @"C:\YourfilePathHere";
string findText = "Your text to locate goes here";
string replaceText = "The replacement text longer than 255 characters";
Word.Application fileOpen = new Word.Application;
Word.Document doc = fileOpen.Documents.Open(filePath, ReadOnly: false);
foreach (Word.Paragraph para in doc.Paragraphs) {
   Word.Range paraRange = para.Range;
   string text = paraRange.Text;
   Regex regex = new Regex(findText);
   string final = regex.Replace(text, replaceText);
   paraRange.Text = final;
}

Now the above will have replaced your text with an unlimited sized replacement.

Upvotes: 1

Borja
Borja

Reputation: 23

What I do is to break the replacement string into smaller pieces, and add the placeholder in the end of every string except for the last one, and then repeat the replace command as many times as string pieces. It will work for smaller strings as well, so you don't have to use a different method:

string acierto; // where acierto is my placeholder
string[] cadenas;
cadenas = BSV.Funciones.ParteCadenas(valor, 170); // function to split a string into 170 character pieces

for (int xx = 0; xx < cadenas.Length; xx++)
{
    if (xx < cadenas.Length - 1) cadenas[xx] += acierto;
    parrafo.Range.Find.Execute(acierto, nulo, nulo, nulo, nulo, nulo, nulo, nulo, nulo, cadenas[xx], WdReplace.wdReplaceAll, nulo, nulo, nulo, nulo);
}

Upvotes: 2

Dirk Vollmar
Dirk Vollmar

Reputation: 176249

It's quite simple to replace text: Once you found it, the range object will contain the found portion of the document. You need to first delete the found text, then insert the new one:

range.Find.Execute(findtext, findmatchcase, findmatchwholeword, 
    findmatchwildcards, findmatchsoundslike, findmatchallwordforms, findforward, 
    findwrap, findformat, findreplacement, findreplace, missing, 
    missing, missing, missing);

range.Delete();
range.Text = "This is the new content.";

Upvotes: 2

MrFox
MrFox

Reputation: 5126

Your problem is likely the search for a multiline text.

Try adding "\r\n" every time you cross a line, also you can't just make a multiline string like that, you need to use @ at the start:

@"firstLine\r\n
second";

Other than that I don't see any multiline options in the execute method. Note that the arguments in the execute method all have a default value, you can use named parameters and leave out the ones you don't use.

Also please edit your question multiple lines are indeed causing the problem.

Edit: Instead of giving the replacement text as an argument you should set it afterwards. http://social.msdn.microsoft.com/forums/en-US/vsto/thread/9c50450e-9579-4e89-8e9c-8c84c8319d0b

range.Execute(... arguments ...);
range.Text = "Replacement text more than 255 characters";

Another option is to use ^c as replacement text which will hint Word to use whatever text is placed on the clipboard as replacement text. http://word.tips.net/T000021_Replacing_Long_Blocks_of_Text.html

System.Windows.Forms.Clipboard.SetText("Replacement text longer than 255 chars");
range.Execute(... replacementText: "^c ...); // don't actually know where you enter your replacement text :P

Upvotes: 0

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

Can you try using Word Bookmarks instead of Find and Replace?

An example snipper -

object oBookMark = "MyBookmark";
oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

Upvotes: 0

Related Questions