Vba access word from excel

In this article, we will see how to access the various word objects using VBA in Excel and insert data from Excel to Word. This has many practical applications such as when you have to fill out a form multiple times with data from Excel or when you have to create a Word document with the same structure but different data each time and so on.

Before we go through individual controls, first let us have a look at how to access a Word document in Excel.

Step 1: Get the name and path of the Word Document that you need to modify. We will use the GetOpenFilename command for that.

fileName = Application.GetOpenFilename(, , "Select the word Document")

Step 2: Check to see if Word is already running on the system.

Set oApp = GetObject(, "Word.Application")

If Word is not running already, then start it

If Err.Number <> 0 Then
    Set oApp = CreateObject("Word.Application")
End If


Step 3:
Assign the selected Word file to a Word object so that we can access it.

Set oDoc = oApp.Documents.Open(fileName)
oApp.Visible = True

Now that we know how to access to the Word document, let us see how to access the various controls in Word. In each of the below examples, we will need to add the above code.

Example 1: Bookmarks

In this example, we will see how to insert data from Excel after a bookmark in Word. Let us assume you have a bookmark named “Table1” in Word, where you be inserting a table from Excel. So, for simplicity, we will name that range in Excel as “Table1”.

Step 1: Access the bookmark

Set oBkMrk = oApp.ActiveDocument.Bookmarks("Table1")

Step 2: Get the location where you want to insert the data

Set objRange = oBkMrk.Range.Characters.last ‘Position of the last character of the bookmark
objRange.Start = objRange.Start + 1 ‘We need to start pasting from the next character


Step 3:
Copy the table and paste it at that location

Range(“Table1”).Copy
objRange.PasteExcelTable False, False, False

The PasteExcelTable method takes 3 arguments: LinkedToExcel, WordFormatting, RTF. We have set them all to False. Once you run the code, the Word Document will look like this

Example 2: Text boxes

In Word, the only way to assign a name to a shape is by using VBA (in contrast to Excel where this can be done using the formula bar). Secondly, Word does not force shapes to have unique names. So, accessing a text box by its name is not a very good option. The approach we will follow is referring to shapes by their index position.

Note: We are referring to text box created using drawing controls (Insert tab)
In this example we will loop through all the text boxes in Word and modify their text.

Step 1: So, first loop through all the shapes in the Word document using the .Shapes collection
Step 2: Check if the shape is a textbox
Step 3: Manipulate the .TextFrame.TextRange.Text property, to copy text from Excel.

Dim str As String
Dim i As Integer
i = 1
For Each shp In oDoc.Shapes
    If shp.Type = msoTextBox Then
        str = ThisWorkbook.Sheets("Sheet1").Cells(i, 1).Value
        shp.TextFrame.TextRange.Text = str
        i = i + 1
    End If
Next

Here the excel values we are using are in column A, and i is used as the counter to directly access column A rows from the Excel. This is how the output will look:

Example 3: Content control Text box from Developer tab

For this we will be using the Title property of a textbox to access it. The title can be set using the properties option of a textbox from the Developer Tab. The code is very similar to that in example 2

    For Each cc In oDoc.ContentControls
        If cc.Title = "Text1" Then
            cc.Range.Text = "Hello World!"
            Exit For
        End If
    Next cc

For multiple textboxes, you can match the title of the text box to the corresponding range in Excel and easily loop through.

Example 4: Headers and Footers

This code will add Headers and Footers on all the pages of Section 1 of the Word Document. The text can easily be taken from an Excel file.

With oDoc.Sections(1)
    .Headers.Item(1).Range.Text = "Header text"
    .Footers.Item(1).Range.Text = "Footer text"
End With

Here is how the header and footer will look like.


And here’s all the above code put together for easy reference:

Sub copyToWord()

Dim oApp        As Object 'Word.Application
Dim oDoc        As Object 'Word.Document
Dim sDocName    As String
Dim path        As String
Dim fileName    As String
Dim noOfFields  As Integer
Dim varName     As String
Dim wb

fileName = Application.GetOpenFilename(, , "Select the word Document")
Set wb = ThisWorkbook

On Error Resume Next
    Set oApp = GetObject(, "Word.Application") 'See if word is already running
    If Err.Number <> 0 Then     'Word isn't running so start it
        Set oApp = CreateObject("Word.Application")
    End If

