Word vba close file

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]

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.

Содержание

  1. Метод Workbook.Close (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Workbook.Close method (Excel)
  8. Syntax
  9. Parameters
  10. Remarks
  11. Example
  12. Support and feedback
  13. Метод Document.Close (Word)
  14. Синтаксис
  15. Параметры
  16. Пример
  17. См. также
  18. Поддержка и обратная связь
  19. Close/Release Word object in VBA?
  20. VBA Excel. Управление приложением Word
  21. Создание объекта Word.Application
  22. Раннее связывание приложения Word

Метод Workbook.Close (Excel)

Синтаксис

expression. Close (SaveChanges, FileName, RouteWorkbook)

Выражение Переменная, представляющая объект Workbook .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Savechanges Необязательный Variant Если в книге нет изменений, этот аргумент игнорируется. Если в книге есть изменения, а книга отображается в других открытых окнах, этот аргумент игнорируется. Если в книге есть изменения, но книга не отображается в других открытых окнах, этот аргумент указывает, следует ли сохранять изменения. Если задано значение True, изменения сохраняются в книге.

Если имя файла еще не связано с книгой, используется имя файла . Если параметр FileName опущен, пользователю будет предложено указать имя файла. FileName Необязательный Variant Сохраняет изменения под этим именем файла. RouteWorkbook Необязательный Variant Если книга не требуется маршрутизировать к следующему получателю (если она не имеет скольжения маршрутизации или уже была перенаправлена), этот аргумент игнорируется. В противном случае Microsoft Excel направляет книгу в соответствии со значением этого параметра.

Если задано значение True, книга отправляется следующему получателю. Если задано значение False, книга не отправляется. Если этот параметр опущен, пользователю будет предложено отправить книгу.

Замечания

При закрытии книги из Visual Basic в ней не выполняются макросы Auto_Close. Используйте метод RunAutoMacros для запуска макросов Auto_Close.

Пример

Этот пример закрывает Book1.xls и удаляет все внесенные в него изменения.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Workbook.Close method (Excel)

Closes the object.

Syntax

expression.Close (SaveChanges, FileName, RouteWorkbook)

expression A variable that represents a Workbook object.

Parameters

Name Required/Optional Data type Description
SaveChanges Optional Variant If there are no changes to the workbook, this argument is ignored. If there are changes to the workbook and the workbook appears in other open windows, this argument is ignored. If there are changes to the workbook but the workbook doesn’t appear in any other open windows, this argument specifies whether changes should be saved. If set to True, changes are saved to the workbook.

If there is not yet a file name associated with the workbook, FileName is used. If FileName is omitted, the user is asked to supply a file name. FileName Optional Variant Saves changes under this file name. RouteWorkbook Optional Variant If the workbook doesn’t need to be routed to the next recipient (if it has no routing slip or has already been routed), this argument is ignored. Otherwise, Microsoft Excel routes the workbook according to the value of this parameter.

If set to True, the workbook is sent to the next recipient. If set to False, the workbook is not sent. If omitted, the user is asked whether the workbook should be sent.

Closing a workbook from Visual Basic doesn’t run any Auto_Close macros in the workbook. Use the RunAutoMacros method to run the Auto_Close macros.

Example

This example closes Book1.xls and discards any changes that have been made to it.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Document.Close (Word)

Закрывает указанный документ.

Синтаксис

expression. Close (SaveChanges, OriginalFormat, RouteDocument)

выражение (обязательно). Переменная, представляющая объект Document .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Savechanges Необязательный Variant Указывает действие сохранения для документа. Может быть одной из следующих констант WdSaveOptions : wdDoNotSaveChanges, wdPromptToSaveChanges или wdSaveChanges.
OriginalFormat Необязательный Variant Задает формат сохранения документа. Может быть одной из следующих констант WdOriginalFormat : wdOriginalDocumentFormat, wdPromptUser или wdWordDocument.
RouteDocument Необязательный Variant Значение true для маршрутизации документа следующему получателю. Если документ не имеет прикрепленного скольжения маршрутизации, этот аргумент игнорируется.

Пример

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

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Close/Release Word object in VBA?

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

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:

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.

Источник

VBA Excel. Управление приложением Word

Создание нового экземпляра приложения Word из кода VBA Excel или подключение к открытому для работы с документами. Функции CreateObject и GetObject.

Работа с Word из кода VBA Excel
Часть 1. Управление приложением Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]

