br0ken.pipe
br0ken.pipe

Reputation: 910

C# Column Break in Word document

I work in a three-column word document. I can insert a column break after a text, but I can't write it in the new column afterwards. What do I miss?

Word.Paragraph oPara4;
var oRng = document.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara4 = document.Content.Paragraphs.Add(oRng);
oPara4.Range.InsertParagraphBefore();
oPara4.Range.Text = "Some Text Before the break";
oPara4.Format.SpaceAfter = 24;
oPara4.Range.InsertParagraphAfter();

// Column Break
oPara4.Range.InsertBreak(Word.WdBreakType.wdColumnBreak);

// New Text in new column

Upvotes: 2

Views: 516

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

When generating Word document content it's a very good idea to work with dedicated Range objects to define the "targets".

The sample code below creates a Range object for oPara4. This makes it possible to "collapse" the Range to its end-point. (Think of it like pressing right-arrow when there's a selection to get a blinking cursort after what was selected.)

Collapsing the Range before inserting the column break ensures that everything created up to that point is not lost when writing new content (the column break) to the Range. After inserting the column break the Range is collapsed once more to its end-point, which is now in the next column.

        Word.Paragraph oPara4;
        var oRng = doc.Bookmarks.get_Item(@"\EndOfDoc").Range;
        oPara4 = doc.Content.Paragraphs.Add(oRng);
        Word.Range rngPara = oPara4.Range;
        rngPara.InsertParagraphBefore();
        rngPara.Text = "Some Text Before the break";
        oPara4.Format.SpaceAfter = 24;
        rngPara.InsertParagraphAfter();
        rngPara.Collapse(Word.WdCollapseDirection.wdCollapseEnd);

        // Column Break
        rngPara.InsertBreak(Word.WdBreakType.wdColumnBreak);
        rngPara.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
        rngPara.Text = "next";

Upvotes: 1

Related Questions