none
How to replace word in word document. RRS feed

  • Question

  • Dear All,

    I have one template in word(abc.docx). In the word template file there words #Name# and #Version#.

    I want to replace this word with actual value and Save AS in different location

    Can anyone please help me how to resolve this issue ?

    Thanks,

    Harish Patil

    Thursday, March 14, 2013 10:42 AM

Answers

  • Hi Harish Patis,

    You can use Find.Execute method to replace the words with actual value and then use  SaveAs method to  save the word document as a new location.

    I create some code snippets as below:

     private void Replacewords(string findtext,string wordfilepath,string replacestr,string newfilepath)
            {
                Word.Application wordapp = new Word.Application();
                Word.Document doc = wordapp.Documents.Open(wordfilepath);
                if(doc.Range().Find.Execute(findtext, ReplaceWith: replacestr))
                {
                    MessageBox.Show("Replace successfully");
                    // save as word documemt to new location
                    doc.SaveAs2(newfilepath);
                }
            }

    I hope this can help you.

    Thanks.

    • Marked as answer by WOW 999999 Wednesday, March 20, 2013 3:02 PM
    Monday, March 18, 2013 10:09 AM

All replies

  • Have you tried recording the actions in a macro in order to get the basic syntax? That would normally be the first step...

    If you require further assistance:

    Which version of Word is involved?

    Which programming environment do you use?


    Cindy Meister, VSTO/Word MVP, my blog

    Friday, March 15, 2013 2:38 PM
    Moderator
  • Hi Harish Patis,

    You can use Find.Execute method to replace the words with actual value and then use  SaveAs method to  save the word document as a new location.

    I create some code snippets as below:

     private void Replacewords(string findtext,string wordfilepath,string replacestr,string newfilepath)
            {
                Word.Application wordapp = new Word.Application();
                Word.Document doc = wordapp.Documents.Open(wordfilepath);
                if(doc.Range().Find.Execute(findtext, ReplaceWith: replacestr))
                {
                    MessageBox.Show("Replace successfully");
                    // save as word documemt to new location
                    doc.SaveAs2(newfilepath);
                }
            }

    I hope this can help you.

    Thanks.

    • Marked as answer by WOW 999999 Wednesday, March 20, 2013 3:02 PM
    Monday, March 18, 2013 10:09 AM