none
How do I replace text inside MS-Word textbox? RRS feed

  • Question

  • I wrote a Windows Forms program using C#. It contains textboxes and a data-grid.

    I want to export the data into a Word file to use the template. I added the library of Microsoft Word into my code.

    Also I created textboxes "shapes" inside the Word file and putted inside them text to be find from my c# program

    For now everything seems okay, But I'm stuck at the C# side, I can replace the normal text, but not the text inside textboxes "Inside the word file"

    And here is my code:

    private void FindAndReplace(Word.Application wordapp, object ToFindText, object replaceWithText)
    
            {
                object matchCase = true;
                object matchWholeWord = true;
                object matchWildCards = false;
                object matchSoundLike = false;
                object matchAllforms = false;
                object forward = true;
                object format = false;
                object matchKashida = false;
                object matchDiactitics = false;
                object matchAlefHamza = false;
                object matchControl = false;
                object matchread_only = false;
                object visible = true;
                object replace = 2;
                object wrap = 1;
    
                wordapp.Selection.Find.Execute(ref ToFindText,
                    ref matchCase, ref matchWholeWord,
                    ref matchWildCards, ref matchSoundLike,
                    ref matchAllforms, ref forward,
                    ref wrap, ref format, ref replaceWithText,
                    ref replace, ref matchKashida,
                    ref matchDiactitics, ref matchAlefHamza,
                    ref matchControl);
            }
    
    
            private void CreateWordDocument(object filename, object SaveAs)
            {
                Word.Application wordApp = new Word.Application();
                object missing = Missing.Value;
                Word.Document myWordDoc = null;
    
                if (File.Exists((string)filename))
    
                {
                    object readOnly = false;
                    object isVisible = false;
                    wordApp.Visible = false;
    
                    myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                        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);
    
                    myWordDoc.Activate();
    
                    //find and replave
                    this.FindAndReplace(wordApp, "<date1>", textBox2.Text);
                    this.FindAndReplace(wordApp, "<date2>", textBox3.Text);
    
                }
    
                else
                {
                    MessageBox.Show("File not found!");
                }
    
                //Svae as
                myWordDoc.SaveAs2(ref SaveAs, 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);
    
                myWordDoc.Close();
                wordApp.Quit();
                MessageBox.Show("File Created!");
    
    
             }

    • Moved by CoolDadTx Monday, September 3, 2018 4:27 PM Office related
    Monday, September 3, 2018 9:27 AM

All replies

  • Consider the next approach:

    • Use your code to replace the text that does not belong to frames.
    • Use wordApp.Selection.Document.Shapes to get the list of shapes.
    • Make a loop for all of the shapes. For each shape, get the shape.TextFrame.TextRange property.
    • For the got ranges, call range.Find.Execute.


    • Edited by Viorel_MVP Monday, September 3, 2018 11:08 AM
    • Proposed as answer by Simon Wu-MSFT Tuesday, September 11, 2018 8:44 AM
    Monday, September 3, 2018 11:07 AM
  • Hi james,

    As Viorel mentioned, you can try the code as below to check if it meets your requirement:

    public void FindReplace(List<repvals> replaceVals, string docLocation, int listLen)
            {
    
                //Opens a new Word application
                var app = new Microsoft.Office.Interop.Word.Application();
                //Opens the .docx
                var doc = app.Documents.Open(docLocation, true, false);
    
                //Selects the document
                var range = doc.Range();
    
                for (int i = 0; i < listLen; i++)
                {
    
                    //Finds the parameter, then replaces
                    range.Find.Execute(FindText: Convert.ToString(replaceVals[i].tempVal), Replace: WdReplace.wdReplaceAll, ReplaceWith: Convert.ToString(replaceVals[i].Boxes));
    
                    var shapes = doc.Shapes;
                    //Finds text within textboxes, then changes them
                    foreach (Microsoft.Office.Interop.Word.Shape shape in shapes)
                    {
                        var initialText = shape.TextFrame.TextRange.Text;
                        var resultingText = initialText.Replace(Convert.ToString(replaceVals[i].tempVal), Convert.ToString(replaceVals[i].Boxes));
                        shape.TextFrame.TextRange.Text = resultingText;
                    }
    
                }
                //prints document
                doc.Save();
                doc.Close();
    
                //fully closes Word
                Marshal.ReleaseComObject(app);
            }

    For more information, please review the following link: Finding & Replacing text in a MS Word textbox 

    Best Regards,

    Yuki


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    • Proposed as answer by Simon Wu-MSFT Tuesday, September 11, 2018 8:44 AM
    Tuesday, September 4, 2018 10:49 AM
    Moderator
  • Hi James,

    Thanks for your asking. Please remember to mark the replies(Include your solution) as answers if they helped and please help us close the thread.

    Thank you for understanding. If you have any question, or update, please feel free to let us know.
    I wish you a happy life!

    Best Regards,

    Yuki


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    Monday, September 10, 2018 2:26 AM
    Moderator