Word object documents open

Создание нового документа 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.

Аннотация: Лекция посвящена описанию коллекции Documents и объекта Document приложения Microsoft Word.

10.1. Коллекция Documents — открытые документы

Коллекция Documents включает в себя открытые документы с их полезными методами и свойствами. Наряду с объектами Document, которые входят в коллекцию, здесь мы подробнее рассмотрим уже известный вам объект ActiveDocument,

ActiveDocument имеет те же свойства и методы, что и любой Documentобъект, однако, часто объектом ActiveDocument удобнее пользоваться.

Так же обратите внимание на объект ThisDocument. Он представляет собой тот документ, из которого запущен макрос.

Для начала давайте рассмотрим свойства и методы коллекции, а потом займемся объектом Document.

10.2. Методы коллекции Documents

10.2.1. Add — создаем новый документ

Этот метод добавляет новый объект Document в коллекцию Documents — то есть создает новый документ. Его можно использовать так (листинг 10.1.):

Documents.Add


Листинг
10.1.
Создаем новый документ

При выполнении такого кода будет создан новый пустой документ на основе шаблона Normal. Чтобы ссылка на созданный документ была присвоена переменной, можете воспользоваться такой конструкцией (листинг 10.2.):

Dim obj_NewDoc As Word.Document
    Set obj_NewDoc = Application.Documents.Add


Листинг
10.2.
Создаем новый документ и присваиваем ссылку на него объектной переменной

Здесь мы сначала объявили переменную соответствующего типа, а потом присвоили ей ссылку на новый документ.

Метод Add может принимать несколько необязательных параметров. Полный вызов метода выглядит так:

Documents.Add (Template, NewTemplate, DocumentType, Visible)

Template (Шаблон) — отвечает за шаблон, который будет использован при создании файла. По умолчанию это Normal.dotm.

NewTemplate (Новый шаблон) — если этот параметр установлен в True — файл будет обрабатываться как шаблон. По умолчанию установлен в False.

DocumentType (Тип документа) — очень полезный параметр, который позволяет создавать документы различных типов. На тип документа указывает одна из констант, в частности, по умолчанию это wdNewBlankDocument — то есть пустой документ. Так же этот параметр может принимать значения wdNewEmailMessage (Почтовое сообщение), wdNewFrameset (Документ с рамками — такие используются при создании WEB-страниц), wdNewWebPage (WEB-страница).

Visible (Видимость) — по умолчанию установлен в True — то есть создаваемый документ видим для пользователя. Если вы хотите, сначала сформировать новый документ, а уже потом показать его пользователю — установите это свойство в False, а после окончания формирования документа — воспользуйтесь свойством Visible созданного документа, чтобы отобразить его.

10.2.2. Open — открываем документы

Метод Open используется для открытия существующих файлов, возвращая объект типа Document. Файл, имя которого задано при вызове метода, открывается и добавляется в коллекцию Documents. Метод может принимать множество параметров, однако основной — это FileName, который и задает имя открываемого файла.

Например, для открытия файла 1.docm, расположенного в корневом каталоги диска С, можно воспользоваться кодом из листинга 10.3.

Documents.Open FileName:="C:1.docm"


Листинг
10.3.
Открываем существующий документ

10.2.3. Close — закрываем все документы

Метод Close используется для закрытия всех открытых документов. Применяют его достаточно редко — удобнее закрывать каждый конкретный документ по отдельности. При вызове метода без параметров система задаст вопрос о сохранении документов, которые были изменены (листинг 10.4.).

Documents.Close


Листинг
10.4.
Закрываем все документы

Полный вызов метода выглядит так:

Documents.Close(SaveChanges, OriginalFormat, RouteDocument)

Среди параметров для нас наибольший интерес представляют первых два.

