Home > front end >  Move word range insertion point to end of line / paragraph
Move word range insertion point to end of line / paragraph

Time:04-07

I am trying to build a caption with custom field codes in the middle of a word document using VB.net. The content of the field codes is not important but should follow the format:

Figure [Field code 1].[Field code 2] afterText

Where [Field 1] and [Field 2] can be toggled to show their field codes.

I am struggling to get the insertion point in the correct place to insert each element. Here is my code so far:

' insert "Figure" text
rng.Style = CaptionStyle
rng.InsertAfter("Figure ")

' insert first field code
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
rng.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "STYLEREF ""Heading 2"" \s", True)

' insert field code separator
rng.Expand(Word.WdUnits.wdParagraph)
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
rng.InsertAfter(".")

' insert second field code
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
rng.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "SEQ FigureBody2 \* ARABIC \s 3", True)

' insert text after the codes
rng.Expand(Word.WdUnits.wdParagraph)
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
rng.InsertAfter("afterText")

The code shown moves the insertion point to the beginning of the next paragraph each time, not the end of the current paragraph like I would have expected. So I end up with the bits of my insertions at the beginning of the following paragraphs.

Please help me move the insertion point to the end of the current paragraph that the range object is in. I cannot just move to the end of the wdStory because this is being inserted half way through a document.

CodePudding user response:

You could use something along the lines of:

rng.Style = CaptionStyle
rng.End = rng.Paragraphs.First.Range.End - 1
rng.Text = "Figure "

  ' insert first field code
rng.Collapse (Word.WdCollapseDirection.wdCollapseEnd)
rng.Fields.Add(rng.Duplicate, Word.WdFieldType.wdFieldEmpty, "STYLEREF ""Heading 2"" \s", False)

' insert field code separator
rng.End = rng.Paragraphs.First.Range.End - 1
rng.Collapse (Word.WdCollapseDirection.wdCollapseEnd)
rng.Text = "."

' insert second field code
rng.End = rng.Paragraphs.First.Range.End - 1
rng.Collapse (Word.WdCollapseDirection.wdCollapseEnd)
rng.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "SEQ FigureBody2 \* ARABIC \s 3", False)

' insert text after the codes
rng.End = rng.Paragraphs.First.Range.End - 1
rng.Collapse (Word.WdCollapseDirection.wdCollapseEnd)
rng.Text = " After Text"

Note: I don't use VB.net, so I'm not sure whether "rng.End = rng.Paragraphs.First.Range.End - 1" is strictly correct in that environment. It's based on what works in VBA.

  • Related