excel to word template code

G

Guest

Hello,
I need to create a word doc using a word template with merge fields in it.
I would like to have a button in excel that launches the word template and
populates it with data that is stored in various sheets of my excel workbook.
Is this fairly straight forward and does anyone have sample code for
populating a word template from excel?
Thank you,
Mark
 
G

Guest

Tick M/soft Word Objects in Tools, References while your project is selected
in Excel VB Editor. It's best to use bookmarks rather than merge fields (you
insert them into the Word template by positioning your cursor and then
selecting Insert, Bookmark). The following code will do the trick:

Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bmk As Word.Bookmark
Set doc = objWord.Documents.Open("full path name of template")
For Each bmk In doc.Bookmarks
If bmk.Name = "First_Name" Then bmk.Range.Text = Range("A1").Value
If bmk.Name = "Address" Then bmk.Range.Text = Range("B1").Value
Next
'doc.Bookmarks("First_Name").Range.Text = Range("A1").Value
objWord.Visible = True

I like to use the loop rather than the remmed-out line in case the template
gets altered along the line and loses one of the bookmarks (in which case the
loop doesn't fall over).
 
G

Guest

Hi,
Thanks for the great reply. The code works well with one issue. I cannot
get the word doc to open until I run the routine a second time. The second
time I run it I get two word windows with no documents in them and then a
third window is open with the doc I want. The fields do get merged.
Any ideas on how to show the document?
Thanks,
Mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top