Создание нового документа Word или открытие существующего из кода VBA Excel. Методы Documents.Add и Documents.Open. Сохранение и закрытие документа.
Работа с Word из кода VBA Excel
Часть 2. Создание и открытие документов Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]
Новый документ Word создается из кода VBA Excel с помощью метода Documents.Add:
Sub Test1() Dim myWord As New Word.Application Dim myDocument As Word.Document Set myDocument = myWord.Documents.Add myWord.Visible = True End Sub |
Переменную myDocument можно объявить с типом Object, но тогда не будет ранней привязки к типу Word.Document и подсказок при написании кода (Auto List Members).
Открытие существующего документа
Существующий документ Word открывается из кода VBA Excel с помощью метода Documents.Open:
Sub Test2() Dim myWord As New Word.Application Dim myDocument As Word.Document Set myDocument = _ myWord.Documents.Open(«C:Документ1.docx») myWord.Visible = True End Sub |
Замените в этой процедуре строку «C:Документ1.docx» на адрес своего файла.
Подключение к открытому документу
Присвоение переменной ссылки на существующий экземпляр Word.Application осуществляется в VBA Excel с помощью функции GetObject:
Sub Test3() Dim myWord As Object, myDoc As Word.Document On Error GoTo Instr Set myWord = GetObject(, «Word.Application») Set myDoc = myWord.Documents(«Документ1.docx») myDoc.Range.InsertAfter «Добавляем новый текст, подтверждающий подключение к открытому документу.» Exit Sub Instr: MsgBox «Произошла ошибка: « & Err.Description End Sub |
Если открытого приложения Word нет, выполнение функции GetObject приведет к ошибке. Также произойдет ошибка, если не будет найден указанный документ (в примере — «Документ1.docx»).
Сохранение и закрытие документа
Сохранение нового документа
Чтобы сохранить из кода VBA Excel новый документ Word, используйте метод SaveAs2 объекта Document:
myDocument.SaveAs2 («C:Документ2.docx») |
Замените «C:Документ2.docx» на путь к нужному каталогу с именем файла, под которым вы хотите сохранить новый документ.
Сохранение изменений в открытом документа
Сохраняйте изменения в существующем документе с помощью метода Document.Save или параметра SaveChanges метода Document.Close:
‘Сохранение изменений документа myDocument.Save ‘Сохранение изменений документа ‘при закрытии myDocument.Close ‘по умолчанию True myDocument.Close True myDocument.Close wdSaveChanges ‘Закрытие документа без ‘сохранения изменений myDocument.Close False myDocument.Close wdDoNotSaveChanges |
Закрытие любого сохраненного документа
Метод Document.Close закрывает документ, но не приложение. Если работа с приложением закончена, оно закрывается с помощью метода Application.Quit.
Word VBA, Open Document
In this article I will explain how you can open a word document using VBA.
–
Opening Word Document:
If you are opening a word document from word you can use the code below:
Sub main()
Documents.Open ("D:TestFolderMain.docx")
End Sub
Where “D:TestFolderMain.docx” is the path where the word document is located.
–
Opening Word Document From Other Applications:
If you are opening a word document from another application, you would need to automate a word application first. This can be done using the code below:
Sub main()
Dim objWord As Object
'automate word application
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'open word document
objWord.documents.Open ("D:TestFolderMain.docx")
End Sub
For more information about automating word applications please see the article below:
- VBA, Automating Word From Excel
–
Using Open File Dialogs
You could also ask the user to choose the path of the word document using an open file dialogs. I have covered this topic in detail in the article below. Although the article was written for VBA for Excel, the concept can also be used in VBA for Word:
- Excel VBA, Open File Dialog
In the sample code below the user is asked to select the location of the word file from an open file dialog. After selecting the file, it is opened:
Sub main()
Dim intChoice As Integer
Dim strPath As String
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'if the user selects a file
If intChoice <> 0 Then
'get the path selected
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'opens the document
objWord.documents.Open (strPath)
End If
End Sub
See also:
- VBA, Automating Word From Excel
- Word Automation VBA, Common Errors
- Word VBA, Apply Macro to Multiple Files
- Word VBA, Modify Header For Multiple Files
- Word Automation VBA, Common Errors
- VBA, Write Excel Values to Word Document
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com
Open Word Document
This Word VBA Macro will open a word document from the specified directory:
Sub OpenDoc()
Dim strFile As String
strFile = "c:UsersNenadDesktopTest PM.docm" 'change to path of your file
If Dir(strFile) <> "" Then 'First we check if document exists at all at given location
Documents.Open strFile
End If
End Sub
Now you can interact with the newly opened document with the ActiveDocument Object. This code will add some text to the document.
ActiveDocument.Range(0, 0).Text = "Add Some Text"
Open Document to Variable
You can also open a Word document, immediately assigning it to a variable:
Sub OpenDoc()
Dim strFile As String
Dim oDoc as Document
strFile = "c:UsersNenadDesktopTest PM.docm" 'change to path of your file
If Dir(strFile) <> "" Then 'First we check if document exists at all at given location
Set oDoc = Documents.Open strFile
End If
End Sub
Allowing you to interact with the document via the variable oDoc.:
oDoc.Range(0, 0).Text = "Add Some Text"
Generally it’s best practice to open to a variable, giving you the ability to easily reference the document at any point.
Open Word Document From Excel
This VBA procedure will open a Word Document from another MS Office program (ex. Excel):
Sub OpenDocFromExcel()
Dim wordapp
Dim strFile As String
strFile = "c:UsersNenadDesktopTest PM.docm"
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open strFile
wordapp.Visible = True
End Sub
There are a number of factors in play with this code that will or might cause problems.
The reason for the error is that this code is running in Excel, so if objWord
is not used for Word syntax, and both Word and Excel use the same name for an object, VBA will try to use the Excel object model. In this case, as the file is in Word and not Excel, using objWord.Windows(Filename).Activate
should avoid this particular error.
Other considerations:
As with Excel, using Active
, Activate
or Selection
in Word VBA is unreliable and shouldn’t be used unless absolutely necessary. Better to work with the application’s objects, directly. So declare and instantiate a variable for the Word document and use that instead of ActiveDocument
:
Dim objDoc as Object 'Word.Document
Set objDoc = objWord.Documents.Open(strPath)
FileName = objDoc.Name
It’s unsure whether you’d really need to activate this window. It’s not necessary for manipulating a document’s content via VBA. If it’s in order to show it to the user, for editing, then by all means. I might wait until the end of the code, but that would be personal preference… In any case, it’s possible to address the document’s windows, specifically, rather than having VBA search for it:
objDoc.Windows(1).Activate
In order to transfer formatted content from one place (Range
) in any document to another place (Range
) in the same or another document, using bookmarks can be done in one step, without any selecting or activating:
objDoc.Bookmarks("Page1").Range.FormattedText = _
objWord.Documents("Template1").Bookmarks("Page1").Range.FormattedText
0 / 0 / 0 Регистрация: 11.08.2016 Сообщений: 55 |
|
1 |
|
11.08.2016, 22:07. Показов 14818. Ответов 16
Всем привет!Окажите содействие плиз: имеется папка с файлами .тхт необходим макрос который открывает все файлы из этой папки в Ворде(если возможно была признательна если можно было реализовать вывод диалогового окна выбора папки в котором сразу открывалась папка из которой нужно открыть файлы), затем нужно изменить на альбомную ориентацию , сделать 8 шрифт распечатать файл и сохранить в формате .doc .docx или .RTF тут не важно главное чтоб читался вордом и форматирование не слетало.Пробовала рекордером но получилось только изменение форматирования записать и печать. При сохранении он сохраняет одним и тем же именем т.е. в макрос записывается имя первого сохраняемого файла и все последующие пытается сохранить под тем же именем.такое реально реализовать ? Хелп ми))), около ста отчетов приходится лопатить вручную((((
0 |
pashulka 4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
||||||||
12.08.2016, 10:18 |
2 |
|||||||
Попробуйте так (только тестировать, разумеется, нужно на нескольких файлах)
~ Тоже самое, но без сообщений
0 |
roneta90 0 / 0 / 0 Регистрация: 11.08.2016 Сообщений: 55 |
||||
14.08.2016, 16:44 [ТС] |
3 |
|||
Добавлено через 31 минуту
Миниатюры
0 |
pashulka 4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
||||
14.08.2016, 16:55 |
4 |
|||
и правильно пишет, что не находит ибо должен быть слэш, но форум его автоматически убирает. приходится вводить два слэша, но стоит забыть об этом правиле и …
0 |
0 / 0 / 0 Регистрация: 11.08.2016 Сообщений: 55 |
|
16.08.2016, 21:17 [ТС] |
5 |
Не получается(( . Тоже самое. Может тогда оставим только чтобы менялся шрифт ориентация страницы и сохранение с именем исходного файла Миниатюры
0 |
4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
|
16.08.2016, 21:47 |
6 |
Смотрите пример, где для чистоты эксперимента, необходимо выбрать папку «Test_for_Roneta90»
0 |
0 / 0 / 0 Регистрация: 11.08.2016 Сообщений: 55 |
|
28.08.2016, 17:20 [ТС] |
7 |
тоже самое)))Ладно , впринципе открою файлы с помощью cntrl+0 . тогда макрос прописать чтобы менял ориентацию шрифт и сохранял с текущим именем файла и в формате док или докх или ртф вообщем чтоб форматиование сохранялось
0 |
1 / 1 / 0 Регистрация: 12.06.2015 Сообщений: 93 |
|
07.09.2016, 21:10 |
8 |
а этот код подойдет для екселя, а не для ворда?
0 |
4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
|
07.09.2016, 21:41 |
9 |
Выбор папки и перебор .txt файлов можно использовать и в Excel
0 |
1 / 1 / 0 Регистрация: 12.06.2015 Сообщений: 93 |
|
07.09.2016, 21:45 |
10 |
проблема в вышеперложенных вариантах в том, что открывается путь, но! нет возможности выбрать в ручном режиме подходящий файл по даному пути
0 |
4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
|
07.09.2016, 21:50 |
11 |
Проблема в людях, которые пытаются использовать диалог выбора папки, для указания файла, хотя для последнего есть свои варианты.
0 |
1 / 1 / 0 Регистрация: 12.06.2015 Сообщений: 93 |
|
07.09.2016, 21:57 |
12 |
какие варианты есть?
0 |
pashulka 4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
||||||||
07.09.2016, 22:07 |
13 |
|||||||
Причём в справке есть готовый пример — для выбора .txt файла или
0 |
1 / 1 / 0 Регистрация: 12.06.2015 Сообщений: 93 |
|
07.09.2016, 22:13 |
14 |
спасибо, а можно чтобы автоматически при этом открывалась определенная папка?
0 |
pashulka 4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
||||
07.09.2016, 22:30 |
15 |
|||
Для первого варианта ChDrive + ChDir, но если не прокатит, то во втором варианте есть свойство InitialFileName
0 |
Heroes 1 / 1 / 0 Регистрация: 12.06.2015 Сообщений: 93 |
||||
07.09.2016, 22:47 |
16 |
|||
у меня получилось так:
0 |
pashulka 4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
||||
07.09.2016, 23:09 |
17 |
|||
Это прокатит только если в момент выполнения макроса текущим будет диск «C» и Вы не откажетесь от выбора файла. Т.е. более универсальным является следующий вариант (хотя и здесь, не помешало бы, проверить указанную папку на наличие)
0 |
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: