How to find and replace text programmatically – MS Word

n
n

nWhile working with the Add – In, came across the scenarionwhere I needed to replace the text in word document programmatically, this isnhow it can be done

n

nFollowing code finds the word occurrence andnreplaces with the desired characters in first paragraph of the document.

n

nprivate voidnFindAndReplaceText(object _wordToFind, object _replaceWith)

n

n{

n

n      

n

n string _text = Globals.ThisAddIn.Application.ActiveDocument.Paragraphs[0].Range.Text;

n

n

n

n object machtCase = true;

n

n object matchWholeWord = true;

n

n object matchWildCards = false;

n

n object matchSoundsLike = false;

n

n object nmachtAllWordForms = false;

n

n object forward = true;

n

n object format = false;

n

n object matchKashida = false;

n

n object matchDiacritics = false;

n

n object matchAlefHamza = false;

n

n object matchControl = false;

n

n object read_only = false;

n

n object visibible = true;

n

n object replace = 2;

n

n object wrap = 1;

n

n

n

n _Globals.ThisAddIn.Application.ActiveDocument.Paragraphs[0].Range.Find.Execute(ref _wordToFind,

n

n        ref machtCase,

n

n        ref matchWholeWord,

n

n        ref matchWildCards,

n

n        ref matchSoundsLike,

n

n        ref nmachtAllWordForms,

n

n        ref forward,

n

n        ref wrap,

n

n        ref format,

n

n        ref _replaceWith,

n

n        ref replace,

n

n        ref matchKashida,

n

n        ref matchDiacritics,

n

n        ref matchAlefHamza,

n

n        ref matchControl);

n

n }

n

n

n

nReference Link: – Here

n

Leave a Comment