2

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

daniele3004
  • 13,072
  • 12
  • 67
  • 75
rejoin14
  • 57
  • 1
  • 6
  • Is it possible that the textbox is within one of the base level shapes? You may need to get a little recursive if the shapes can be nested within other shapes (just guessing, haven't worked with word like this) – Justin Packwood Feb 26 '16 at 11:57
  • This looks like an ActiveX control from VBA UserForms type of text box, not a Shape, which explains why your code is not showing any effect. Unless you have a really good reason for using this I don't recommend it, especially not for C#. A content control might be the better solution. Or perhaps a form field if the document can be protected for forms. Or draw a text box, then your code could work... – Cindy Meister Feb 26 '16 at 15:19
  • Found a workaround. Using Bookmark to write to the textbox coordinates – rejoin14 Feb 29 '16 at 10:32

1 Answers1

1

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();
daniele3004
  • 13,072
  • 12
  • 67
  • 75