0

I am trying to refer to an existing end note in word from a table cell in the document thus (using netoffice):

row.Cells[2].Range.InsertCrossReference(WdReferenceType.wdRefTypeEndnote, WdReferenceKind.wdEndnoteNumberFormatted, 1);

However, this appears to put the reference at the beginning of the row, rather than at the end of the text at Cell[2]. In general, I haven't found much help on the web on how to programmatically add a cross-reference to footnotes and end notes. How can I get the reference to display properly?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Sundar
  • 43
  • 4

1 Answers1

2

The problem is that the target Range specified in your code snippet is the entire cell. You need to "collapse" the Range to be within the cell. (Think of the Range like a Selection. If you click at the edge of a cell, the entire cell is selected, including its structural elements. If you then press left-arrow, the selection is collapsed to a blinking I-beam.)

To go to the start of the cell:

Word.Range rngCell = row.Cells[2].Range;
rngCell.Collapse(Word.WdCollapseDirection.wdCollapseStart);
rngCell.InsertCrossReference(WdReferenceType.wdRefTypeEndnote, WdReferenceKind.wdEndnoteNumberFormatted, 1);

If the cell has content and you want it at the end of the content, then you use wdCollapseEnd instead. The tricky part about that is this puts the target point at the start of the next cell, so it has to be moved back one character:

Word.Range rngCell = row.Cells[2].Range;
rngCell.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
rng.MoveEnd(Word.WdUnits.wdCharacter, -1);
rngCell.InsertCrossReference(WdReferenceType.wdRefTypeEndnote, WdReferenceKind.wdEndnoteNumberFormatted, 1);
Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
  • Very good and informative answer and it solved my problem. But I still don't understand why my reference appeared before at the beginning of the row (which is beginning of Cell[1] rather than Cell[2]). – Sundar Apr 20 '16 at 14:44
  • I don't *know*, but I would assume it's a default behavior in the Word code. Something along the lines of: If the target range in a table isn't usable (i.e. contains cell or row structures) go to the beginning of the row. But that's just my guess... – Cindy Meister Apr 20 '16 at 16:04