On Error GoTo Error_Handler_Exit
    Set oDoc = oApp.Documents.Open(fileName)
    oApp.Visible = True

'Bookmarks
Set oBkMrk = oApp.ActiveDocument.Bookmarks("Table1")

Set objRange = oBkMrk.Range.Characters.last
objRange.Start = objRange.Start + 1

Range("Table1").Copy
objRange.PasteExcelTable False, False, False

'Textbox
Dim str As String
Dim i
i = 1

For Each shp In oDoc.Shapes
    If shp.Type = msoTextBox Then
        str = ThisWorkbook.Sheets("Sheet1").Cells(i, 1).Value
        shp.TextFrame.TextRange.Text = str
        i = i + 1
    End If
Next

'Textbox Content Control
    For Each cc In oDoc.ContentControls
        If cc.Title = "Text1" Then
            cc.Range.Text = "Hello World!"
            Exit For
        End If
    Next cc

'Headers and Footers
With oDoc.Sections(1)
    .Headers.Item(1).Range.Text = "Header goes here"
    .Footers.Item(1).Range.Text = "Footer goes here"
End With

oDoc.Save

Error_Handler_Exit:
    On Error Resume Next
    Set oDoc = Nothing
    Set oApp = Nothing
    Exit Sub

Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: UpdateDoc" & vbCrLf & _
           "Error Description: " & Err.Description, _
           vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit

End Sub

Хитрости »

24 Февраль 2012              91411 просмотров


Иногда бывает необходимо перенести что-то из Excel в другое приложение. Я возьму для примера Word. Например скопировать ячейки и вставить. Обычно мы это так и делаем — скопировали в Excel, открыли Word — вставили. Но сделать это при помощи кода чуть сложнее, хотя если разобраться никаких сложностей нет. Ниже приведен пример кода, который открывает Word, открывает в нем определенный документ, копирует данные из Excel и вставляет в открытый документ Word.

Sub OpenWord()
    Dim objWrdApp As Object, objWrdDoc As Object
    'создаем новое приложение Word
    Set objWrdApp = CreateObject("Word.Application")
    'Можно так же сделать приложение Word видимым. По умолчанию открывается в скрытом режиме
    'objWrdApp.Visible = True
    'открываем документ Word - документ "Doc1.doc" должен существовать
    Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc")
    'Копируем из Excel диапазон "A1:A10"
    Range("A1:A10").Copy
    'вставляем скопированные ячейки в Word - в начала документа
    objWrdDoc.Range(0).Paste
    'закрываем документ Word с сохранением
    objWrdDoc.Close True    ' False - без сохранения
    'закрываем приложение Word - обязательно!
    objWrdApp.Quit
    'очищаем переменные Word - обязательно!
    Set objWrdDoc = Nothing: Set objWrdApp = Nothing
End Sub

Скачать пример:

  Tips_Macro_OpenWord.xls (49,5 KiB, 6 264 скачиваний)

В файле-примере, приложенном к данной статье, в комментариях к коду есть несколько добавлений. Например, как вставить текст из ячеек в определенные закладки Word-а и как добавить новый документ, а не открывать уже имеющийся. Так же так есть код проверки — открыто ли приложение Word в данный момент. Порой это тоже может пригодиться, чтобы работать с запущенным приложением Word, а не создавать новое:

Sub Check_OpenWord()
    Dim objWrdApp As Object
    On Error Resume Next
    'пытаемся подключится к объекту Word
    Set objWrdApp = GetObject(, "Word.Application")
    If objWrdApp Is Nothing Then
        'если приложение закрыто - создаем новый экземпляр
        Set objWrdApp = CreateObject("Word.Application")
        'делаем приложение видимым. По умолчанию открывается в скрытом режиме
        objWrdApp.Visible = True
    Else
        'приложение открыто - выдаем сообщение
        MsgBox "Приложение Word уже открыто", vbInformation, "Check_OpenWord"
    End If
End Sub

В принципе, активировать или вызвать(если закрыто) другое приложение Офиса можно одной строкой:

Sub Open_AnotherApp()
    Application.ActivateMicrosoftApp xlMicrosoftWord
End Sub

