How to write Text directly in a Word Textbox using C#?

3.4k Views Asked by At

I want to write some text to an existing word textbox using C#. Actually nothing happens and I don't know why. Maybe someone can help me?

My method:

Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

void SearchTextBox(Microsoft.Office.Interop.Word.Document oDoc, string name, string newContent)
{
    foreach (Microsoft.Office.Interop.Word.Shape shape in oDoc.Shapes)
    {
        if (shape.Name == name)
        {
            shape.TextFrame.TextRange.Text = newContent;
            return;
        }
    }
}

Call:

SearchTextBox(oWordDoc, "tbTest", "Please write some Text");

Word file

1

There are 1 best solutions below

0
On

Here the solution:

using Word = Microsoft.Office.Interop.Word

var WORD = new Word.Application();
Word.Document doc   = WORD.Documents.Open(@PATH_APP);
doc.Activate();

foreach (Microsoft.Office.Interop.Word.Shape shape in WORD.ActiveDocument.Shapes)
{
    if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
        if (shape.AlternativeText.Contains("MY_FIELD_TO_OVERWRITE_OO1"))
        {       
             shape.TextFrame.TextRange.Text="MY_NEW_FIELD_VALUE";
        }

    }
}

doc.Save();