none
Insert heading and text in Word RRS feed

  • Question

  • Hi,

    I want insert a heading with text followed in Word 2010 document. I can insert text like this way:

    Word.Range rng = _Application.ActiveDocument.Range(0, 0);
    object style1 = "Standard";
    rng.set_Style(ref style1);
    rng.InsertAfter("Text");
    object style2 = "Heading 1";
    rng.set_Style(ref style2);
    rng.InsertAfter("Heading");

    But this looks not the rigt way becaus:

    - there is the style with text "Heading 1" 
    - the table of content does not work with  this

    How can I insert headings and text to get a table of content after inserting?

    Thanks

    Andreas

    Sunday, October 20, 2013 1:34 PM

Answers

  • Hi Andreas

    Roughly, like this

    Word.Range rng = _Application.ActiveDocument.Content;
    rng.Text = "Heading 1\n";
    object style1 = Word.WdBuiltinStyle.wdStyleHeading1;
    rng.set_Style(ref style1);
    object collapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
    rng.Collapse(ref collapseEnd);
    //Now the "point" is just AFTER the end of the range with the text.
    rng.Text = "Text";
    object style2 = Word.WdBuiltinStyle.wdStyleNormal;
    rng.set_Style(ref style2);


    Cindy Meister, VSTO/Word MVP, my blog

    • Marked as answer by AndreasM85 Sunday, October 20, 2013 4:23 PM
    Sunday, October 20, 2013 3:18 PM
    Moderator

All replies

  • Hi Andreas

    Roughly, like this

    Word.Range rng = _Application.ActiveDocument.Content;
    rng.Text = "Heading 1\n";
    object style1 = Word.WdBuiltinStyle.wdStyleHeading1;
    rng.set_Style(ref style1);
    object collapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
    rng.Collapse(ref collapseEnd);
    //Now the "point" is just AFTER the end of the range with the text.
    rng.Text = "Text";
    object style2 = Word.WdBuiltinStyle.wdStyleNormal;
    rng.set_Style(ref style2);


    Cindy Meister, VSTO/Word MVP, my blog

    • Marked as answer by AndreasM85 Sunday, October 20, 2013 4:23 PM
    Sunday, October 20, 2013 3:18 PM
    Moderator
  • Thanks. This works fine.

    Sunday, October 20, 2013 4:24 PM