Создание объекта Word.Application

Экземпляр приложения Word необходим для того, чтобы с его помощью создавать новые документы или открывать существующие для редактирования из кода VBA Excel.

Создать новый экземпляр объекта Word.Application можно при помощи раннего или позднего связывания, используя при позднем связывании функцию CreateObject. Подключиться к открытому экземпляру приложения Word можно только при помощи позднего связывания, используя функцию GetObject.

Раннее связывание приложения Word

Создание нового экземпляра Word.Application и присвоение ссылки на него переменной myWord:

Для раннего связывания переменной с объектом Word.Application необходимо подключить в редакторе VBA Excel ссылку на библиотеку Microsoft Word Object Library, если она не подключена. Подключается ссылка в окне «References VBAproject», перейти в которое можно через главное меню редактора: Tools–>References…

Раннее связывание позволяет при написании кода использовать лист подсказок для выбора и вставки свойств и методов привязанных объектов (Auto List Members). Если проект VBA Excel создается на заказ, то, после его завершения, раннее связывание следует заменить на позднее, так как на компьютере пользователя может не оказаться нужной библиотеки, и код работать не будет.

Источник

Использование 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"

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

  • #2

Your code isn’t trying to terminate the Word session; it’s only trying to close a particular document.

A simpler approach is to explicitly run your own Word instance, which you can terminate when finished. For example:

Code:

Sub Demo()
'Note: A reference to the Word library must be set, via Tools|References
Dim wdApp As New Word.Application, wdDoc As Word.Document
Const StrDocNm As String = "Full document name & path"
If Dir(StrDocNm) = "" Then Exit Sub
Set wdDoc = wdApp.Documents.Open(Filename:=StrDocNm, ReadOnly:=False, AddToRecentfiles:=False)
With wdDoc
    'process the document
    
    'save & close
    .Close SaveChanges:=True
End With
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub

Testing whether Word is already running and conditionally starting and ending it accordingly — or using the existing session — is much more involved; it’s something you’d probably only want to do if the user running the macro may or may not already have the document opened.

  • #3

I realy need to test if there’s more than 1 instance of word, so the code will not close other opened documents, nor leave a «blank» word instance opened after printing, avoidind any prompts.

My code opens a word document, prints this document based on cells values, then closes without saving the «docx» file.

Also, it not creates a new word object if there’s one instace of word runing, avoidind problems with «.dot» already opened, etc.

Last edited: Mar 13, 2017

  • #4

The code I posted will not interfere with any Word document that might already be opened. The fact it creates a new instance ensures that. Neither will it create «problems with «.dot» already opened, etc.» or leave an empty Word instance running. You really should have tested the code before posting…

If you want to guard against any changes being saved, you could change:
ReadOnly:=False
to:
ReadOnly:=Truee
and/or change:
.Close SaveChanges:=True
to:
.Close SaveChanges:=False
Those changes are both obvious and trivial.

  • #5

Thanks I will try the changes.
The problem might be that excel vba does not allow «wdDoNotSaveChanges», instead I should inform raw values, like 0, 1, -1, true, false.
I will also add wordapp.displayalerts = 0.
In fact, I didn’t try your first code cause I don’t want to create new instance, cause this is causing some problems here,
those problems also ocurrs when opening multiple excel instances with the boring message «PERSONAL.XLSB» is already open.
I will update later.

Last edited: Mar 14, 2017

  • #6

The problem might be that excel vba does not allow «wdDoNotSaveChanges», instead I should inform raw values, like 0, 1, -1, true, false.

That is nonsense. Again, you should try the code before making such claims. Even if it was true, the code I posted doesn’t use it (and doesn’t need to)!

I will also add wordapp.displayalerts = 0.

I don’t know what you expect to achieve by that. In all likelihood it is quite unnecessary.

In fact, I didn’t try your first code cause I don’t want to create new instance, cause this is causing some problems here

How could you possibly ‘know’ that when you haven’t tried the code? Your «PERSONAL.XLSB» problems have nothing to do with the code I posted!

Last edited: Mar 14, 2017

  • #7

Thanks. This topic is now concluded and can be closed.

Понравилась статья? Поделить с друзьями:
  • Word vba cell color
  • Word vba application dialogs
  • Word vba all open documents
  • Word vba макрос как запустить
  • Word vba выделить текст в таблице