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]
Ципихович Эндрю 1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
||||||||||||
1 |
||||||||||||
03.04.2011, 15:51. Показов 27758. Ответов 14 Метки нет (Все метки)
Close и Save документа Word, не могу в них врубиться, посмотрите пжл, три
Подскажите, мне надо условие составить
тогда сохранить без диалога «Сохранить документ» Добавлено через 17 часов 15 минут
Но проблема в синтаксе, поправьте пжл
1 |
Заблокирован |
|
03.04.2011, 16:20 |
2 |
Help — Справка Microsoft Visual Basic — Microsoft Word Visual Basic Reference — Methods — C — Close Method — Close Method as it applies to the Document and Documents objects.
0 |
1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
|
03.04.2011, 16:23 [ТС] |
3 |
читал раз 100, говорю не могу врубиться ‘Doc.Close (SaveChanges, OriginalFormat, RouteDocument) Подскажите пожалуйста с примерм
0 |
Заблокирован |
|
03.04.2011, 16:25 |
4 |
Ципихович Эндрю,
0 |
Mawrat 13094 / 5875 / 1706 Регистрация: 19.09.2009 Сообщений: 8,808 |
||||
03.04.2011, 16:28 |
5 |
|||
Например, такой способ можно применить:
—
1 |
1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
|
03.04.2011, 16:43 [ТС] |
6 |
Mawrat Ваш скрипт выполняет, получаем ошибку Ошибка команды Добавлено через 4 минуты
Если в документе есть изменения, тогда Решать надо строго: IF ActiveDocument.Undo = True THEN
0 |
Mawrat 13094 / 5875 / 1706 Регистрация: 19.09.2009 Сообщений: 8,808 |
||||
03.04.2011, 16:45 |
7 |
|||
Я проверял — у меня работает.
0 |
1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
|
03.04.2011, 16:50 [ТС] |
8 |
если пользователь своими руками ничего не изменял в документе это то Вы наверное выполняете, но есть но:
0 |
Mawrat 13094 / 5875 / 1706 Регистрация: 19.09.2009 Сообщений: 8,808 |
||||||||
03.04.2011, 17:00 |
9 |
|||||||
В общем, тут надо рассмотреть вопрос о том, в каких случаях надо сохранять документ в файл. И требуется ли делать отмену изменений в документе.
2. Если надо сначала откатить все изменения, которые были выполнены над содержимым документа, тогда так:
—
0 |
1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
|
03.04.2011, 17:17 [ТС] |
10 |
в предыдущем посте скрипт 1 Добавлено через 7 минут
0 |
13094 / 5875 / 1706 Регистрация: 19.09.2009 Сообщений: 8,808 |
|
03.04.2011, 17:22 |
11 |
Наверное лучше в начале исследуемого кода поставить точку останова и прогнать его по шагам. Такое ощущение, что ошибка происходит где-то в другом месте. Потому что выше представленные процедуры в чистом виде нормально отрабатывают.
0 |
1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
|
03.04.2011, 17:27 [ТС] |
12 |
ActiveDocument.Close А что там останавливаться, всего 5-6 строк, на указанной строке форма: Ошибка команды
0 |
13094 / 5875 / 1706 Регистрация: 19.09.2009 Сообщений: 8,808 |
|
03.04.2011, 17:39 |
13 |
А на какой строке ошибка команды?
0 |
Ципихович Эндрю 1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
||||
03.04.2011, 17:54 [ТС] |
14 |
|||
на этой
ActiveDocument.Close Добавлено через 2 минуты 170 Глава 7. В мире объектов MS Office делаю:
Получаю Ошибка команды и запрос на сохранение, а мне не нужно ни того ни другого
0 |
Ципихович Эндрю 1508 / 478 / 56 Регистрация: 10.04.2009 Сообщений: 8,008 |
||||
05.04.2011, 20:32 [ТС] |
15 |
|||
по большому счёту эта строка:
мне как бальзам на душу за исключением того, что если бы не сохранялся шаблон с текущим временем
0 |
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.
Close 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.
Close 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
As 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"
As 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
As 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
As 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 a macro that inserts select cells of an Excel document into a Word template, copies the entire Word document then closes the document without saving, to preserve certain keywords.
However when it closes the Word document it leaves a blank Word window open, with no active document, and each time the macro runs it leaves a new blank window.
Dim appWd As Word.Application
Dim wdFind As Object
Dim ClipEmpty As New MSForms.DataObject
Dim ClipT As String
Sub CopyDatatoWord()
Dim docWD As Word.Document
Dim sheet1 As Object
Dim sheet2 As Object
Dim saveCell1 As String
Dim saveCell2 As String
Dim saveCell3 As String
Dim dir1 As String
Dim dir2 As String
date_example = Cells(Application.ActiveCell.Row, 3)
Set appWd = CreateObject("Word.Application")
appWd.Visible = True
Set docWD = appWd.Documents.Open(ThisWorkbook.Path & "template.docx")
'Select Sheet where copying from in excel
Set sheet1 = Sheets("Scheduling tracker")
Set wdFind = appWd.Selection.Find
Cells(Application.ActiveCell.Row, 15).Select
Selection.Copy
wdFind.Text = "QREQQ"
Call NoFormatPaste
Cells(Application.ActiveCell.Row, 14).Select
Selection.Copy
wdFind.Text = "QREQNOQ"
Call NoFormatPaste
Cells(Application.ActiveCell.Row, 6).Select
Selection.Copy
wdFind.Text = "QNAMEQ"
Call NoFormatPaste
Cells(Application.ActiveCell.Row, 15).Select
Selection.Copy
wdFind.Text = "QREQQ"
Call NoFormatPaste
Cells(Application.ActiveCell.Row, 14).Select
Selection.Copy
wdFind.Text = "QREQNOQ"
Call NoFormatPaste
Dim dateValue As String
dateValue = Cells(Application.ActiveCell.Row, 3).Value
wdFind.Text = "QDATEQ"
Call NoFormatDatePaste(dateValue)
Dim timeValue As String
timeValue = Cells(Application.ActiveCell.Row, 4).Value
wdFind.Text = "QTIMEQ"
Call NoFormatTimePaste(timeValue)
appWd.Selection.WholeStory
appWd.Selection.Copy
appWd.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
Set appWd = Nothing
Set docWD = Nothing
Set appXL = Nothing
Set wbXL = Nothing
End Sub
This is the window I am left with, and a new one is created each time the macro is run.
I have tried using
appWd.Application.Quit SaveChanges:=wdDoNotSaveChanges
But this will force any other open documents to quit as well. Does anyone know how I can close the document without leaving this blank application window?
I am trying to get a document to close when saved, using VBA.
I have searched for this extensively but mostly it comes up with people trying to not turn off saving when closing a document.
What I have so far is the following (I removed the unrelated code).
Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
ActiveDocument.Close
End Sub
This causes word to crash and the document not to save, possibly because it is in the wrong procedure?
Replacing ActiveDocument.close
with App.Quit
works but this closes all open documents(this is not the desired behaviour).
Any ideas will be greatly appreciated.
asked Apr 13, 2016 at 9:33
15
I am trying to get a document to close when saved, using VBA.
You can override (modify) existing word commands.
In this case you need to modify FileSave
and add ActiveDocument.Close
after ActiveDocument.Save
in the code below.
Modifying a Word Command
This example takes you through the steps needed to modify the
FileSave
command.
On the Tools menu, point to Macro, and then click Macros.
In the Macros in box, select Word commands.
In the Macro name box, select FileSave.
In the Macros in box, select a template or document location to store the macro.
For example, select
Normal.dot
(Global Template) to create a global
macro (theFileSave
command will be modified for all documents).Click the Create button.
The FileSave macro appears as shown below.
Sub FileSave()
'
' FileSave Macro
' Saves the active document or template
'
ActiveDocument.Save
End Sub
You can add additional instructions or remove the existing
ActiveDocument.Save
instruction.Now every time the
FileSave
command runs, yourFileSave
macro runs
instead of the word command. To restore the originalFileSave
functionality, you need to rename or delete yourFileSave
macro.
Source Modifying a Word Command
answered Apr 13, 2016 at 16:15
DavidPostill♦DavidPostill
150k77 gold badges348 silver badges386 bronze badges
1