Hi,
I have to find/replace text from a word document. It works fine for plain
text spread through the document, however when the text is in a textbox, the
standard find/replace approach doesn't reach it.
I found a vba solution, however since I am working in C#, I would like to
find a solution in C#. The word document is in 2007 format and my visual
studio is 2010. I am using .Net Framework 3.5, but if required, I can
consider moving to 4.0.
Here is the code for the find/replace that only works with plain text (not
in word textbox objects):
object Missing = System.Reflection.Missing.Value;
object fileToOpen = (object)@"c:\doc.docx";
object fileToSave = (object)@"c:\doc.docx";
Word.Application app = new Word.ApplicationClass(); Word.Document doc = new
Word.Document();
try
{
doc = app.Documents.Open(ref fileToOpen,
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, ref Missing, ref Missing);
object replaceAll = Word.WdReplace.wdReplaceAll;
app.Selection.Find.ClearFormatting();
app.Selection.Find.Text = "MyTextForReplacement";
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.Replacement.Text = "Found you!";
app.Selection.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);
I also tried using the below code, but didn't work as well:
foreach(Word.Shape s in app.ActiveDocument.Shapes)
{
if(s.TextFrame.HasText >= 1) //The value is always 0 or -1, and even leaving 0 go forward,
// it doesn't work, because there is no text in there...
{
foreach(Word.Field f in s.TextFrame.TextRange.Fields)
{
switch( f.Type)
{
.
. //I never reached this point
.
}
}
}
Any help will be appreciated...
Thanks,
--
Roberto Lopes