Pages

Monday, January 9, 2012

How to find and replace text programmatically – MS Word


While working with the Add – In, came across the scenario where I needed to replace the text in word document programmatically, this is how it can be done
Following code finds the word occurrence and replaces with the desired characters in first paragraph of the document.
private void FindAndReplaceText(object _wordToFind, object _replaceWith)
{
      
 string _text = Globals.ThisAddIn.Application.ActiveDocument.Paragraphs[0].Range.Text;

 object machtCase = true;
 object matchWholeWord = true;
 object matchWildCards = false;
 object matchSoundsLike = false;
 object nmachtAllWordForms = false;
 object forward = true;
 object format = false;
 object matchKashida = false;
 object matchDiacritics = false;
 object matchAlefHamza = false;
 object matchControl = false;
 object read_only = false;
 object visibible = true;
 object replace = 2;
 object wrap = 1;

 _Globals.ThisAddIn.Application.ActiveDocument.Paragraphs[0].Range.Find.Execute(ref _wordToFind,
        ref machtCase,
        ref matchWholeWord,
        ref matchWildCards,
        ref matchSoundsLike,
        ref nmachtAllWordForms,
        ref forward,
        ref wrap,
        ref format,
        ref _replaceWith,
        ref replace,
        ref matchKashida,
        ref matchDiacritics,
        ref matchAlefHamza,
        ref matchControl);
 }

Reference Link: - Here

No comments:

Post a Comment