VBA to copy text from excel to on specific location in wordfile

限于喜欢 提交于 2020-01-30 11:01:09

问题


Problem: Pasting copied data from excel to specific location in a word file.

Currently I have code which can paste the value, but it does so to "paragraph1"

myDoc.Paragraphs(1).Range.Paste

How do I specify the exact location (by line) in which to paste the data? Let me know if more info is required.

Thanks!

Mohd Akhtar


回答1:


You could also use some bookmarks:

You can choose where you put your bookmark and then write on it like this ThisDocument.Bookmarks("NAME_OF_THE_BOOKMARK").Range.Text = THE_EXCEL_DATA

To place a bookmark you have to click on the selected area and then go on Insert->Bookmarks and then name it.




回答2:


Word gives a number to each character in the document's body, from 1 up. It then defines a range with Range.Start to Range.End So, Paragraphs(1).Range might be equal to Range(Start:=1, End:=120).

The text contained in that range is Range.Text, Read/Write. Therefore, Paragraphs(1).Range.Text = "My new paragraph text" will replace the existing text in the document's first paragraph. ActiveDocument.Range(0, 0).Text specifies the range before the first character in the document.

In order to insert text at a specific location you have to find the location, meaning the Range. As you have seen above, if the range has a length of 0 you can insert before or between existing text, and if it has any length the new text will replace whatever was there before. New and old text need not have the same length.

Counting paragraphs is helpful to find a range. You can also count words or sentences. You can search for a specific word combination. Or you can use a bookmark. In all of these cases you define a range the text of which you can replace outright, or which you can use to find a location relative to it where to insert the text, such as the beginning or end or after the 3rd word or whatever.



来源:https://stackoverflow.com/questions/45351308/vba-to-copy-text-from-excel-to-on-specific-location-in-wordfile

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