Vba word закрыть документ без сохранения

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

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



You can try WordDoc.Close SaveChanges:=wdDoNotSaveChanges before the Set WordDoc = Nothing

Also, if you want to quit the program entirely you should indeed send the command to quit it before setting the variable to Nothing:

WordApp.Quit SaveChanges:=wdDoNotSaveChanges

Other options for the Quit and Close methods can be found in the documentation: Application.Quit; Document.Close.

Your final code might look like this:

Sub pdf()
    Dim WordApp As Object
    Dim WordDoc As Object
    Set WordApp = CreateObject("Word.Application")

    WordApp.Visible = True

    Set WordDoc = WordApp.Documents.Open("C:testdoc.docx")

    WordDoc.ExportAsFixedFormat OutputFileName:= _
        "C:testdoc.docx.pdf", ExportFormat:= _
        17, OpenAfterExport:=False, OptimizeFor:= _
        0, Range:=0, From:=1, to:=1, _
        Item:=0, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=0, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False

    'If you want to quit the entire Application:
    WordApp.Quit SaveChanges:=wdDoNotSaveChanges

    'If you want to quit only the Document:
    'WordDoc.Close SaveChanges:=wdDoNotSaveChanges

    Set WordDoc = Nothing
    Set WordApp = Nothing
End Sub

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]

title ms.prod ms.assetid ms.date ms.localizationpriority

Working with Document Objects

word

af304f65-6cdd-ff7d-a81f-cce0161f2b47

06/08/2019

medium

Working with Document Objects

In Visual Basic, the methods for modifying files are methods of the Document object or the Documents collection. This topic includes Visual Basic examples related to the tasks identified in the following sections.

Creating a new document

The Documents collection includes all of the open documents. To create a new document, use the Add method to add a Document object to the Documents collection. The following instruction creates a document.

A better way to create a document is to assign the return value to an object variable. The Add method returns a Document object that refers to the new document. In the following example, the Document object returned by the Add method is assigned to an object variable. Then, several properties and methods of the Document object are set. You can easily control the new document using an object variable.

Sub NewSampleDoc() 
    Dim docNew As Document 
    Set docNew = Documents.Add 
    With docNew 
        .Content.Font.Name = "Tahoma" 
        .SaveAs FileName:="Sample.doc" 
    End With 
End Sub

Opening a document

To open an existing document, use the Open method with the Documents collection. The following instruction opens a document named Sample.doc located in the MyFolder folder.

Sub OpenDocument() 
    Documents.Open FileName:="C:MyFolderSample.doc" 
End Sub

Saving an existing document

To save a single document, use the Save method with the Document object. The following instruction saves the document named Sales.doc.

Sub SaveDocument() 
    Documents("Sales.doc").Save 
End Sub

You can save all open documents by applying the Save method to the Documents collection. The following instruction saves all open documents.

Sub SaveAllOpenDocuments() 
    Documents.Save 
End Sub

Saving a new document

To save a single document, use the SaveAs2 method with a Document object. The following instruction saves the active document as «Temp.doc» in the current folder.

Sub SaveNewDocument() 
    ActiveDocument.SaveAs FileName:="Temp.doc"
End Sub

The FileName argument can include only the file name or the complete path (for example, «C:DocumentsTemporary File.doc»).

Closing documents

To close a single document, use the Close method with a Document object. The following instruction closes and saves the document named Sales.doc.

Sub CloseDocument()
    Documents("Sales.doc").Close SaveChanges:=wdSaveChanges 
End Sub

You can close all open documents by applying the Close method of the Documents collection. The following instruction closes all documents without saving changes.

Sub CloseAllDocuments() 
    Documents.Close SaveChanges:=wdDoNotSaveChanges
End Sub

The following example prompts the user to save each document before the document is closed.

Sub PromptToSaveAndClose()
    Dim doc As Document
    For Each doc In Documents 
        doc.Close SaveChanges:=wdPromptToSaveChanges
    Next
End Sub

Activating a document

To change the active document, use the Activate method with a Document object. The following instruction activates the open document named Sales.doc.

Sub ActivateDocument() 
    Documents("Sales.doc").Activate 
End Sub

Determining if a document is open

To determine if a document is open, you can enumerate the Documents collection by using a For Each…Next statement. The following example activates the document named Sample.doc if the document is open, or opens Sample.doc if it is not currently open.

Sub ActivateOrOpenDocument() 
    Dim doc As Document 
    Dim docFound As Boolean 
 
    For Each doc In Documents 
        If InStr(1, doc.Name, "sample.doc", 1) Then 
            doc.Activate 
            docFound = True 
            Exit For 
        Else 
            docFound = False 
        End If 
    Next doc 
 
    If docFound = False Then Documents.Open FileName:="Sample.doc" 
End Sub

Referring to the active document

Instead of referring to a document by name or by index number—for example, Documents("Sales.doc") —the ActiveDocument property returns a Document object that refers to the active document (the document with the focus). The following example displays the name of the active document, or if there are no documents open, it displays a message.

Sub ActiveDocumentName() 
    If Documents.Count >= 1 Then 
        MsgBox ActiveDocument.Name 
    Else 
        MsgBox "No documents are open" 
    End If 
End Sub