но данный метод может пригодиться только в том случае, если Вам необходимо действительно лишь активировать другое приложение, но дальше обращаться к этому приложению Вы уже не сможете.

По сути, методами CreateObject и GetObject можно обратиться к любому стороннему приложению(например Internet Explorer). Куда важнее при обращении к этим объектам знать объектную модель того приложения, к которому обращаетесь. Чтобы увидеть свойства и методы объектной модели приложения, можно в редакторе VBA подключить необходимую библиотеку, объявить переменную, назначив ей тип приложения. Покажу на примере того же Word-а.
Для начала открываем меню Tools -References:

Подключаем библиотеку:

Затем объявляем переменную и присваиваем ей тип нужного приложения:

Sub OpenWord()
    Dim objWrdApp As Word.Application
    Set objWrdApp = New Word.Application
    objWrdApp.Visible = True
End Sub

Если теперь в редакторе, внутри этой процедуры в любом месте ниже объявления переменной набрать objWrdApp и точку, то сразу после ввода точки выпадет меню, в котором будут перечислены все доступные методы и свойства этого приложения.

Так же можно нажать F2 и через поиск найти Word и просмотреть все методы и свойства данного приложения.

Метод установки ссылки на библиотеку приложения через ToolsReferences называют еще ранним связыванием. Подобный метод позволяет создать ссылку на приложение быстрее и, как описано выше, предоставляет разработчику доступ к визуальному отображению свойств и методов объекта. Но есть существенный минус: если в своем коде Вы установите ссылку на Word 12 Object Libbary(Word 2007), то на ПК с установленным Word 2003 получите ошибку MISSING, т.к. Word 2003 относится к библиотеке Word 11 Object Libbary. Подробнее можно прочитать в статье Ошибка — Cant find project or library.
Метод же CreateObject еще называется методом позднего связывания. Применяя его не возникнет проблем с MISSING, очень часто возникающих при раннем связывании. Поэтому я рекомендовал бы при разработке использовать раннее связывание для удобства использования свойств и методов(если Вы их не знаете), а перед распространением приложения в коде заменить все именованные константы(типа wdLine) на числовые константы(для wdLine это 5) и применить позднее связывание. Посмотреть числовое значение константы можно просто записав её в коде, начать выполнение кода через F8 и навести курсор мыши на эту константу. Всплывающая подсказка покажет числовое значение. Так же можно отобразить окно Immediate(ViewImmediate Window или сочетание клавиш Ctrl+G), записать вопросительный знак и вставить эту константу и нажать Enter:
?wdLine
ниже будет выведено числовое представление этой константы.
А заменять эти константы их числовыми значениями в случае с поздним связыванием необходимо, т.к. Excel не знает их значений.
Попробую пояснить поподробнее про эти константы и почему их надо заменять какими-то числами: при подключении библиотеки Wordа(Word 12 Object Libbary) мы так же подключаем и все свойства, методы и константы, которые доступны из Wordа. И их использование напрямую становится доступно из Excel и мы можем смело написать что-то вроде wbLine и Excel поймет эту константу. При позднем же связывании мы уже не подключаем библиотеки Word(во избежание ошибок совместимости) и как следствие — методы, свойства и константы Wordа для Excel становятся чем-то неизвестным и не документированным и мы получим ошибку «Variable not defined»(если включена директива Option Explicit) при попытке назначить свойство через wdLine. Если же Option Explicit не включена — то хоть ошибки не будет, но и код будет работать неверно, т.к. для неизвестной для Excel переменной wbLine будет назначено значение 0(Empty). Поэтому и надо все константы другого приложения заменять их числовыми значениями.

Главная ошибка новичка
И хочу так же упомянуть про ошибку, которую очень часто совершают при обращении к одному приложению из другого. Допустим, необходимо скопировать из Word все данные в Excel. Часто начинающие делают это так:

Sub OpenWord()
    Dim objWrdApp As Object, objWrdDoc As Object
    'создаем новое приложение Word
    Set objWrdApp = CreateObject("Word.Application")
    'Можно так же сделать приложение Word видимым. По умолчанию открывается в скрытом режиме
    'objWrdApp.Visible = True
    'открываем документ Word - документ "Doc1.doc" должен существовать
    Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc")
    'Копируем из Word все данные, обращаясь к объекту Range документа
    Range.Copy
    'вставляем скопированное в ячейку А1 активного листа Excel
    ActiveSheet.Paste
    'закрываем документ Word без сохранения
    objWrdDoc.Close False
    'закрываем приложение Word
    objWrdApp.Quit
    'очищаем переменные Word - обязательно!
    Set objWrdDoc = Nothing: Set objWrdApp = Nothing
