none
[Word 2003] Move cursor after to insert a Field

    Question

  • Hi,
     
    I have a problem :)
    I want to insert a Field with Range and after that move the cursor to insert Xml.

    My code to add the Field:

    Range rngStart = Globals.ThisDocument.Application.Selection.Range
    object formatting = true;

    object fieldType = WdFieldType.wdFieldMergeField;
    object fieldCode = "Blabla";

    object start = rngStart.Start;
    object end = rngStart.End;

    Range rngEnd = Globals.ThisDocument.Range(ref start, ref end);

    rngEnd.Fields.Add(rngStart,ref fieldType, ref fieldCode, ref formatting);

    This part of code workes fine but after that I want to insert an xml text with InsertXml.
    So how can I move the cursor to insert my text after my field ?
    Now, the xml text replace all the time my field because the Start Range is always the start of the field range.

    Thanks you for your help.

    Fix

    fix
    Wednesday, January 07, 2009 2:35 PM

Answers

  • Create an object for the field you're inserting. A field object's Result property returns an object of type Range. So you can use this to move beyond the end of the field. Very roughly:

    Word.Field fld = rngEnd.Fields.Add(....
    Word.Range rngField = fld.Result;
    Word.Range rngAfterField = rngField.Duplicate;  //may not be necessary to have two ranges...
    object collapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
    rngAfterField.Collapse(ref collapseEnd);
    //You have to check at this point whether you're actually beyond the field, if not
    //object moveOneChar = 1;
    //rngAfterField.MoveStart(ref moveOneChar);
    Cindy Meister, VSTO/Word MVP
    • Marked as answer by fix105 Tuesday, January 13, 2009 7:58 AM
    Thursday, January 08, 2009 9:49 AM
    Moderator

All replies

  • Create an object for the field you're inserting. A field object's Result property returns an object of type Range. So you can use this to move beyond the end of the field. Very roughly:

    Word.Field fld = rngEnd.Fields.Add(....
    Word.Range rngField = fld.Result;
    Word.Range rngAfterField = rngField.Duplicate;  //may not be necessary to have two ranges...
    object collapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
    rngAfterField.Collapse(ref collapseEnd);
    //You have to check at this point whether you're actually beyond the field, if not
    //object moveOneChar = 1;
    //rngAfterField.MoveStart(ref moveOneChar);
    Cindy Meister, VSTO/Word MVP
    • Marked as answer by fix105 Tuesday, January 13, 2009 7:58 AM
    Thursday, January 08, 2009 9:49 AM
    Moderator
  • Thanks you for your help Cindy.
    I learnt a lot of with Field, Range and other objects.


    fix
    Tuesday, January 13, 2009 7:57 AM