Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# interop: How to determine a range of a Field?

I'd like to loop through all the fields in my document and place text after those of type wdFieldIndexEntry but Fields don't have a Range value they way Bookmarks do.

Below is the closest I've come:

foreach( Field f in document.Fields)
{
    if( f.Type == WdFieldType.wdFieldIndexEntry)
    {
        // f.Range.InsertAfter("{{Some After text}}"); // <- no Range field
        f.Code.InsertAfter("{{Some After text}}");  // puts text inside field
    }
}

As noted the above puts the text in the code (not surprisingly). How do I get the field location/Range so I can insert text before or after the field?

like image 219
buttonsrtoys Avatar asked Sep 07 '25 10:09

buttonsrtoys


1 Answers

Actually, fields do return Range objects. Most field types can return two kinds of ranges: one for Field.Code, another for Field.Result.

The Index field is special in that it returns only Field.Code. This is the text within the field { brackets }. So returning this Range won't put the focus outside the field, but you can get there...

First "collapse" the Range to its end-point (think of it like pressing Right arrow for a selection). Then move the starting point of the Range one character towards the end of the document - now it's outside the field.

Word.Range rngField = null;
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
object oMoveCharacter = Word.WdUnits.wdCharacter;
object oOne = 1;
foreach( Field f in document.Fields)
{
    if( f.Type == WdFieldType.wdFieldIndexEntry)
    {
        rngField = f.Code;
        rngField.Collapse(ref oCollapseEnd);
        rngField.MoveStart(ref oMoveCharacter, ref oOne);
        rngField.InsertAfter("{{Some After text}}");         }
}
like image 111
Cindy Meister Avatar answered Sep 09 '25 23:09

Cindy Meister