End Sub

На строке Range.Copy обязательно получите ошибку от VBA, указывающую, что нужен аргумент для объекта. Можно попробовать добавить этот аргумент: Range(1).Copy. Но все равно получим ошибку. Можно, конечно, указать даже ячейки: Range(«A1»).Copy. Но это приведет к тому, что скопирована будет ячейка А1 активного листа Excel.
Все дело в том, что мы хотим скопировать данные из Word-а, выполняя при этом код из Excel. А у Excel тоже есть объект Range с другими аргументами. И если не указать какому приложению, листу или документу принадлежит Range, то по умолчанию он будет отнесен к тому приложению, из которого выполняется код. Т.е. к Excel. Если совсем кратко об этом — всегда надо указывать какому приложению или объекту принадлежит используемый объект или свойство. Правильно код должен выглядеть так:

Sub OpenWord()
    Dim objWrdApp As Object, objWrdDoc As Object
    'создаем новое приложение Word
    Set objWrdApp = CreateObject("Word.Application")
    'Можно так же сделать приложение Word видимым. По умолчанию открывается в скрытом режиме
    'objWrdApp.Visible = True
    'открываем документ Word - документ "Doc1.doc" должен существовать
    Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc")
    'Копируем из Word все данные, обращаясь к объекту Range документа
    'при этом перед Range явно указываем откуда его брать - из документа Word -objWrdDoc("C:Doc1.doc")
    objWrdDoc.Range.Copy
    'вставляем скопированное из Word в активную ячейку активного листа Excel
    ActiveSheet.Paste
    'закрываем документ Word без сохранения
    objWrdDoc.Close False
    'закрываем приложение Word
    objWrdApp.Quit
    'очищаем переменные Word - обязательно!
    Set objWrdDoc = Nothing: Set objWrdApp = Nothing
End Sub

Вместо Range ту же ошибку делают и с Selection(потому что Selection часто присутствует в записанных макрорекордером макросах), т.к. этот объект есть и в Excel и в Word и без явного указания приложения будет относится к приложению, в котором записано.


В приложенном файле код немного отличается от представленных выше — в нем можно посмотреть как вставить текст из ячеек в определенные(созданные заранее) закладки Word-а. Это удобно для создания бланков в Word и заполнения их через Excel

Скачать пример:

  Tips_Macro_OpenWord.xls (49,5 KiB, 6 264 скачиваний)


А в архиве ниже — практически готовое решение заполнения всевозможных бланков Word из Excel. Как это работает. У нас есть таблица Excel с данными для заполнения бланков заявлений на пособия:
Исходная таблица
Обращаю внимание, что в первой строке расположены метки. Они нужны для того, чтобы код мог понять значения какого столбца в какое место шаблона Word должны попасть. А в самом шаблоне Word мы должны проставить эти самые метки:
Шаблон Word с метками
Фигурные скобки сделаны для того, чтобы код 100% искал и заменял только метку в шаблоне, исключая при этом замену случайного текста вне скобок(ведь слово «Должность» может встречаться и само по себе).
А здесь я схематично привел то, как будут происходить замены:
Схема замен
Сначала программа создаст новую папку, в которую и будет сохранять создаваемые файлы(имя папки состоит из даты и времени запуска кода). Далее программа циклом пройдется по каждой строке таблицы, создаст на основании шаблона Word(«Шаблон.doc») новый файл для этой строки, заполнит этот шаблона данными на основании меток, и сохранит созданный файл под новым именем. Сам файл шаблона при этом не изменяется — все метки в нем сохраняются как были настроены до запуска кода. Конкретно в приложенном коде значение для имени нового файла берется из первого столбца «ФИО с инициалами». Но это можно изменить в коде при необходимости. Делается это в этой строке:

'считываем фамилию с инициалами
sWDDocName = .Cells(lr, 1).Value

