Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Programmatically replace word with the help of Word Automation

Hi,

In My last two posts I talked about

·         How to open and close a word document programmatically.

·         How to save a word document in different programmatically.

In this post I will talk about how we can replace words in the word document. Many a times we will find ourselves in situation where by we have a word document with a predefined template where some of the words need to be replaced by user entered values. This can be easily performed with the help of word automation.

To replace words in the word document we first need to open the word document programmatically. The following code snippet function shows how we can replace the word in the document. If we want to replace the word inside a selection then we need to pass the range of the selection or we need to pass the full word document in the

  public static void ReplaceRange(Microsoft.Office.Interop.Word.Range range, object findText,

                                                 object replaceText)

        {

            object item = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;

            object whichItem = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;

            object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

            object forward = true;

            object matchAllWord = true;

            object missing = System.Reflection.Missing.Value;

 

            range.Document.GoTo(ref item, ref whichItem, ref missing, ref missing);

 

            range.Find.Execute(ref findText, ref missing, ref matchAllWord,

               ref missing, ref missing, ref missing, ref forward,

               ref missing, ref missing, ref replaceText, ref replaceAll,

               ref missing, ref missing, ref missing, ref missing);

        }

 

Here we first go to the first page in the document and then execute the find with a replace text. We also pass the optional parameter to replace all keyword in the system.  To call this function we need to pass the word document(or a range selection of word document) along with object of the find text and replace text and the function will replace all the words in the given word document.

Vikram

4 Comments

  • This is a really useful procedure.

  • please post a solution for the same thing with out using microsoft.office.interop.word

  • Can u give me a solution to replace a word in Word Document without using COM object like Microsoft.Office.Interop.Word

  • Thanks fo rthis article. i am using the ReplaceRange method to replace a stringwith a string of 1000 characters, But its throwing an exception "string length is too long", if the length of the string is more than 255 characters(255 is fine).
    Can you help me on this please?

    Thanks,
    a c# dummy

Comments have been disabled for this content.