General discussion

Locked

Word2007 automation with C#

By koenvermaelen ·
I want to do some programmed automation with Office2007, using C#.
For example, a simple search and replace in Word2007. I use this code:

Word2007.Application word =
new Word2007.Application();
Word2007.Document doc =
new Word2007.Document();

object missing = Type.Missing;

try
{
object fileName = "test.doc";
object varFalse = false;
doc = word.Documents.Open(ref fileName,
ref missing, ref varFalse, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);

doc.Activate();

foreach (Word2007.Range tmpRange in doc.StoryRanges)
{
if (tmpRange == null) continue;
tmpRange.Find.Text = "old";
tmpRange.Find.Replacement.Text = "new";
tmpRange.Find.Wrap = Word2007.WdFindWrap.wdFindContinue;

replaceAll = Word2007.WdReplace.wdReplaceAll;
tmpRange.Find.Execute(ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing,
ref missing, ref missing);
}

doc.Save();
doc.Close(ref missing, ref missing,
ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
}
catch (Exception ex)
{
doc.Close(ref missing, ref missing,
ref missing);
word.Application.Quit(ref missing,
ref missing, ref missing);
MessageBox.Show("Error:\n" + ex.Message, "Error message");
}


The code worked fine with Word2003, but with Word2007 the replacement isn't done anymore...
I have the correct Microsoft.Office.Interop.Word dll to my project (version 12), so I don't think that is the problem.

Any thoughts anyone?

This conversation is currently closed to new comments.

0 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Back to Windows Forum
0 total posts (Page 1 of 1)  

Related Discussions

Related Forums