Что еще важно: файл шаблона Word должен находиться в той же папке, что и файл с кодом. Название файла в приложенном к статье файле должно быть «Шаблон.doc». Но его так же можно изменить, не забыв изменив его в коде в этой строке:

'имя шаблона Word с основным текстом и метками
Const sWDTmpl As String = "Шаблон.doc"

В общем-то, если хоть чуть-чуть разбираетесь, то поменять можно многое. А для тех, кто не разбирается достаточно будет просто создавать метки в файле Word и обозначать ими столбца в таблице Excel. Количество столбцов и строк в таблице код определяет автоматически и при изменении размеров таблицы ничего изменять не надо. Главное, чтобы метки находились в первой строке, вторая строка — заголовок(необязательно), а с третьей строки начинаются данные, которые и используются для наполнения шаблонов.
Скачать пример:

  Автосоздание бланков Word из таблицы Excel.zip (37,6 KiB, 1 470 скачиваний)

Примеры работы с тем же Outlook можно посмотреть в моих статьях:
Как отправить письмо из Excel?
Сохранить вложения из Outlook в указанную папку


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

To copy data from Excel to a Word file using VBA we need to access the word application using Excel VBA. In this tutorial we will learn how to open a word application, add a document and copy-paste data from excel to it.

In this article, we will use the Early Binding method to create an object of word application instead of using the late binding. You can read about it here in detail.

The Process Of Copying Excel Data To A Word File Using Excel VBA

To copy data from excel to a word file using VBA, we first need to open the Word Application of course. Then add a document to it (if you want a new document). Copy data from excel file. Select the paragraph on the doc and paste on it.Finally save and close the document. Each of these steps can be done easily from Excel. You will not need to interact with the Word Document.

Let’s get started with an example without getting any further into theory. Because Iron Man said, «Sometimes you gotta run before you can walk».

Example : Paste Excel Data To Word Using VBA

The below code is an example of how you can copy some range of excel and paste it into a new word document and save it on the drive to use later

'VBA Code To Write to Copy data from Excel to A Document

Sub ExcelToWord()

   'Using Early Binding

    Dim wordApp As Word.Application

    Dim mydoc As Word.Document

        

    

    'Creating a new instance of word only if there no other instances

    Set wordApp = New Word.Application

    

    

    'Making word App Visible

    wordApp.Visible = True

   

    'Creating a new document

    Set mydoc = wordApp.Documents.Add()


    

    'copying the content from excel sheet


    ThisWorkbook.Worksheets("sheet1").Range("A1:g20").Copy


    'Pasting on the document


    mydoc.Paragraphs(1).Range.PasteExcelTable _

                               LinkedToExcel:=False, _

                               WordFormatting:=False, 

                               RTF:=False

    'saving the document

    mydoc.SaveAs2 "MyDoc"

    

    'closing the document

    mydoc.Close

   

    'Emptying the Clipboard 

    CutCopyMode = False

   

End Sub

Explanation of the Code:

Well I have explained each step in the code itself using comments but let’s have some word about the lines we have used in this sub.

  ‘Created variables of word application and document type

    Dim wordApp As Word.Application

    Dim mydoc As Word.Document

Here we have declared two variables of the required types. We can do this because  we have already added the reference to the word application. You can do this by going to tools in menu. Find references option and then look for the word reference.

    ‘Creating a new instance of word only if there no other instances

    Set wordApp = New Word.Application

    ‘Making word App Visible

    wordApp.Visible = True

    ‘Creating a new document

    Set mydoc = wordApp.Documents.Add()

In the first line above, we are intentiating the wordApp variable with an object of type Word.App using the New keyword. This will open the Word Application.

In the second line we are making the word application visible so that we can work with it.

In the next line, we add a new document to the word application using Word.Documents.Add() function. This is stored in the mydoc variable.

    ‘copying the content from excel sheet

    ThisWorkbook.Worksheets(«sheet1»).Range(«A1:G20»).Copy

Here we are simply copying a range from excel. You must have done it before. It is stored on the clipboard.

    ‘Pasting on the document

    mydoc.Paragraphs(1).Range.PasteExcelTable _

                               LinkedToExcel:=False, _

                               WordFormatting:=False, 

                               RTF:=False

We are using the PasteExcelTable method of Paragraph.Range class of mydoc to paste data from clipboard.

 ‘saving the document

    mydoc.SaveAs2 «MyDoc»

    ‘closing the document

    mydoc.Close

    ‘Emptying the Clipboard 

    CutCopyMode = False

