I have a word document which has a text box. When i run an automated find and replace its matching in the main document, but not match anything in the Text Box. How do i tell the find and replace function to include Text Boxes.
Word.Range range = objDoc.Content;
object findtext = Field;
object findreplacement = Value;
object findwrap = WdFindWrap.wdFindContinue;
object findreplace = WdReplace.wdReplaceAll;
range.Find.Execute(findtext, missing, missing, missing, missing, missing, missing, findwrap, missing, findreplacement, findreplace);
I suspect i need to change the range = objDoc.content line.
If your text boxes are inline with your text, then you can use Find and Replace to locate and replace them. All you need to do is to display the Replace tab of the Find and Replace dialog box and, in the Find What box, enter ^g.
When you need to find and replace text in a text box in Excel, you can use the Find and Replace dialog box to do so. To open the Find and Replace dialog box, click the Home tab, then click Find & Select in the Editing group, and then click Find. Or, you can press Ctrl+F on your keyboard.
How can you find text without using the Find and Replace dialog box? To find an item, click in the search field of the Navigation pane and begin typing the characters for the search criteria. As Word finds matches, it begins to display items in the Results tab of the Navigation pane.
From the Home tab, click the Replace command. You can also press Ctrl+H on your keyboard. The Find and Replace dialog box will appear. Type the text you want to find in the Find what: field.
Slightly messy but this worked for me:
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
namespace ConsoleApplication7
{
class Program
{
static void Main()
{
const string documentLocation = @"C:\temp\Foo.docx";
const string findText = "Foobar";
const string replaceText = "Woo";
FindReplace(documentLocation, findText, replaceText);
}
private static void FindReplace(string documentLocation, string findText, string replaceText)
{
var app = new Application();
var doc = app.Documents.Open(documentLocation);
var range = doc.Range();
range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText);
var shapes = doc.Shapes;
foreach (Shape shape in shapes)
{
var initialText = shape.TextFrame.TextRange.Text;
var resultingText = initialText.Replace(findText, replaceText);
shape.TextFrame.TextRange.Text = resultingText;
}
doc.Save();
doc.Close();
Marshal.ReleaseComObject(app);
}
}
}
Before:
After:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With