Hi everybody,
Now, I have to create a Word file from a word template, i have faced a difficult problem when replace a text on Word file.
In my file Word template, I have 5 lines with the text is "Name_of_Applicant". (Please note that the BOOKMARK will not use in this template)
In my C# code, I would like to do as follows:
1. Find the text "Name_of_Applicant" and Replace it.
2. I do Foreach(Word.Range tmpRange in oWordDoc.StoryRanges) { ... do something ... }. In the FOR loop, I will replace 5 lines as "Name_1", "Name_2", .... , "Name_5".
private void OpenWord_Click(object sender, EventArgs e)
{
object oMissing = System.Reflection.Missing.Value;
oWord = new Word.Application();
oWordDoc = new Word.Document();
oWord.Visible = true;
oWord.NormalTemplate.Saved = true;
oTemplatePath = "D:\\Template.doc";
oWordDoc = oWord.Documents.Open(ref oTemplatePath, ref oMissing, ref readOnly, ref readOnly, ref oMissing, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
object findText = "Name_of_Applicant";
try
{
int index_name = 0;
object oReplace = "Name_" + index_name.ToString();
foreach (Word.Range tmpRange in oWordDoc.StoryRanges)
{
//The Paramater 11 is the REPLACED text
if (oWord.Application.Selection.Find.Execute(ref findText, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oReplace, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing))
{
index++;
}
}
}
catch
{
MessageBox.Show("The text could not be located.");
}
}
The code above is only one of many different way that I have tried, but the above code only replace the FIRST LINE. The 4 lines left was not replaced.
Thank you very much for your help.
Cuong