We are saving the document with the name MyDoc. Then we close the document using the Close function. Finally we release the clipboard to be used by others.

So yeah guys, this is how you can create a new Word document and copy Excel data to it using VBA. I have not gone into details as it would make the article exhaustingly long. This was only to learn how you can paste to a word document through Excel. I hope it helped you understand the process. If you have any questions regarding this article, you can contact me through the comments section below.

Related Articles:

Getting Started With Excel VBA UserForms| I will explain how to create a form in excel, how to use VBA toolbox, how to handle user inputs and finally how to store the user inputs. We will go through these topics using one example and step by step guide.

VBA variables in Excel| VBA stands for Visual Basic for Applications. It is a programming language from Microsoft. It is used with Microsoft Office applications such as MSExcel, MS-Word and MS-Access whereas VBA variables are specific keywords.

Excel VBA Variable Scope| In all the programming languages, we have variable access specifiers that define from where a defined variable can be accessed. Excel VBA is no Exception. VBA too has scope specifiers.

ByRef and ByVal Arguments | When an argument is passed as a ByRef argument to a different sub or function, the reference of the actual variable is sent. Any changes made into the copy of the variable, will reflect in the original argument.

Delete sheets without confirmation prompts using VBA in Microsoft Excel | Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.

Add And Save New Workbook Using VBA In Microsoft Excel 2016| In this code, we first created a reference to a workbook object. And then we initialized it with a new workbook object. The benefit of this approach is that you can do operations on this new workbook easily. Like saving, closing, deleting, etc

Display A Message On The Excel VBA Status Bar| The status bar in excel can be used as a code monitor. When your VBA code is lengthy and you do several tasks using VBA, you often disable the screen update so that you don’t see that screen flickering.

Turn Off Warning Messages Using VBA In Microsoft Excel 2016| This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific values. Countif function is essential to prepare your dashboard.

How to use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

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:

  1. Enable the Word Developer menu
  2. Record a Word macro
  3. Add the code to Excel VBA and amend
  4. Record macros in Excel if necessary
  5. 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.

Enable Word Developer Tab

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

Word VBA 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.

Word Record Macro Window

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

Word VBA Stop Recording

We can now view the code for opening a new Word Document in the Visual Basic Editor. Click: Developer -> Visual Basic.

Word Visual Basic Editor

Find the location of your recorded code in the Visual Basic Editor. In this example: Normal -> Modules -> NewMacros.

Automate Word from Excel

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.

VBA Word Object Library

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

Headshot Round

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:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. 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.
  4. 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:

Содержание

  • 1 Add a word document
  • 2 Close a document
  • 3 Generating Word ata from an Excel VBA program
  • 4 Load contact table from Access and create letter in Word
  • 5 Open an Existing Document
  • 6 Save a document
  • 7 Save Changes to a Document
  • 8 To close a specific document, you can close the active document or you can specify a document name:
  • 9 To create a new document that uses a specific template, use this:
  • 10 To save a document with a new name, use the SaveAs method

Add a word document

   <source lang="vb">

Sub wordDoc()

   Dim WordApp As Object
   Set WordApp = CreateObject("Word.Application")
   With WordApp
       .Documents.Add
   End With

End Sub

</source>
   
  

Close a document

   <source lang="vb">

Sub exitFor()

   Dim Doc As Document
   For Each Doc In Documents
       If Doc.Name = "Document1" Then Exit For
       Doc.Close
   Next Doc

End Sub

</source>
   
  

Generating Word ata from an Excel VBA program

   <source lang="vb">