SaveChanges (Сохранить изменения) отвечает за сохранение изменений. По умолчанию он установлен в wdPromptToSaveChanges (Вывести запрос о сохранении), так же он может быть установлен в wdDoNotSaveChanges (Не сохранять изменения) и wdSaveChanges (Сохранить изменения). Как видите, с помощью параметра wdSaveChanges можно организовать удобное и быстрое закрытие множества документов с сохранением изменений

OriginalFormat (Формат) — отвечает за формат сохраняемого документа. Может принимать различные значения: wdOriginalDocumentFormat (Оригинальный формат документа), wdPromptUser (Запросить формат у пользователя), wdWordDocument (Документ Word).

Вот как выглядит вызов метода Close, который сохраняет все открытые документы и закрывает их (листинг 10.5.)

Documents.Close (wdSaveChanges)


Листинг
10.5.
Закрываем все документы, предварительно сохранив

Учтите — если какие-то из документов сохраняются в первый раз — вы получите запрос об имени документа.

10.2.4. Item — обращаемся к отдельным документам

10-01-Item.docm — пример к п. 10.2.4.

Метод Item позволяет обращаться к открытым документам (то есть — к объектам Document ), используя их индексы или имена. Нумерация документов начинается с единицы. Чтобы узнать общее количество открытых документов, можно воспользоваться свойством Documents.Count.

Например, с помощью нижеприведенного кода из листинга 10.6 мы поочередно выводим имена открытых документов с указанием номера документа в коллекции:

For i = 1 To Documents.Count
    MsgBox (Documents.Item(i).Name & _
    " - документ номер " & i)
Next i


Листинг
10.6.
Выводим имена и номера документов

Очевидно, что свойство Count коллекции Documents позволяет узнать количество открытых документов, а свойство Name объекта Item(i) содержит имя документа с индексом i.

На рис. 10.1 вы можете видеть одно из окон с сообщением об имени и номере документа.

Окно сообщения об имени и номере документа

Рис.
10.1.
Окно сообщения об имени и номере документа

К документам в коллекции Documents можно обращаться и по именам. Также, при обращении к документу необязательно напрямую указывать метод Item — в листинге 10.7 вы можете видеть различные варианты обращения к документу.

MsgBox Documents("Мой документ.docx").Name
   MsgBox Documents.Item("Мой документ.docx").Name
   MsgBox Documents(1).Name


Листинг
10.7.
Выводим имена и номера документов

10.2.5. Save — сохранение всех документов

Метод Save сохраняет все документы коллекции. Если документ сохраняется впервые — будет выведено окно с запросом имени файла. В листинге 10.8 приведен пример вызова метода.

Documents.Save


Листинг
10.8.
Сохраним все документы в коллекции

10.3. Свойства коллекции Documents

Среди свойств коллекции Documents нас будет интересовать лишь одно — Count. Это свойство позволяет узнать количество элементов в коллекции Documents, то есть — количество открытых документов. В листинге 10.9 мы выводим в окне сообщения количество открытых документов

MsgBox ("Количество открытых документов: " & _
    Documents.Count)


Листинг
10.9.
Сохраним все открытые документы

10.4. Объект Document

Объект Document — это открытый документ. У него есть множество свойств и методов, которые активно используются при программной работе с документами. Здесь мы рассмотрим важнейшие из них.

Использование Word в приложениях на Visual Basic 6 открывает широчайшие возможности для создания профессионально оформленных документов (например отчетов). Это часто необходимо при работе в фирме или на предприятии для обеспечения документооборота. Основным преимуществом использования Wordа в этом случае является то, что практически на всех компьютерах, используемых в фирмах и на предприятиях установлены Windows и пакет Microsoft Office. Поэтому подготовленные документы Word не требуют каких-либо дополнительных усилий для их просмотра, печати и редактирования. Единственное что нужно помнить, это то что работа через автоматизацию OLE (связывание и внедрение объектов) на деле оказывается довольно медленной технологией, хотя и очень полезной.

