How to add text into Word Documents at a specific position?

Gypsy picture Gypsy · Aug 22, 2012 · Viewed 15.7k times · Source

How do I write to a specific position in a Word document, for example, line 5, character 50? I have searched for a couple of hours, but couldn't find a solution.

I am using Microsoft.Office.Interop.Word

Answer

Fionnuala picture Fionnuala · Aug 22, 2012

If you are content with the more simple sentence, rather than lines:

ActiveDocument.Sentences(1).Characters(5).Select
Selection.Collapse
Selection.InsertBefore "added "

Five paragraphs and 50 spaces in VBA

Selection.Text = String(5, vbCrLf) 
Selection.Collapse wdCollapseEnd
Selection.Text = String(50, " ")

However, for a particular position, I would prefer a textbox:

Set sh = doc.Shapes.AddTextbox(1, 10, 344, 575, 80)
sh.Name = "Course1"

With some properties:

sh.Fill.Visible = False
sh.Line.Visible = False
sh.TextFrame.MarginLeft = 0#
sh.TextFrame.MarginRight = 0#
sh.TextFrame.MarginTop = 0#
sh.TextFrame.MarginBottom = 0#