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

血红的双手。 提交于 2019-12-10 12:48:14

问题


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


回答1:


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#



回答2:


If you will be inserting text at the same location every time a simple way to do this is to create a .dotx template file with a bookmark at the location. Make sure the template is included in the build

Doc = Word.Documents.Add("Directory\Filename")
Doc.Bookmarks.Item("BookmarkName").Range.Text = "Text to be inserted"



回答3:


Finding a position in a word document to insert a table

You may find some useful information in the above location.



来源:https://stackoverflow.com/questions/12071425/how-to-add-text-into-word-documents-at-a-specific-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!