This post is the second in a series about controlling other applications from Excel using VBA. In the first part we looked at the basics of how to reference other applications using Early Binding or Late Binding. In this post, we will look at how we can automate Word from Excel even though we don’t know any VBA code for Word… yet. The process we will use for this is as follows:
- Enable the Word Developer menu
- Record a Word macro
- Add the code to Excel VBA and amend
- Record macros in Excel if necessary
- Repeat the previous steps until macro complete
I am not an Excel VBA expert (I’m more of an Excel VBA tinkerer), and I am certainly not a Word VBA expert. The process I am about to show you may not create the most efficient code, but I know this process works, because I have used it myself to automate lots tasks using Microsoft Word.
Enable the Word Developer menu
If you have enabled the Excel Developer menu it is the same process in Word.
In Word: File -> Options -> Customize Ribbon
Then tick the Developer Ribbon option, OK.
Record a Word Macro
The key to the success of this method is taking small sections of code and building up a complex macro bit by bit. Using the Word Macro Recorder is again, similar to the Excel Macro recorder.
Click on: Developer -> Record Macro
For the example in this post, we will create a macro which will open a new Word document, then copy a chart from Excel and paste it into that Word document. We will tackle this one stage at a time. Firstly, lets create the macro to open a new word document.
Click – Developer -> Record Macro. The Record Macro window will open.
Make a note of the “Store macro in” option, as we will need to know where to find the recorded code later. Normal.dotm is fine for now. Click OK – the Macro Recorder is now running.
Open a new Word Document – File -> New -> Blank Document
Stop the Macro from recording – Developer -> Stop Recording
We can now view the code for opening a new Word Document in the Visual Basic Editor. Click: Developer -> Visual Basic.
Find the location of your recorded code in the Visual Basic Editor. In this example: Normal -> Modules -> NewMacros.
Your code should look like the following. It may be slightly different, but not significantly.
Sub Macro1() ' ' Macro1 Macro ' ' Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0 Windows("Document1").Activate Windows("Document2").Activate End Sub
Add the code to Excel VBA and amend
Let’s head back to the Excel VBA Editor and use the Early Binding method to control to Microsoft Word. In the Visual Basic Editor click Tools -> References select Microsoft Word x.xx Object Library. Then click OK.
As we are using Early Binding we need to declare the Application as a variable as follows:
Dim WordApp As Word.Application Set WordApp = New Word.Application
Now copy and paste the code from the Word VBA Editor into the Excel VBA Editor.
The Word VBA code started with Documents.Add, all we have to do is add our application variable to the front of that line of code. Now becomes WordApp.Documents.Add . . .
Often, Selecting and Activating Objects is not required in VBA code, so I have not copied those statements into the code below.
Sub CreateWordDocument() 'Connect using Early Binding. 'Remember to set the reference to the Word Object Library 'In VBE Editor Tools -> References -> Microsoft Word x.xx Object Library Dim WordApp As Word.Application Set WordApp = New Word.Application WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0 WordApp.Visible = True 'New Apps will be hidden by default, so make visible Set WordApp = Nothing 'release the memory End Sub
A point to note, when an application is opened with VBA, it is normally opened in the background. To make the Word document visible I have added the following code:
WordApp.Visible = True
Record macros in Excel (if necessary)
If we want to copy Excel content into a Word document, we will need to copy that content using Excel VBA. We can use the Macro Recorder in Excel to obtain the VBA code for copying, then we can use the Word Macro Recorder to obtain the VBA code for pasting.
Macro Recording from Excel – selecting a worksheet and copying chart
Sheets("Sheet1").Select ActiveSheet.ChartObjects("Chart 1").Activate ActiveChart.ChartArea.Copy
Macro Recording from Word – pasting a chart into a document
Selection.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _ Placement:=wdInLine, DisplayAsIcon:=False
We can add both Macro recordings into our Excel macro. Remember to add WordApp. at the start of each statement of Word VBA code.
Sub CreateWordDocument() 'Connect using Early Binding. 'Remember to set the reference to the Word Object Library 'In VBE Editor Tools -> References -> Microsoft Word x.xx Object Library Dim WordApp As Word.Application Set WordApp = New Word.Application WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0 WordApp.Visible = True 'New Apps will be hidden by default, so make visible 'code copied from Excel Macro recorder Sheets("Sheet1").Select Selection.ChartObjects("Chart 1").ChartArea.Copy 'code copied from Word Macro recorder with WordApp. added to the front. WordApp.Selection.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _ Placement:=wdInLine, DisplayAsIcon:=False Set WordApp = Nothing 'release the memory End Sub
This code is not particularly efficient; it contains a few unnecessary sections code. However… it works!
Repeat the previous steps until macro complete
By repeating the same steps above; recording short actions, then transferring the code into Excel, we can slowly build up much more complex Macros. The key is to keep the actions short, if you do too many actions with the Macro Recorder, code starts to look long and scary.
If you’ve you tried to use the Macro Recorder before you will know that this is not as easy as it seems. And this simple tutorial may make you think it is easy, when it’s not. Sometimes, it can be quite frustrating trying to find out where the issues and errors are. The key to success is recording very short actions, such as those below and copying them into the Visual Basic Editor.
'Pressing the Enter Key to move to a new line in Word WordApp.Selection.TypeParagraph 'Turn on/off Bold Text WordApp.Selection.Font.Bold = wdToggle 'Change Font Size WordApp.Selection.Font.Size = 16 'Type some text WordApp.Selection.TypeText Text:="Here is some text"
You will soon build up a standard library of code that you can use to control Word for most basic tasks.
In recorded VBA code from Word, the word “Selection” in the code often refers to the document itself. It is possible to make the code a little bit more efficient by declaring the document as a variable. If we were opening a specific document, we could include this at the start, just below the declaration of the application.
'Declare a specific document as a variable Dim WordDocument As Object Set WordDocument = WordApp.Documents.Open(sourceFileName)
Or, if we created a new document we could include the following below the declaration of the application variable.
'Delcare a new document as a variable Dim WordDocument As Object Set WordDocument = WordApp.Documents.Add Template:="Normal", _ NewTemplate:=False, DocumentType:=0
If we have created the document as a variable we can then reference the specific document. This code:
WordApp.Selection.TypeParagraph
Would become this code:
WordDocument.TypeParagraph
Or this code:
WordApp.Selection.TypeText Text:="Here is some text"
Would become this code:
WordDocument.TypeText Text:="Here is some text"
This method is much better, as it doesn’t rely on the Selection of the user being in the right place.
Conclusion
We have seen in this post that it is possible to create complex Macros to automate Word from Excel using VBA. By understanding how to declare variables for the application and documents we can create much more robust macros, even without knowing a lot of VBA code.
Related Posts:
- 5 quick ways to embed a Word document in Excel
- Controlling Powerpoint from Excel using VBA
- Edit links in Word using VBA
- How to link Excel to Word
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
March 19, 2002 — by Bill Jelen
Thanks to Jake who provided this week’s Excel question:
How can I write a macro which will take Excel spreadsheet data and create a Word file for each row of data?
Jake — what a great idea! I often have sales results for the entire company and it would be great to be able to send each rep just his or her information in Word. You could do this from Word using Mail Merge, but controlling Word from Excel is an interesting prospect. The example below is fairly straightforward, but one would be able to build upon this concept to do fairly advanced applications.
First, let’s take a look at a sample data set. I created a workbook with two sheets — one called Data and one called Template. The Data worksheet has many rows of data. The Template worksheet has the structure of the Word Document that I want to create. In this case, I will want to copy the name from column A of the database to cell C4 on the template. Columns B:E of the database will go in cells C10:C13.
First, let’s take a look at a sample data set. I created a workbook with two sheets — one called Data and one called Template. The Data worksheet has many rows of data. The Template worksheet has the structure of the Word Document that I want to create. In this case, I will want to copy the name from column A of the database to cell C4 on the template. Columns B:E of the database will go in cells C10:C13.
Start the VB Editor with alt-F11. Since we want to issue Word commands here, Go to Tools > References. Scroll down to find «Microsoft Word 8» and check the box next to select this item.
To control Word from Excel, you need to define a variable to represent the Word application. In the example below, I used appWD. For any commands in the Excel Macro which you want to apply to the Word application, you simply prefix the command with appWD. In fact, since I have never written a line of Word Macro code before, I went to Word, recorded the actions, then copied that code into Excel, adding the prefix before each line.
Sub ControlWord()
' You must pick Microsoft Word 8.0 from Tools>References
' in the VB editor to execute Word commands.
' See VB Help topic "Controlling One Microsoft Office Application from Another"
' for more information.
' Originally published by www.MrExcel.com 2/28/1999
Dim appWD As Word.Application
' Create a new instance of Word & make it visible
Set appWD = CreateObject("Word.Application.8")
appWD.Visible = True
Sheets("Data").Select
'Find the last row with data in the database
FinalRow = Range("A9999").End(xlUp).Row
For i = 2 To FinalRow
Sheets("Data").Select
' Copy the name to cell C4
Range("A" & i).Copy Destination:=Sheets("Template").Range("C4")
' Copy data columns, transpose and paste in C10:C13
Range("B" & i & ":E" & i).Copy
Sheets("Template").Select
Range("C10").PasteSpecial Transpose:=True
' Copy the data for the new document to the clipboard
Range("A1:F15").Copy
' Tell Word to create a new document
appWD.Documents.Add
' Tell Word to paste the contents of the clipboard into the new document
appWD.Selection.Paste
' Save the new document with a sequential file name
appWD.ActiveDocument.SaveAs FileName:="File" & i
' Close this new word document
appWD.ActiveDocument.Close
Next i
' Close the Word application
appWD.Quit
End Sub
After running this macro, you will have one new Word file for each row of data on your data sheet.
Thanks again to Jake for this great question. There are many applications where controlling Word from inside of Excel could provide a powerful solution.
- Документы Word
- Создание файлов
- Работа с файлами
Макрос предназначен для программного создания документов Word на основе шаблона
(без использования функции слияния в Word)
В прикреплённом к статье архиве находятся 2 файла:
- шаблон договора в формате Microsoft Word (расширение .dot)
- файл Excel с макросом
Настройки макроса задаются в коде:
Const ИмяФайлаШаблона = «шаблон.dot»
Const КоличествоОбрабатываемыхСтолбцов = 8
Const РасширениеСоздаваемыхФайлов = «.doc»
При нажатии кнопки запуска макрос на основе шаблона dot создаёт очередной файл, и в этом документе производит замену текста («кода поля») из первой строки файла Excel на значение поля (из очередной строки с данными файла Excel)
Папка для сформированных документов создаётся автоматически, и содержит в имени текущую дату и время
(например, созданная папка будет называться Договоры, сформированные 01-05-2011 в 15-03-24)
Имена создаваемых файлов формируются объединением полей фамилия, имя и отчество, с добавлением расширения doc
PS: Макрос был написан достаточно давно, когда я только начинал изучать VBA, — так что код недостаточно универсален.
Но, в качестве примера, пожалуй, подойдёт (если вам нужен более функциональный макрос, воспользуйтесь универсальной надстройкой (см. ниже))
Ознакомьтесь также с универсальной надстройкой формирования документов по шаблонам,
которая может делать всё тоже самое, что и эта программа,
только в качестве шаблонов могут выступать, помимо документов Word, ещё текстовые файлы, и книги Excel.
В надстройке — много возможностей, и полезных дополнений: склонение ФИО в родительный и дательный падежи, автоматический вывод на печать (с заданным количеством копий), размещение созданных файлов в разных папках, создание и рассылка писем со вложениями, и множество других полезных функций.
По вышеприведённой ссылке программа заполнения документов Word из Excel доступна для бесплатного скачивания.
Внимание: просьбы о доработке макроса, описанного в этой статье, не принимаются.
Есть новая (универсальная) версия, — в которой уже есть практически всё, что может понадобиться.
- 197018 просмотров
Не получается применить макрос? Не удаётся изменить код под свои нужды?
Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.
In Previous Article we saw how to Copy Content from a Word Document and Paste in in to the Active Workbook. Now in this Article i am going to write a function will Select a Range from Excel and paste the content in a New Word Document.
Here there are two possible way of copying and pasting in Word Document. Also while pasting in the word Document you can format the Doc as per your requirement. Below 3rd point describe about that.
1. Copy only the Content and paste it in Word Document as Content.
Sub CopyToWord()
Dim objWord As New Word.Application
'Copy the range Which you want to paste in a New Word Document
Range("A1:B10").Copy
With objWord
.Documents.Add
.Selection.Paste
.Visible = True
End With
End Sub
2. Copy the Excel Range as Picture and paste it in word Doc.
Sub CopyToWord()
Dim objWord As New Word.Application
'Copy the range Which you want to paste in a
' New Word Document as a Picture
Range("A1:B10").CopyPicture xlPrinter
With objWord
.Documents.Add
.Selection.Paste
.Visible = True
End With
End Sub
3. Font Formatting of Word Document while pasting
Sub CopyRangeToWord()
Dim objWord As New Word.Application
Dim objDoc As New Word.Document
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Range("A1:B10").Copy
With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
'All formatting goes here
.Paste
.Font.Name = "broadway"
.Font.Color = wdColorBlue
.Font.Bold = True
.Font.Italic = True
.Font.Allcaps = True
.Font.Size = 20
End With
End Sub
Buy a coffee for the author
Вставка таблицы Excel в документ Word с помощью кода VBA Excel. Метод Selection.PasteExcelTable: синтаксис, параметры, пример использования.
Работа с Word из кода VBA Excel
Часть 6. Вставка таблицы Excel в документ Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]
Метод Selection.PasteExcelTable
Метод Range.Paste, использующийся в VBA Word для вставки в документ таблиц, скопированных в буфер обмена из другого документа Word, не применим для вставки в документ таблиц, скопированных из книги Excel. Для этих целей используется метод Selection.PasteExcelTable.
Selection.PasteExcelTable — это метод, предназначенный для вставки Excel-таблицы из буфера обмена в документ Word и ее форматирования в соответствии с заданными параметрами.
Синтаксис
Expression.PasteExcelTable(LinkedToExcel, WordFormatting, RTF) |
Expression — переменная, представляющая объект Selection. В том числе, это может быть курсор или закладка.
Параметры
Все параметры метода Selection.PasteExcelTable логического типа и являются обязательными.
Параметр | Описание |
---|---|
LinkedToExcel | True — вставленная таблица связывается с исходным файлом Excel, чтобы изменения, внесенные в файл Excel, отображались в Microsoft Word. False — связь между вставленной таблицей и таблицей в исходном файле не устанавливается. |
WordFormatting | True — вставленная таблица будет отформатирована как таблица документа Word. False — вставленная таблица будет отформатирована в соответствии с исходным файлом Excel. |
RTF | True — Excel-таблица будет вставлена в расширенном текстовом формате (RTF). False — Excel-таблица будет вставлена в формате HTML-таблицы. |
Допустим, у нас есть таблица Excel, начинающаяся с ячейки A1 (или с любой другой), и нам необходимо скопировать эту таблицу в существующий документ Word, вставив ее на место закладки «Закладка1».
Решение:
Sub Primer() Dim myWord As New Word.Application, myDoc As Word.Document ‘Открываем существующий документ Word Set myDoc = myWord.Documents.Open(«C:ТестоваяДокумент1.docx») ‘Копируем таблицу на активном листе в буфер обмена ‘Вместо ячейки Range(«A1») можно указать любую другую, расположенную внутри таблицы Range(«A1»).CurrentRegion.Copy ‘Вставляем таблицу из буфера обмена на место закладки myDoc.Bookmarks(«Закладка1»).Range.PasteExcelTable False, False, False ‘Отображаем программу Word myWord.Visible = True ‘Очищаем переменные Set myWord = Nothing Set myDoc = Nothing End Sub |
Если необходимо таблицу вставить в конец документа, строку
myDoc.Bookmarks(«Закладка1»).Range.PasteExcelTable False, False, False |
следует заменить на
With myDoc ‘Переводим курсор в конец документа .Range(.Range.Characters.Count — 1, .Range.Characters.Count — 1).Select ‘Добавляем перенос строки, если необходимо .ActiveWindow.Selection.InsertAfter vbCr ‘Переводим курсор в конец документа .Range(.Range.Characters.Count — 1, .Range.Characters.Count — 1).Select ‘Вставляем таблицу из буфера обмена .ActiveWindow.Selection.PasteExcelTable False, False, False End With |