Vba word activedocument 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]

Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

1

03.04.2011, 15:51. Показов 27758. Ответов 14

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Close и Save документа Word, не могу в них врубиться, посмотрите пжл, три
нижепреведённые строки правильно закомметировали, если нет поправьте

Visual Basic
1
2
3
4
5
6
7
8
9
'1 закрываем документ, чтобы не появлялось предупреждение о сохранении
ActiveDocument.Close SaveChanges:=False
 
'2 закрываем документ без сохранения, ноль в скобках обозначает, что сохранение документа при закрытии не 
'требуется, иначе будет отображен диалог "Сохранить документ"
ActiveDocument.Close (0)
 
'3 закрываем документ без сохранения, диалог "Сохранить документ" отображаться не будет
ActiveDocument.Close wdDoNotSaveChanges

Подскажите, мне надо условие составить
если пользователь своими руками ничего не изменял в документе

PureBasic
1
If ActiveDocument.Undo = True Then

тогда сохранить без диалога «Сохранить документ»
как ????

Добавлено через 17 часов 15 минут
понял, что надо использовать строку:

PureBasic
1
ActiveDocument.Close (wdDoNotSaveChanges)

Но проблема в синтаксе, поправьте пжл



1



Busine2009

Заблокирован

03.04.2011, 16:20

2

HelpСправка Microsoft Visual BasicMicrosoft Word Visual Basic ReferenceMethodsCClose MethodClose 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, говорю не могу врубиться
‘Close — Закрывает указанный документ или документы.

‘Doc.Close (SaveChanges, OriginalFormat, RouteDocument)
‘SaveChanges опциональный вариант. Указывает, сохранять действий по документу
‘Может быть одной из следующих констант WdSaveOptions:
‘wdDoNotSaveChanges, wdPromptToSaveChanges, wdSaveChanges
‘Не сохраняйте изменения, предложение сохранить изменения, сохраните изменения
‘OriginalFormat опциональный вариант. Определяет формат сохранения документа
‘Может быть одной из следующих констант WdOriginalFormat:
‘wdOriginalDocumentFormat, wdPromptUser, wdWordDocument
‘Оригинальный Document Format, проворная пользователя, документ Word
‘RouteDocument опциональный вариант. Правда, чтобы направить документ на следующей получателя
‘Если документ не имеет маршруте прилагается, этот аргумент игнорируется

Подскажите пожалуйста с примерм



0



Busine2009

Заблокирован

03.04.2011, 16:25

4

Ципихович Эндрю,
там пример есть, в котором написан синтаксис.



0



Mawrat

13094 / 5875 / 1706

Регистрация: 19.09.2009

Сообщений: 8,808

03.04.2011, 16:28

5

Например, такой способ можно применить:

Visual Basic
1
2
3
4
5
6
  'Если в документе есть изменения - тогда сохраняем.
  If Not ActiveDocument.Saved Then
    ActiveDocument.Save
  End If
  'Закрываем документ.
  ActiveDocument.Close


Код простой, но делает то что надо — если документ ещё не связан с файлом, то будет выведен диалог сохранения. Если файл уже есть и имеются изменения — сохранит, если файл есть и изменений нет — сохранять не будет.



1



1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

03.04.2011, 16:43

 [ТС]

6

Mawrat Ваш скрипт выполняет, получаем ошибку Ошибка команды

Добавлено через 4 минуты

Цитата
Сообщение от Mawrat
Посмотреть сообщение

Если в документе есть изменения, тогда

Решать надо строго: IF ActiveDocument.Undo = True THEN



0



Mawrat

13094 / 5875 / 1706

Регистрация: 19.09.2009

Сообщений: 8,808

03.04.2011, 16:45

7

Я проверял — у меня работает.
Вот полностью код, который я запускал:

Visual Basic
1
2
3
4
5
6
7
8
Sub Sub1()
  'Если в документе есть изменения - тогда сохраняем.
  If Not ActiveDocument.Saved Then
    ActiveDocument.Save
  End If
  'Закрываем документ.
  ActiveDocument.Close
End Sub



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

В общем, тут надо рассмотреть вопрос о том, в каких случаях надо сохранять документ в файл. И требуется ли делать отмену изменений в документе.
1. Если надо выполнять сохранение в случае, если файл на диске отличается от содержания открытого в Word документа. Тогда подойдёт этот код:

Visual Basic
1
2
3
4
5
6
7
8
Sub Sub1()
  'Если в документе есть изменения - тогда сохраняем.
  If Not ActiveDocument.Saved Then
    ActiveDocument.Save
  End If
  'Закрываем документ.
  ActiveDocument.Close
End Sub

2. Если надо сначала откатить все изменения, которые были выполнены над содержимым документа, тогда так:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
Sub Sub1()
  'Откатываем все изменения.
  While ActiveDocument.Undo
  Wend
  'Если документ отличается от версии, сохранённой в файле - тогда сохраняем.
  If Not ActiveDocument.Saved Then
    ActiveDocument.Save
  End If
  'Закрываем документ.
  ActiveDocument.Close
End Sub


А вот если требуется различать изменения сделанные пользователем от тех изменений, которые сделала программа — в этом случае задача усложняется…
Undo откатывает любые изменения — независимо от того как они сделаны — пользователем или программно.



0



1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

03.04.2011, 17:17

 [ТС]

10

в предыдущем посте скрипт 1
опробовал
был шаблон 1.дот время изменения 12:00
открыл, ничего не делал закрываю, вылазит форма ошибка команды и время изменеия свежее, не то
2 скрипт пробую

Добавлено через 7 минут
2 скрипт опробовал тоже самое



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

Цитата
Сообщение от Mawrat
Посмотреть сообщение

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
Documents.Close wdPromptToSaveChanges
Закрыть текущий документ без сохранения:
ActiveDocument.Close wdDoNotSaveChanges

делаю:

PureBasic
1
2
3
4
5
'условие, если не было в документе отмен, тогда ...
If ActiveDocument.Undo = False Then
'закрыть текущий документ без сохранения
ActiveDocument.Close wdDoNotSaveChanges
End If

Получаю Ошибка команды и запрос на сохранение, а мне не нужно ни того ни другого



0



Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

05.04.2011, 20:32

 [ТС]

15

по большому счёту эта строка:

PureBasic
1
If ActiveDocument.Undo = False Then Dialogs(wdDialogFileSaveAs).Execute

мне как бальзам на душу за исключением того, что если бы не сохранялся шаблон с текущим временем



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.

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 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.

Blank Word window left after macro

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

Richard H's user avatar

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.

  1. On the Tools menu, point to Macro, and then click Macros.

  2. In the Macros in box, select Word commands.

  3. In the Macro name box, select FileSave.

  4. 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 (the FileSave command will be modified for all documents).

  5. 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, your FileSave macro runs
instead of the word command. To restore the original FileSave
functionality, you need to rename or delete your FileSave macro.

Source Modifying a Word Command

answered Apr 13, 2016 at 16:15

DavidPostill's user avatar

DavidPostillDavidPostill

150k77 gold badges348 silver badges386 bronze badges

1

Понравилась статья? Поделить с друзьями:
  • Vba with microsoft word
  • Vba with excel book
  • Vba with excel 2003
  • Vba visio from excel
  • Vba userform for word