|
|
|
date: Thu, 26 Jun 2008 00:10:01 -0700,
group: microsoft.public.word.oleinterop
back
Word2007 automation
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 get a runtime error "External component has thrown an exception" on this
line: tmpRange.Find.Text = "old";
I have added the correct Microsoft.Office.Interop.Word dll to my project
(version 12), so I don't think that is the problem.
Any thoughts anyone?
date: Thu, 26 Jun 2008 00:10:01 -0700
author: -kve-
|
|