[!includeSupport and feedback]

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#1

13.10.2014 17:55:26

Всем Мяу!
Создаем экземпляр Word, поработали, все скопировали, в Excel вставили, осталось малое — убить Word.

Код
Sub t()
    Set wa = CreateObject("Word.Application")
    ' скопировали , вставили...
    ' осталось закрыть Word
    On Error GoTo 0
    '            wa.CutCopyMode = False
    wa.DisplayAlerts = False
    wa.Quit
    wa.DisplayAlerts = True
    Set wa = Nothing

End Sub

А не тут то и было. Word убиваться не желает.
И ошибки нет, и Word не закрывается.
При попытке закрыть ручками, кричит, что в буфере большой объем данных, и не оставить ли их там?
Где собака порылась?
Другой час ничего придумать не могу…

кросс

Изменено: RAN13.10.2014 17:58:34

 

B.Key

Пользователь

Сообщений: 633
Регистрация: 26.02.2014

а собственно почему документ не создали ?
Вам даже при таком коде данные вставит некуда, так как документ не создан, загружен только application

Изменено: B.Key13.10.2014 18:28:35

 

B.Key

Пользователь

Сообщений: 633
Регистрация: 26.02.2014

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#4

13.10.2014 18:29:53

Создал и уже убил в цикле

Код
 Application.CutCopyMode = False
            wd.Close False
            Set wd = Nothing
 

B.Key

Пользователь

Сообщений: 633
Регистрация: 26.02.2014

приведите полный код создания докумена и как вы его закрыватете

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#6

13.10.2014 18:43:17

Код
Sub q()
    Dim arr
    Application.ScreenUpdating = False
    Set wa = CreateObject("Word.Application" ) 
    wa.Visible = True
    foldPath = ThisWorkbook.Path & ""
    fPath = Dir(foldPath)
    On Error Resume Next
    Do While fPath <> ""
        If fPath Like "*.doc*" Then
            Set wd = wa.Documents.Open(foldPath & fPath)
            wa.Selection.WholeStory
            wa.Selection.Copy
            With shtmp
                .Activate
                .Range("A1"  )  .Select
                '               .UsedRange.Clear
                .Columns("A:F"  )  .Clear
                .Columns("A:F"  )  .NumberFormat = "@"
                .PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:= _
                              False, NoHTMLFormatting:=True
' Код VBA ............
            End With
            Application.CutCopyMode = False
            wd.Close False
            Set wd = Nothing
            With shSablon
   'Код VBA .............
            End With
        End If
        fPath = Dir
    Loop
    With shSablon
'Код VBA .................
    End With

' дальше спупор

    On Error GoTo 0
    '            wa.CutCopyMode = False
    wa.DisplayAlerts = False
    wa.Quit
    wa.DisplayAlerts = True
    Set wa = Nothing

End Sub
 

B.Key

Пользователь

Сообщений: 633
Регистрация: 26.02.2014

я думаю скорее всего документ в цикле не закрылся и так как стоит пропуск ошибок вы его и не видитите
msgbox wa.Documents.count  перед закрытием аппликейшена должен выдать 0

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#8

13.10.2014 18:50:56

Цитата
B.Key пишет: должен выдать 0

И выдал 0!

 

B.Key

Пользователь

Сообщений: 633
Регистрация: 26.02.2014

On Error Resume Next…… и ошибок нет?

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#10

13.10.2014 18:53:42

М-да…Толпа переменных, для которых не видать строк назначения им значений(shtmp, shShablon)
Притом странно, что копируете Вы данные в Word (wa.Selection.Copy), а буфер очищаете из Excel(Application.CutCopyMode = False).
Для DisplayAlerts в данном случае лучше все же вообще не играть:
Т.к. сначала осуществляете выход из приложения, а потом пытаетесь изменить его свойство. Как Вы себе сами это представляете?
Лучше уж либо так:

Код
wa.Quit 0 'закрывает приложение и все файлы без сохранения

либо так:

Код
wa.DisplayAlerts = 0
wa.Quit
Set wa = Nothing

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

B.Key

Пользователь

Сообщений: 633
Регистрация: 26.02.2014

#11

13.10.2014 18:54:06

а если все убрать?

Код
Sub t()
    Set wa = CreateObject("Word.Application")
    
   Set wd = wa.documents.Add
  wd.Close False
    wa.Quit
    Set wa = Nothing
 
End Sub
 

Изменено: B.Key13.10.2014 18:57:46

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#12

13.10.2014 18:59:24

Уряяяя!

Код
      wa.Quit False
    Set wa = Nothing

так пошло.
Затупил жуткостно…

PS shtmp, shShablon — codeNames

Всем спасибо.

Изменено: RAN13.10.2014 19:59:10

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#13

13.10.2014 19:01:08

Цитата
B.Key пишет: On Error Resume Next…… и ошибок нет?
Код
On Error GoTo 0

и нет.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#14

13.10.2014 21:45:00

Не

кошерное

кошачье это дело — с Word работать)) То ли дело Excel!

Понравилась статья? Поделить с друзьями:
  • Vba word selection paste
  • Vba word закрыть все документы
  • Vba word selection in table
  • Vba word закладка это
  • Vba word selection find if not found