Mohd akhtar
Mohd akhtar

Reputation: 55

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

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

Upvotes: 0

Views: 6035

Answers (2)

B.carne
B.carne

Reputation: 36

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.

Upvotes: 2

Variatus
Variatus

Reputation: 14383

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.

Upvotes: 1

Related Questions