Search code examples
c#.netms-wordoffice-interopnetoffice

Word interop cross referencing an endnote


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?


Solution

  • 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);