560 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Referencing Word and other applications in Excel VBA Part four of a four-part series of blogs |
---|
Even if you're writing Visual Basic macros within Excel, there's nothing to stop you inserting text into Word documents, manipulating PowerPoint slides or sending Outlook emails. This blog explains how to reference other applications, and write macros in Excel to link to other Microsoft Office software
This blog is part of a complete Excel VBA tutorial. You can also learn to program in VBA on one of our VBA macros courses. |
This page shows an example of how to create a mail merge from Word to Excel. It's quite a long example, but should be a great aid to helping understand how to link applications using VBA.
The files that you'll need to get this to work are as follows:
The Excel workbook containing the people
The Word document containing the template to be filled in
The macros are written in Excel 2010 and Word 2010, but should work in Office version 2007 also.
Suppose that we have a list of people in an Excel worksheet:
Our aim is to create a "letter" in Word addressed to each of these people.
If we succeed, the end result will be 3 documents saved in Word - the one for Tinky Winky will look like this, for example:
The form filled in for Tinky Winky, the second of the 3 people we're writing to.
To do this we'll loop over the people in the list in Excel, creating a document in Word for each.
We now need to create our Word template form and add bookmarks to it, so that we know where to insert the various fields. The template form begins life as a simple table:
The first name, last name and company name will appear in the table.
The next thing to do is to make sure that we can see any bookmarks that we add.
A bookmark in Word is a flag in a document which you can jump to - like an insertion point.
To view bookmarks, follow these steps:
You can now insert bookmarks - we'll create 3, called FirstName, LastName and Company. For each bookmark, select the following option and fill in the dialog box which appears:
The ribbon option to insert a bookmark
After creating 3 bookmarks, your document should now look like this:
You can see where the 3 bookmarks have been inserted.
After saving this document, you now need to know how to go to a bookmark in Word from within your Excel code.
If you happen to know Word Visual Basic inside-out, you can ignore this step!
Firstly, start recording a macro (if you're not sure what recording a macro means or how to do it, see my earlier tutorial on recording macros in Excel).
Click on this tool to start recording a macro.
While recording (it doesn't really matter what you called your macro), choose to find a bookmark:
Choose which bookmark you want to go to:
Choose to go to a bookmark, then choose one from the list (it doesn't matter which).
Now stop recording:
Click on this tool to stop recording your macro.
If you press ALT + F11 to go into Visual Basic, you'll find your recorded macro in the Normal template:
Word by default puts recorded macros into a module called NewMacros.
You can now see your macro, and copy the only line you want from it:
Selection.GoTo What:=wdGoToBookmark, _
Name:="LastName"
You can now close down Word, and write your Excel macro!
The final stage is to open your workbook in Excel, and write your macro:
A reminder of what the Excel workbook looks like.
To write your macro, go into VBA and create a reference to Word 2010 as described earlier in this blog. You can then create the macro - here's what it could look like:
Option Explicit
'change this to where your files are stored
Const FilePath As String = "C:\ajb files\"
Dim wd As New Word.Application
Dim PersonCell As Range
Sub CreateWordDocuments()
'create copy of Word in memory
Dim doc As Word.Document
wd.Visible = True
Dim PersonRange As Range
'create a reference to all the people
Range("A1").Select
Set PersonRange = Range( _
ActiveCell, _
ActiveCell.End(xlDown))
'for each person in list �
For Each PersonCell In PersonRange
'open a document in Word
Set doc = wd.Documents.Open(FilePath & "Word form.docx")
'go to each bookmark and type in details
CopyCell "FirstName", 1
CopyCell "LastName", 2
CopyCell "Company", 3
'save and close this document
doc.SaveAs2 FilePath & "person " & PersonCell.Value & ".docx"
doc.Close
Next PersonCell
wd.Quit
MsgBox "Created files in " & FilePath & "!"
End Sub
Sub CopyCell(BookMarkName As String, ColumnOffset As Integer)
'copy each cell to relevant Word bookmark
wd.Selection.GoTo What:=wdGoToBookmark, Name:=BookMarkName
wd.Selection.TypeText PersonCell.Offset(0, ColumnOffset).Value
End Sub
When you run this macro, it should:
Create a new copy of Word in memory, and make it visible; then
For each person, create a new document, write in the person's name and company at the correct locations, then save and close it.
The results? Three documents on your hard disk:
What you should see after running your macro - each document contains a filled-in form for a different person.
And that's how you can fill in a Word document from within Excel!
If you'd like to go on one of our VBA courses and have a real live owl explain this to you, consider booking on our Advanced VBA course - wherever you are in the world, for the online version.
Parts of this blog |
---|
|
Some other pages relevant to the above blogs include:
From: | Matéo |
When: | 23 Nov 21 at 11:11 |
Amazing article, thank you !
But i have a problem: I want in the same bookmark to use two columns (to put someone's first name and surname for example). And after a bookmark I want to add a string using something like CopyCell "Amount", 1 & " €". Is this possible?
From: | Andy B |
When: | 23 Nov 21 at 11:20 |
To put in the first name and surname, the easiest thing to do is to use two bookmarks. Likewise with the amount - just add another bookmark, and type what you want in there.
From: | Matéo |
When: | 23 Nov 21 at 11:25 |
I am so stupid. And for my second problem, do you have idea ?
From: | Andy B |
When: | 23 Nov 21 at 11:40 |
I guess I'm not really sure what you mean. If you want to paste in the value of something, an easy way to do that is to store the text in a variable in Excel, then just write the contents of the variable in at a Word bookmark as if it were normal text.
From: | lauch001 |
When: | 27 Oct 20 at 11:45 |
If i only wanted to create one word document for all instead of individual ones, what would the code look like? Thanks!
From: | Andy B |
When: | 27 Oct 20 at 11:56 |
Just move the first grey line below before the loop, and the last two grey lines after it.
For Each PersonCell In PersonRange
'open a document in Word
Set doc = wd.Documents.Open(FilePath & "Word form.docx")
'go to each bookmark and type in details
CopyCell "FirstName", 1
CopyCell "LastName", 2
CopyCell "Company", 3
'save and close this document
doc.SaveAs2 FilePath & "person " & PersonCell.Value & ".docx"
doc.Close
Next PersonCell
You could probably do with adding a carriage return after copying each set of values - from memory, something like:
Selection.TypeParagraph
From: | purlo |
When: | 22 May 20 at 11:34 |
Thanks for wonderful article, this is what I was looking for. For some reason when I run macro it shows a mistake on this line:
Set doc = wd.Documents.Open(FilePath & "Word form.docx")
Mistake: "Run-time error '5174'. This file could not be found. It also showed error 462.
Should it be modified?
From: | Teo_B |
When: | 28 Jan 21 at 19:25 |
I had the same problem because
1) FilePath refers to the path that locates the folder of the user form and not the word.docx you downloaded. When i copied the folder's path i did not realise that the last \ was missing.
2) At Set doc = wd.Documents.Open(FilePath & "Word form.docx") , "Word form" is the name of the file and when i downloaded it was called "d7". So when i changed to "d7.docx" it worked.
Hope it helped you.
From: | Andy B |
When: | 22 May 20 at 16:53 |
I think the code is good. You may have some strange characters in your folder or file names? Try this StackOverflow article for ideas if you're still stuck.
From: | AHVBA |
When: | 19 May 20 at 16:51 |
Constantly find myself coming back to this page - thanks so much for creating it WiseOwl.
One thing i've never mangaged to tackle is how you amend this so that the values inserted into the Word bookmarks keep their source fomatting (or merge formatting with the word document) - sometimes it'd be useful to retain or merge that formatting to improve the look/feel of the document. Any ideas?
From: | Andy B |
When: | 20 May 20 at 09:36 |
I'd try this. Copy something in Excel which includes formatting, then go to Word. Start recording a macro, and use Paste Special to paste in the cells keeping the formatting you want. Stop recording, and have a look to see if the code you've got can be tweaked to do what you want. Feel free to report back if you have any success, for others to use in the future!
From: | AJHEZ |
When: | 18 May 18 at 09:55 |
This is great!
Does anyone have any idea how to amend this so that if the value that you're copying to the word document is a numerical value?
I.e. if the value you wanted to copy from excel was "15%" if you use this code then the value inserted into the word bookmark reads "0.15".
Is there a way to keep the cell format as it is displayed in the excel document when pasted into the bookmark?
Cheers,
AJHEZ
From: | Andrew G |
When: | 18 May 18 at 11:20 |
You could use the Text property of the range you're copying, rather than the Value property:
wd.Selection.TypeText PersonCell.Offset(0, ColumnOffset).Text
I hope that helps!
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2023. All Rights Reserved.