Создание нового документа 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
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date |
---|---|---|---|---|---|---|
Documents.Open Method (Word) |
vbawd10.chm158072851 |
vbawd10.chm158072851 |
word |
Word.Documents.Open |
9e61e9d5-58d1-833a-5f93-b87299deb400 |
06/08/2017 |
Documents.Open Method (Word)
Opens the specified document and adds it to the Documents collection. Returns a Document object.
Syntax
expression . Open( FileName , ConfirmConversions , ReadOnly , AddToRecentFiles , PasswordDocument , PasswordTemplate , Revert , WritePasswordDocument , WritePasswordTemplate , Format , Encoding , Visible , OpenConflictDocument , OpenAndRepair , DocumentDirection , NoEncodingDialog )
expression Required. A variable that represents a Documents collection.
Parameters
Name | Required/Optional | Data Type | Description |
---|---|---|---|
FileName | Required | Variant | The name of the document (paths are accepted). |
ConfirmConversions | Optional | Variant | True to display the Convert File dialog box if the file isn’t in Microsoft Word format. |
ReadOnly | Optional | Variant | True to open the document as read-only. This argument doesn’t override the read-only recommended setting on a saved document. For example, if a document has been saved with read-only recommended turned on, setting the ReadOnly argument to False will not cause the file to be opened as read/write. |
AddToRecentFiles | Optional | Variant | True to add the file name to the list of recently used files at the bottom of the File menu. |
PasswordDocument | Optional | Variant | The password for opening the document. |
PasswordTemplate | Optional | Variant | The password for opening the template. |
Revert | Optional | Variant | Controls what happens if FileName is the name of an open document. True to discard any unsaved changes to the open document and reopen the file. False to activate the open document. |
WritePasswordDocument | Optional | Variant | The password for saving changes to the document. |
WritePasswordTemplate | Optional | Variant | The password for saving changes to the template. |
Format | Optional | Variant | The file converter to be used to open the document. Can be one of the WdOpenFormat constants. The default value is wdOpenFormatAuto . To specify an external file format, apply the OpenFormat property to a FileConverter object to determine the value to use with this argument. |
Encoding | Optional | Variant | The document encoding (code page or character set) to be used by Microsoft Word when you view the saved document. Can be any valid MsoEncoding constant. For the list of valid MsoEncoding constants, see the Object Browser in the Visual Basic Editor. The default value is the system code page. |
Visible | Optional | Variant | True if the document is opened in a visible window. The default value is True . |
OpenConflictDocument | Optional | Variant | Specifies whether to open the conflict file for a document with an offline conflict. |
OpenAndRepair | Optional | Variant | True to repair the document to prevent document corruption. |
DocumentDirection | Optional | WdDocumentDirection | Indicates the horizontal flow of text in a document. The default value is wdLeftToRight . |
NoEncodingDialog | Optional | Variant | True to skip displaying the Encoding dialog box that Word displays if the text encoding cannot be recognized. The default value is False . |
Return Value
Document
Security
Avoid using hard-coded passwords in your applications. If a password is required in a procedure, request the password from the user, store it in a variable, and then use the variable in your code. For recommended best practices on how to do this, see Security Notes for Microsoft Office Solution Developers.
Example
This example opens MyDoc.doc as a read-only document.
Sub OpenDoc() Documents.Open FileName:="C:MyFilesMyDoc.doc", ReadOnly:=True End Sub
This example opens Test.wp using the WordPerfect 6.x file converter.
Sub OpenDoc2() Dim fmt As Variant fmt = Application.FileConverters("WordPerfect6x").OpenFormat Documents.Open FileName:="C:MyFilesTest.wp", Format:=fmt End Sub
See also
Concepts
Documents Collection Object
Если есть необходимость обратиться к данным, хранящимся в текстовом файле приложения Word, или наоборот, передать данные из Excel в такой файл, то возникнет необходимость запуска приложения, в формате которого сохранен файл. Ниже приведен программный код макроса VBA для Microsoft Excel, запускающий приложение Word.
Если для передачи данных из Excel в Word необходим новый документ, можно воспользоваться примером кода, приведенного ниже. Макрос проверяет запущен ли Word и если он запущен, то добавляет новый документ, если же не запущен, то сначала запускает Word, а затем добавляет новый документ.
Sub Zapusk_Word_iz_Excel_01() Dim objWrdApp As Object Dim objWrdDoc As Object On Error Resume Next Set objWrdApp = GetObject(, "Word.Application") If objWrdApp Is Nothing Then Set objWrdApp = CreateObject("Word.Application") Set objWrdDoc = objWrdApp.Documents.Add objWrdApp.Visible = True End If Set objWrdDoc = objWrdApp.Documents.Add Set objWrdDoc = Nothing Set objWrdApp = Nothing End Sub
Для того, чтобы перенести этот программный код на свой компьютер, наведите курсор мыши на поле с программным кодом, нажмите на одну из двух кнопкок в правом верхнем углу этого поля, скопируйте программный код и вставьте его в модуль проекта на своем компьютере (подробнее о том, как сохранить программный код макроса).
Макрос, запускающий Word из Excel и открывающий существующий документ
Если для передачи данных из Word в Excel, необходимо открыть файл с заданным именем, то можно использовать аналогичный код, в котором вместо добавления нового документа открывается документ существующий:
Sub Zapusk_Word_iz_Excel_02() Dim objWrdApp As Object Dim objWrdDoc As Object On Error Resume Next Set objWrdApp = GetObject(, "Word.Application") If objWrdApp Is Nothing Then Set objWrdApp = CreateObject("Word.Application") Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc") objWrdApp.Visible = True End If Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc") Set objWrdDoc = Nothing Set objWrdApp = Nothing End Sub
При копировании этого кода на свой компьютер, не забудьте изменить путь к файлу и его имя. Запуск приложения можно сделать невидимым, если в коде изменить True на False.
Макрос для передачи данных из Excel в Word
Ниже приведен программный код макроса, копирующий в активной рабочей книге Excel диапазон с данными A1:E2 и вставляющий его в открытый документ Word. После передачи данных из Excel в Word производится закрытие документа с сохранением изменений и выход из приложения.
Sub Peredacha_Dannyh_iz_Excel_v_Word() Dim objWrdApp As Object Dim objWrdDoc As Object On Error Resume Next Set objWrdApp = GetObject(, "Word.Application") If objWrdApp Is Nothing Then Set objWrdApp = CreateObject("Word.Application") Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc") objWrdApp.Visible = False End If Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc") Range("A1:E2").Copy objWrdDoc.Range(0).Paste objWrdDoc.Close True 'True - с сохранением, False - без сохранения objWrdApp.Quit Set objWrdDoc = Nothing Set objWrdApp = Nothing End Sub