Sub MakeMemos()

   Dim WordApp As Object
   Set WordApp = CreateObject("Word.Application")
   
   For i = 1 To 3
       Application.StatusBar = "Processing Record " & i
       SaveAsName = ThisWorkbook.Path & "test.doc"
       With WordApp
           .Documents.Add
           With .Selection
               .Font.Size = 14
               .Font.Bold = True
               .ParagraphFormat.Alignment = 1
               .TypeText Text:="M E M O R A N D U M"
               .TypeParagraph
               .TypeParagraph
               .Font.Size = 12
               .ParagraphFormat.Alignment = 0
               .Font.Bold = False
               .TypeText Text:="Date:" & vbTab & Format(Date, "mmmm d, yyyy")
               .TypeParagraph
               .TypeText Text:="To:" & vbTab & " Manager"
               .TypeParagraph
               .TypeText Text:="From:" & vbTab & _
                  Application.userName
               .TypeParagraph
               .TypeParagraph
               .TypeText "text"
               .TypeParagraph
               .TypeParagraph
               .TypeText Text:="Units Sold:" & vbTab & "asdf"
               .TypeParagraph
               .TypeText Text:="Amount:" & vbTab & Format(1000, "$#,##0")
           End With
               .ActiveDocument.SaveAs FileName:=SaveAsName
               .ActiveWindow.Close
       End With
   Next i
   WordApp.Quit
   Set WordApp = Nothing
   Application.StatusBar = ""
   MsgBox " memos were created and saved in " & ThisWorkbook.Path

End Sub

</source>
   
  

Load contact table from Access and create letter in Word

   <source lang="vb">

Sub ControlWord()

   Dim objWord As New Word.Application
   Dim rsContacts As New ADODB.Recordset
   Dim strLtrContent As String
   rsContacts.ActiveConnection = CurrentProject.Connection
   rsContacts.Open "tblContacts"
   
   objWord.Documents.Add
   
   Do While Not rsContacts.EOF
     strLtrContent = rsContacts("FirstName") & " " & rsContacts("LastName")
     strLtrContent = strLtrContent & rsContacts("Address") & vbCrLf
     strLtrContent = strLtrContent & rsContacts("City") & ", " & rsContacts("Region")
     strLtrContent = strLtrContent & "  " & rsContacts("PostalCode") 
     strLtrContent = strLtrContent & "Dear " & rsContacts("FirstName") & " "
     strLtrContent = strLtrContent & rsContacts("LastName") & ":" 
   
       objWord.Selection.EndOf
       objWord.Selection.Text = strLtrContent
   
       objWord.Selection.EndOf
       objWord.Selection.InsertBreak
       
       rsContacts.MoveNext
   Loop
   objWord.Visible = True
   objWord.PrintPreview = True

End Sub

</source>
   
  

Open an Existing Document

   <source lang="vb">

Sub Main()

   Dim wdApp As Word.Application
   
   Set wdApp = GetObject(, "Word.Application")
   wdApp.Documents.Open Filename:="C:Arrays.docx", ReadOnly:=True, AddtoRecentFiles:=False

End Sub

</source>
   
  

Save a document

   <source lang="vb">

Sub WordLateBound()

   Dim objWord As Object 
   Dim objDoc As Object 
   Set objWord = CreateObject("Word.Application") 
   Set objDoc = objWord.Documents.Add 
   objDoc.SaveAs "C:testdoc2.doc" 
   objDoc.Close 
   Set objDoc = Nothing 
   Set objWord = Nothing 

End Sub

</source>
   
  

Save Changes to a Document

   <source lang="vb">

Sub main()

   Dim wdApp As Word.Application
   
   Set wdApp = GetObject(, "Word.Application")
   wdApp.Documents.Save

End Sub

</source>
   
  

To close a specific document, you can close the active document or you can specify a document name:

   <source lang="vb">

Sub main()

   Dim wdApp As Word.Application
   Set wdApp = GetObject(, "Word.Application")
   wdApp.ActiveDocument.Close
   "or
   wdApp.Documents("Arrays.docx").Close

End Sub

</source>
   
  

To create a new document that uses a specific template, use this:

   <source lang="vb">

Sub add()

   Dim wdApp As Word.Application
   
   Set wdApp = GetObject(, "Word.Application")
   wdApp.Documents.Add Template:="Contemporary Memo.dot"

End Sub

</source>
   
  

To save a document with a new name, use the SaveAs method

   <source lang="vb">

Sub Main()

   Dim wdApp As Word.Application
   Set wdApp = GetObject(, "Word.Application")
   wdApp.ActiveDocument.SaveAs "C:MemoTest.docx"

End Sub

</source>

Понравилась статья? Поделить с друзьями:
  • Vba access recordset to excel
  • Vba excel 2007 массивы
  • Vba access excel object
  • Vba excel 2007 массив
  • Vba access excel cells