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?
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}}"); }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.