Чтобы использовать объекты Word в Visual Basic , необходимо инсталлировать сам Word. После этого вы получаете в своё распоряжение библиотеку Microsoft Word Object Library, которую нужно подключить к текущему проекту через диалоговое окно «Разработать»>>»Ссылки» (References) и указать Microsoft Word 9.0 Object Library (для Word 2000).

Два самых важных объекта Word это Word.Application и Word.Document. Они обеспечивают доступ к экземпляру приложения и документам Word.

Поэтому в раздел Generals «Общее» формы введите следующий код для объявления объектных переменных приложения Word и документа Word.

Dim WordApp As Word.Application '  экземпляр приложения
Dim DocWord As Word.Document'  экземпляр документа

Чтобы создать новый экземпляр Word, введите такой код кнопки;

Private Sub Комманда1_Click()

'создаём  новый экземпляр Word-a
Set WordApp = New Word.Application

'определяем видимость Word-a по True - видимый,
'по False - не видимый (работает только ядро)
WordApp.Visible = True

'создаём новый документ в Word-e
Set DocWord = WordApp.Documents.Add

'// если нужно открыть имеющийся документ, то пишем такой код
'Set DocWord = WordApp.Documents.Open("C:DDD.doc")

'активируем его
DocWord.Activate

End Sub

Для форматирования печатной области документа используйте данный код:

(вообще-то Word использует для всех размеров своих элементов пункты, поэтому для использования других единиц измерения, необходимо использовать встроенные функции форматирования.)

Например:

  • CentimetersToPoints(Х.ХХ) — переводит сантиметры в пункты.
  • MillimetersToPoints(X.XX) — переводит миллиметры в пункты
Private Sub Комманда2_Click()

'отступ слева "2,0 сантиметра"
DocWord.Application.Selection.PageSetup.LeftMargin = CentimetersToPoints(2)

'отступ справа "1,5 сантиметра"
DocWord.Application.Selection.PageSetup.RightMargin = CentimetersToPoints(1.5)

'отступ сверху "3,5 сантиметра"
DocWord.Application.Selection.PageSetup.TopMargin = CentimetersToPoints(3.5)

'отступ снизу "4,45 сантиметра"
DocWord.Application.Selection.PageSetup.BottomMargin = CentimetersToPoints(4.45)

End Sub

Небольшое отступление.

Для того чтобы в своём приложении не писать постоянно одно и тоже имя объекта, можно использовать оператор With.

Например код находящейся выше можно переписать так:

With DocWord.Application.Selection.PageSetup
.LeftMargin = CentimetersToPoints(2)
.RightMargin = CentimetersToPoints(1.5)
.TopMargin = CentimetersToPoints(3.5)
.BottomMargin = CentimetersToPoints(4.45)
End With

Если вам необходимо создать документ Word с нестандартным размером листа, то используйте данный код:

With DocWord.Application.Selection.PageSetup
.PageWidth = CentimetersToPoints(20)    'ширина листа (20 см)
.PageHeight = CentimetersToPoints(25)   'высота листа (25 см)
End With

Данный код меняет ориентацию страницы (практически меняет местами значения ширины и высоты листа):

 
DocWord.Application.Selection.PageSetup.Orientation = wdOrientLandscape
  • wdOrientLandscape — альбомная ориентация ( число 1)
  • wdOrientPortrait — книжная ориентация ( число 0)

Для сохранения документа под новым именем и в определенное место
используйте данный код код:

'сохраняем документ как
DocWord.SaveAs "c:DDD.doc"

После такого сохранения вы можете про ходу работы с документом сохранять его.

'сохраняем документ
DocWord.Save

Или проверить, были ли сохранены внесенные изменения свойством Saved и если изменения не были сохранены — сохранить их;

If DocWord.Saved=False Then DocWord.Save

Завершив работу с документом, вы можете закрыть сам документ методом Close и сам Word методом Quit.

'закрываем документ (без запроса на сохранение)
DocWord.Close True

'закрываем Word (без запроса на сохранение)
WordApp.Quit True

