Word vba document close

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Document.Close method (Word)

vbawd10.chm158008401

vbawd10.chm158008401

word

Word.Document.Close

59603a58-17ee-bc65-597b-6200e8be9fbc

06/08/2017

medium

Document.Close method (Word)

Closes the specified document.

Syntax

expression.Close (SaveChanges, OriginalFormat, RouteDocument)

expression Required. A variable that represents a Document object.

Parameters

Name Required/Optional Data type Description
SaveChanges Optional Variant Specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.
OriginalFormat Optional Variant Specifies the save format for the document. Can be one of the following WdOriginalFormat constants: wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument.
RouteDocument Optional Variant True to route the document to the next recipient. If the document does not have a routing slip attached, this argument is ignored.

Example

This example prompts the user to save the active document before closing it. If the user clicks Cancel, error 4198 (command failed) is trapped and a message is displayed.

On Error GoTo errorHandler 
ActiveDocument.Close _ 
 SaveChanges:=wdPromptToSaveChanges, _ 
 OriginalFormat:=wdPromptUser 
errorHandler: 
If Err = 4198 Then MsgBox "Document was not closed"

See also

Document Object

[!includeSupport and feedback]

Closes the specified document or documents.

expression.Close(SaveChanges, OriginalFormat, RouteDocument)

expression    Required. An expression that returns one of the above objects.

SaveChanges   Optional Variant. Specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.

OriginalFormat   Optional Variant. Specifies the save format for the document. Can be one of the following WdOriginalFormat constants: wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument.

RouteDocument   Optional Variant. True to route the document to the next recipient. If the document doesn’t have a routing slip attached, this argument is ignored.

ShowClose method as it applies to the MailMergeDataSource, Pane, and Task objects.

Closes the specified Mail Merge data source, pane, or task.

expression.Close

expression    Required. An expression that returns one of the above objects.

ShowClose method as it applies to the Window object.

Closes the specified window.

expression.Close(SaveChanges, RouteDocument)

expression    Required. An expression that returns one of the above objects.

SaveChanges   Optional Variant. Specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.

RouteDocument   Optional Variant. True to route the document to the next recipient. If the document doesn’t have a routing slip attached, this argument is ignored.

Example

ShowAs it applies to the Document object.

This example prompts the user to save the active document before closing it. If the user clicks Cancel, error 4198 (command failed) is trapped and a message is displayed.

On Error GoTo errorHandler
ActiveDocument.Close _
    SaveChanges:=wdPromptToSaveChanges, _
    OriginalFormat:=wdPromptUser
errorHandler:
If Err = 4198 Then MsgBox "Document was not closed"
				

ShowAs it applies to the Pane object.

This example closes the active pane if the active window is split.

If ActiveDocument.ActiveWindow.Panes.Count >= 2 Then _
    ActiveDocument.ActiveWindow.ActivePane.Close
				

ShowAs it applies to the Task object.

This example activates Microsoft Excel and then closes it.

For Each myTask In Tasks
    If InStr(myTask.Name, "Microsoft Excel") > 0 Then
        myTask.Activate
        myTask.Close
    End If
Next myTask
				

ShowAs it applies to the Window object.

This example closes the active window of the active document and saves it.

ActiveDocument.ActiveWindow.Close SaveChanges:=wdSaveChanges
				

I have the following code to open the manual for an Excel Workbook application I have developed:

Sub OpenManual()

'Word.Application.Documents.Open "\filePathFormFlow To MSExcelFeedSampleReport-Manual.docx"

Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True

objWord.Documents.Open "\filePathFormFlow To MSExcelFeedSampleReport-Manual.docx"

End Sub

This gives me 2 issues though:

  1. The document opens, but in the background. The user doesn’t know the document has opened unless they know to check Microsoft Word in the Taskbar.
  2. When I try to close the word document I receive:
    This file is in use by another application or user. (C:UsersMeAppData…Normal.dotm)

When I click ok on that dialogue, I receive a «Save As» screen.

If I cancel out of that and try to close the blank Microsoft Word instance I then get:

Changes have been made that affect the global template, Normal. Do you want to save those changes?

Then if I click No, everything finally closes.

Can anyone help me out with these 2 issues? Do I need to release the object somehow? Have never seen this before.

EDIT:

After trying @Layman-Coders method:

Sub OpenManual()
'Word.Application.Documents.Open "\filePathFormFlow To MSExcelFeedSampleReport-Manual.docx"

'Open an existing Word Document from Excel
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True

' Should open as the forefront
objWord.Activate

'Change the directory path and file name to the location
'of the document you want to open from Excel
objWord.Documents.Open "\filePathFormFlow To MSExcelFeedSampleReport-Manual.docx"

objWord.Quit
Set objWord = Nothing

End Sub

When I have one other word document open and click the button, the following occurs:

  1. Manual opens in the forefront, but I immediately receive This file is in use by another application or user. (C:UsersMeAppData...Normal.dotm)
  2. I press OK and receive the Save As dialogue.
  3. Cancel out of the Save As dialogue and am presented my Manual document.
  4. When I click the Red X to close the document, I receive Changes have been made that affect the global template, Normal. Do you want to save those change? I click No and the document closes.

If this document is the first instance of word I have opening:

  1. The document opens.
  2. As soon as code hits the objWord.Quit line the document immediately closes.

I am just wanting the document to open to the forefront allowing users to view the Manual for assistance when they need it, and let them close the document at their discretion.

Создание нового документа 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 в приложениях на 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 column width
  • Word vba close file
  • Word vba close all documents
  • Word vba cell color
  • Word vba application dialogs