Search code examples
c#ms-wordms-officeadd-inoffice-interop

Word Interop Copy Formatted Text of Table Cell


I am writing an addin for word to automate editing of a protocol template.

In the template is a table and I want to extract/copy the formated text of a cell inside this table.

Right now I am doing it this way:

Range formattedText = agendaTable.Rows[i].Cells[1].Range;
string temp = formattedText.WordOpenXML;

Later I want to paste the text into another tables cell:

otherTablesRow.Cells[1].Range.InsertXML(temp);

The formating is correct, except a linebreak ("\r\a") at the end, which comes from the range where I extract the text out of the cell. Seems like word uses the linebreak to mark the cells end.

So after inserting the text into the other tables cell, I have two linebreaks. How can I avoid that duplication of linebreaks? Does someone know an alternative method to retrieve the cells content?


Update: May be I ask my question in another way.

My overall problem is to copy more than one formatted text range to memory and later paste it somewhere in the same document.


Solution

  • Try the following code, it copies the text and formatting from one cell to another:

    var copyFrom = agendaTable.Rows[i].Cells[1].Range;
    var copyTo = otherTablesRow.Cells[1].Range;
    
    copyFrom.MoveEnd(WdUnits.wdCharacter, -1);
    copyTo.FormattedText = copyFrom.FormattedText;
    

    There is an end of cell character in the agendaTable Range that messes up the target cell in your example; using MoveEnd we copy everything except the end of cell character (last character).