'уничтожаем обьект - документ
Set DocWord = Nothing

'уничтожаем обьект - Word
Set WordApp = Nothing

Если в методах Close и Quit не использовать необязательный параметр True то Word запросит согласие пользователя (если документ не был перед этим сохранён) на закрытие документа.

Если вам необходимо оставить Word открытым, просто не используйте методы Close и Quit.

Если вам необходимо поставить пароль на документ, то используйте код:

DocWord.Protect wdAllowOnlyComments, , "123456789"

Пример программы можно скачать здесь.

Word VBA, Open Document

Jun 07, 2015 in Dialogs

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

The Documents collection, available from the Application object’s Documents property, contains a collection of Document objects currently open in Word. It also has methods used to access a Document in the collection, create a new document, open an existing document, close all the documents, and save all the documents.

Iterating over the Open Documents

The documents collection can be iterated over using the foreach keyword in C#. Listing 8-18 shows a simple example of iterating over the open documents in Word and printing the name of each document to the console.

Listing 8-18. Iterating over the Documents Collection Using foreach

foreach (Word.Document doc in Application.Documents)
{
 Console.WriteLine(doc.Name);
}

Accessing a Document in the Documents Collection

To access a Document in the Documents collection, you use the get_Item method, which returns a Document object. The get_Item method has an Index parameter passed by reference that is of type object. You can pass an int representing the 1-based index of the document in the collection you want to access.

Alternatively, you can pass a string representing the name of the document you want to access. The name you pass for a document is the full name of the file if it has been saved (for example, «c:Documents and SettingsJohnDesktop Doc1.doc»). If the document has not yet been saved, the name to pass is the temporary name that Word creates for a new document. This temporary name is typically something like Document1, with no file extension. Listing 8-19 shows an example of calling get_Item with a 1-based index and a string index.

Listing 8-19. A VSTO Customization That Uses get_Item to Get a Document

private void ThisDocument_Startup(object sender, EventArgs e)
{
 // Add 5 documents
 for (int i = 0; i < 5; i++)
 {
 Application.Documents.Add(ref missing,
 ref missing, ref missing, ref missing);
 }

 // Iterate over the open documents using foreach
 foreach (Word.Document doc in Application.Documents)
 {
 MessageBox.Show(doc.Name);
 }

 // Get a document by 1-based index.
 object index = 2;
 Word.Document doc1 = Application.Documents.get_Item(ref index);
 MessageBox.Show(String.Format(
 "The document at index {0} is {1}.",
 index, doc1.FullName));

 // Get a document by full name
 object stringIndex = doc1.FullName;
 Word.Document doc2 = Application.Documents.get_Item(ref index);
 MessageBox.Show(String.Format(
 "The document at string index {0} is {1}.",
 stringIndex, doc2.FullName));
}

You can also use the Count property to determine the number of open documents. You should check the Count property before accessing a document by index.

Creating a New Document

To create a new document, you can use the Documents collection’s Add method. The Add method returns the newly created Document object. It takes four optional by reference parameters of type object, as described in Table 8-5.

Table 8-5. Optional Parameters for the Documents Collection’s Add Method

Parameter Name

What It Does

Template

Pass the short name of the template to be used (for example, «mytemplate.dot») if the template is in the Templates collection. If the template is not in the Templates collection, pass the full filename to the template (for example, «c:mytemplates template1.dot»). If you omit this parameter, Word uses the Normal template.

NewTemplate

Pass the bool value true if the document should be opened as a template. The default is false.

DocumentType

Pass a member of the WdNewDocumentType enumeration: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default is wdNewBlankDocument.

Visible

Pass the bool value true if the document should be opened in a visible window. The default is TRue.

Opening an Existing Document

To open an existing document, use the Documents collection’s Open method, which returns the opened Document object. The Open method takes one required object parameter to which you pass the string representing the filename to open. The Open method also takes 15 optional by reference parameters of type object, as described in Table 8-6.

