Nick_F Nick_F - 18 days ago 9
C# Question

Define range to text inside table cell

I use Word Interop to insert some text in a cell of a table. After adding the text, I want insert a bookmark just to that text. At the moment I can select the entire cell and insert a bookmark to it, but I want the bookmark to belong only to the text.

var cell = tb.Cell(row, col);
cell.Range.Text = "MyText";
Microsoft.Office.Interop.Word.Range rng = tb.Cell(row, col).Range;
rng.Select(); // this line is useful to see the range where bookmark will be placed
rng.Bookmarks.Add("BookmarkName", rng);

Answer

The range inside the cell still includes the end-of-cell mark. You need to adjust the range accordingly by moving the end just before adding the bookmark:

rng.MoveEnd Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1
rng.Select(); // this line is useful to see the range where bookmark will be placed
rng.Bookmarks.Add("BookmarkName", rng);