Table 8-6. Optional Parameters for the Documents Collection’s Open Method

Parameter Name

What It Does

ConfirmConversions

Pass true to display the Convert File dialog box if the filename passed to Open is not in Microsoft Word format.

ReadOnly

Pass true to open the document as read-only. If the document is already set to read-only on disk, passing false will not affect the read-only status of the document. The default is false.

AddToRecentFiles

Pass TRue to add the file name to the list of recently used files in the File menu. The default is true.

PasswordDocument

Pass a string representing the password for opening the document if the document is password protected.

PasswordTemplate

Pass a string representing the password for opening the template if the template is password protected.

Revert

If the document you are opening with the Open method is already opened in Word, pass TRue to discard any unsaved changes in the already open document. Pass false to activate the already open document.

WritePasswordDocument

Pass a string representing the password for saving changes to the document if the document is password protected.

WritePasswordTemplate

Pass a string representing the password for saving changes to the template if the template is password protected.

Format

Pass a member of the WdOpenFormat enumeration specifying the file conversion to be used when opening the document.

Encoding

Pass a member of the Office.MsoEncoding enumeration specifying the code page or character set to be used when you open the document.

Visible

Pass true to open the document in a visible window. The default is true.

OpenConflictDocument

Pass true to open the conflict file for a document that has offline conflicts.

OpenAndRepair

Pass true to try to repair a corrupted document.

DocumentDirection

Pass a member of the WdDocumentDirection enumeration specifying the horizontal flow of text in the opened document.

NoEncodingDialog

Pass true to prevent Word from displaying the Encoding dialog box if the text encoding of the document cannot be determined.

Listing 8-20 shows the simplest possible way to call the Open method to open a document. The code omits all the parameters by passing by reference the missing class member variable in VSTO, which is of type object and has been set to System.Type.Missing.

Listing 8-20. A VSTO Customization That Uses the Open Method to Open a Document

private void ThisDocument_Startup(object sender, EventArgs e)
{
 object fileName = "c:	est.doc";

 Word.Document doc = Application.Documents.Open(ref fileName,
 ref missing, ref missing, ref missing,
 ref missing, ref missing, ref missing,
 ref missing, ref missing, ref missing,
 ref missing, ref missing, ref missing,
 ref missing, ref missing, ref missing);

 MessageBox.Show(String.Format(
 "Just opened {0}.", doc.Name));
}

Closing All Open Documents

The Close method on the Documents collection closes all the open documents in Word. It takes three optional parameters of type object by reference. The first optional parameter, called SaveChanges, is of type object and can be passed a member of the WdSaveOptions enumerationeither wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges. The second optional parameter, called OriginalFormat, is of type object and can be passed a member of the Wd-OriginalFormat enumeration. The second parameter controls Word’s behavior when saving a changed document whose original format was not Word document format. This parameter can be passed wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument. The final optional parameter is called RouteDocument and is of type object. Passing true for this parameter routes the document to the next recipient if a routing slip is attached.

It is also possible to close an individual document using the Document object’s Close method, as discussed later in this chapter. You have already learned how to use the Application object’s Quit method as a third way to close all open documents and quit Word. The Quit method takes the same parameters as Documents.Close and Document.Close.

Saving All Open Documents

The Save method on the Documents collection saves all the open documents in Word. It takes two optional parameters. The first optional parameter, called NoPrompt, is of type object and can be set to TRue to have Word automatically save all open documents without prompting the user. The second optional parameter, called OriginalFormat, is of type object and can be passed a member of the WdOriginalFormat enumeration. The second parameter controls Word’s behavior when saving a changed document whose original format was not Word document format.

It is also possible to save an individual document using the Document object’s Save or SaveAs methods, as discussed later in this chapter.

Понравилась статья? Поделить с друзьями:
  • Word numbers in english for
  • Word not checking spelling correctly
  • Word not checking spelling as i type
  • Word not changing font
  • Word not capitalizing i