Vba как сохранить файл word

Создание нового документа 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.

Автор lapin9126, 21 мая 2017, 08:33

Добрый день. Как сохранить открытый документ с другим именем, в другую папку расположенную в той же директории откуда открыт документ, и в нём выполнить макрос.
Например: документ с именем «Исходный» («С:оригиналы»), сохранить как «Исходный (копия)» в папку «обработано»(«С:оригиналыобработано») и  в  «Исходный (копия)» выполнить макрос.



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Исходный файл после создания копии нужно закрыть или нужно, чтобы он оставался открытым?




Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Папка «обработано» должна быть создана (можно и с помощью макроса её создать).

Макрос

Sub Макрос()

    Dim doc As Document

        ‘ Присваиваем активному ворд-файлу имя «doc».
    Set doc = ActiveDocument

        ‘ Создание копии активного файла, при этом он закроется.
    doc.SaveAs2 FileName:=doc.Path & «обработаноИсходный (копия).docx», FileFormat:=wdFormatXMLDocument

        ‘ Здесь делаете действия с переменной «doc», которая представляет собой новый созданный файл.
    ‘ Вывод имени файла «doc» в View — Immediate Window.
    Debug.Print doc.Name

    End Sub

[свернуть]



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Переменную «doc» не обязательно использовать, можно и без неё обойтись:

Макрос

Sub Макрос()
    ‘ Создание копии активного файла, при этом он закроется.
    ActiveDocument.SaveAs2 FileName:=ActiveDocument.Path & «обработаноИсходный (копия).docx», FileFormat:=wdFormatXMLDocument
    ‘ Здесь делаете действия с новым созданным файлом, используя «ActiveDocument».
    ‘ Вывод имени активного файла в View — Immediate Window.
    Debug.Print ActiveDocument.Name
End Sub

[свернуть]


При сохранении файла нужно присваивать имя исходного (открытого) файла с добавлением (копия), а не конкретно «Исходный (копия)» Это для примера было.



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан
Макрос

Sub Макрос()

    Dim FN As String

        ‘1. Формирование полного имени (путь + имя) для нового файла на основе полного имени активного файла.
    ‘ Вычленение имени файла.
    FN = Left(ActiveDocument.Name, InStrRev(ActiveDocument.Name, «.») — 1)
    ‘ Добавление к имени файла фразы «(копия»).
    FN = FN & » (копия)» & «.docx»
    ‘ Добавление пути.
    FN = ActiveDocument.Path & «» & FN

        ‘2. Создание копии активного файла, при этом он закроется.
    ActiveDocument.SaveAs2 FileName:=FN, FileFormat:=wdFormatXMLDocument

        ‘3. Здесь делаете действия с новым созданным файлом, используя «ActiveDocument».
    ‘ Вывод имени активного файла в View — Immediate Window.
    Debug.Print ActiveDocument.Name

    End Sub

[свернуть]


Спасибо, чуть-чуть подправил (добавил место сохранения  & «обработано» & «»), теперь то что нужно.


  • Форум по VBA, Excel и Word

  • Word

  • Макросы в Word

  • Word: Как сохранить документ (ворд-файл) с помощью VBA?

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

Document.SaveAs2 method (Word)

vbawd10.chm158007864

vbawd10.chm158007864

word

Word.SaveAs2

aa491007-0e31-26f5-3a5e-477381529b6e

06/08/2017

medium

Document.SaveAs2 method (Word)

Saves the specified document with a new name or format. Some of the arguments for this method correspond to the options in the Save As dialog box (File tab).

Syntax

expression. SaveAs2( _FileName_ , _FileFormat_ , _LockComments_ , _Password_ , _AddToRecentFiles_ , _WritePassword_ , _ReadOnlyRecommended_ , _EmbedTrueTypeFonts_ , _SaveNativePictureFormat_ , _SaveFormsData_ , _SaveAsAOCELetter_ , _Encoding_ , _InsertLineBreaks_ , _AllowSubstitutions_ , _LineEnding_ , _AddBiDiMarks_ , _CompatibilityMode_ )

expression An expression that returns a Document object.

Parameters

Name Required/Optional Data type Description
FileName Optional Variant The name for the document. The default is the current folder and file name. If the document has never been saved, the default name is used (for example, Doc1.doc). If a document with the specified file name already exists, the document is overwritten without prompting the user.
FileFormat Optional Variant The format in which the document is saved. Can be any WdSaveFormat constant. To save a document in another format, specify the appropriate value for the SaveFormat property of the FileConverter object.
LockComments Optional Variant True to lock the document for comments. The default is False.
Password Optional Variant A password string for opening the document. (See Remarks below.)
AddToRecentFiles Optional Variant True to add the document to the list of recently used files on the File menu. The default is True.
WritePassword Optional Variant A password string for saving changes to the document. (See Remarks below.)
ReadOnlyRecommended Optional Variant True to have Microsoft Word suggest read-only status whenever the document is opened. The default is False.
EmbedTrueTypeFonts Optional Variant True to save TrueType fonts with the document. If omitted, the EmbedTrueTypeFonts argument assumes the value of the EmbedTrueTypeFonts property.
SaveNativePictureFormat Optional Variant If graphics were imported from another platform (for example, Macintosh), True to save only the Microsoft Windows version of the imported graphics.
SaveFormsData Optional Variant True to save the data entered by a user in a form as a record.
SaveAsAOCELetter Optional Variant If the document has an attached mailer, True to save the document as an AOCE letter (the mailer is saved).
Encoding Optional Variant The code page, or character set, to use for documents saved as encoded text files. The default is the system code page. You cannot use all MsoEncoding constants with this parameter.
InsertLineBreaks Optional Variant If the document is saved as a text file, True to insert line breaks at the end of each line of text.
AllowSubstitutions Optional Variant If the document is saved as a text file, True allows Word to replace some symbols with text that looks similar. For example, displaying the copyright symbol as (c). The default is False.
LineEnding Optional Variant The way Word marks the line and paragraph breaks in documents saved as text files. Can be one of the following WdLineEndingType constants: wdCRLF (default) or wdCROnly.
AddBiDiMarks Optional Variant True adds control characters to the output file to preserve bi-directional layout of the text in the original document.
CompatibilityMode Optional Variant The compatibility mode that Word uses when opening the document. WdCompatibilityMode constant.

Important
By default, if no value is specified for this parameter, Word enters a value of 0, which specifies that the current compatibility mode of the document should be retained.

Return value

Nothing

Example

The following code example saves the active document as Test.rtf in rich-text format (RTF).

Sub SaveAsRTF() 
    ActiveDocument.SaveAs2 FileName:="Text.rtf", _ 
        FileFormat:=wdFormatRTF 
End Sub

The following code example saves the active document in text-file format with the extension «.txt».

Sub SaveAsTextFile() 
    Dim strDocName As String 
    Dim intPos As Integer 
 
    ' Find position of extension in file name 
    strDocName = ActiveDocument.Name 
    intPos = InStrRev(strDocName, ".") 
 
    If intPos = 0 Then 
 
        ' If the document has not yet been saved 
        ' Ask the user to provide a file name 
        strDocName = InputBox("Please enter the name " & _ 
            "of your document.") 
    Else 
 
        ' Strip off extension and add ".txt" extension 
        strDocName = Left(strDocName, intPos - 1) 
        strDocName = strDocName & ".txt" 
    End If 
 
    ' Save file with new extension 
    ActiveDocument.SaveAs2 FileName:=strDocName, _ 
        FileFormat:=wdFormatText 
End Sub

The following code example loops through all the installed converters, and if it finds the WordPerfect 6.0 converter, it saves the active document using the converter.

Sub SaveWithConverter() 
 
    Dim cnvWrdPrf As FileConverter 
 
    ' Look for WordPerfect file converter 
    ' And save document using the converter 
    ' For the FileFormat converter value 
    For Each cnvWrdPrf In Application.FileConverters 
        If cnvWrdPrf.ClassName = "WrdPrfctWin" Then 
            ActiveDocument.SaveAs2 FileName:="MyWP.doc", _ 
                FileFormat:=cnvWrdPrf.SaveFormat 
        End If 
    Next cnvWrdPrf 
 
End Sub

The following code example shows a procedure that saves a document with a password.

Sub SaveWithPassword(docCurrent As Document, strPWD As String) 
    With docCurrent 
        .SaveAs2 WritePassword:=strPWD 
    End With 
End Sub

See also

Document Object

[!includeSupport and feedback]

SaveAs

This Word macro will save the ActiveDocument with a new file name that includes the current time:

Sub SaveMewithDateName()
'saves active doc in current folder as a filtered html and named upon current time
    Dim strTime As String
    strTime = Format(Now, "hh-mm")
    ActiveDocument.SaveAs FileName:=ActiveDocument.Path & "" & strTime, FileFormat:=wdFormatFilteredHTML
End Sub

Create and SaveAs

This VBA macro will create a new document and save as using the current date and time:

Sub CreateAndSaveAs()
'creates a new doc and saves as a filtered html [In the default folder and named upon current time]
    Dim strTime As String
    Dim strPath As String
    Dim oDoc As Document
    
    strPath = ActiveDocument.Path & Application.PathSeparator
     strTime = Format(Now, "yyyy-mm-dd hh-mm")
    Set oDoc = Documents.Add 'create a new doc and asign it to oDoc variable
    'write some text in the new doc  reffering to it using oDoc variable
    oDoc.Range.InsertBefore "Visit https://www.automateexcel.com/vba-code-library"
    oDoc.SaveAs FileName:=strPath & strTime, FileFormat:=wdFormatFilteredHTML
    oDoc.Close wdDoNotSaveChanges 'close doc
End Sub

SaveAs PDF

This macro will save the Word document as a PDF:

Sub MacroSaveAsPDF()
'macro saves pdf either in the same folder where active doc is or in documents folder if file is not yet saved
'
    Dim strPath As String
    Dim strPDFname As String

    strPDFname = InputBox("Enter name for PDF", "File Name", "example")
    If strPDFname = "" Then 'user deleted text from inputbox, add default name
        strPDFname = "example"
    End If
    strPath = ActiveDocument.Path
    If strPath = "" Then    'doc is not saved yet
        strPath = Options.DefaultFilePath(wdDocumentsPath) & Application.PathSeparator
    Else
        'just add  at the end
        strPath = strPath & Application.PathSeparator
    End If
    ActiveDocument.ExportAsFixedFormat OutputFileName:= _
                                       strPath & strPDFname & ".pdf", _
                                       ExportFormat:=wdExportFormatPDF, _
                                       OpenAfterExport:=False, _
                                       OptimizeFor:=wdExportOptimizeForPrint, _
                                       Range:=wdExportAllDocument, _
                                       IncludeDocProps:=True, _
                                       CreateBookmarks:=wdExportCreateWordBookmarks, _
                                       BitmapMissingFonts:=True
End Sub

This function will also Save any word document as a PDF:

Sub MacroSaveAsPDFwParameters(Optional strPath As String, Optional strFilename As String)

'strPath, if passed, must include path separator [""]

    If strFilename = "" Then
        strFilename = ActiveDocument.Name
    End If
    'extract just file name without extension
    If InStr(1, strFilename, ".") > 0 Then
        strFilename = Left$(strFilename, InStrRev(strFilename, ".") - 1)
    End If


    If strPath = "" Then
        If ActiveDocument.Path = "" Then    'doc is not saved yet, we will use default path
            strPath = Options.DefaultFilePath(wdDocumentsPath) & Application.PathSeparator
        Else    ' use path of active doc
            strPath = Options.DefaultFilePath(wdDocumentsPath) & Application.PathSeparator
        End If
    End If
    On Error GoTo EXITHERE
    ActiveDocument.ExportAsFixedFormat OutputFileName:= _
                                       strPath & strFilename & ".pdf", _
                                       ExportFormat:=wdExportFormatPDF, _
                                       OpenAfterExport:=False, _
                                       OptimizeFor:=wdExportOptimizeForPrint, _
                                       Range:=wdExportAllDocument, _
                                       IncludeDocProps:=True, _
                                       CreateBookmarks:=wdExportCreateWordBookmarks, _
                                       BitmapMissingFonts:=True
    Exit Sub

EXITHERE:
    MsgBox "Error: " & Err.Number & " " & Err.Description
End Sub

You can enter the file path and file name to indicate which file to save as a PDF:

Sub CallSaveAsPDF()

    Call MacroSaveAsPDFwParameters("c:/Documents", "example.docx")
    
End Sub

Содержание

  1. Метод Document.SaveAs2 (Word)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Пример
  6. См. также
  7. Поддержка и обратная связь
  8. Работа с объектами документа
  9. Создание нового документа
  10. Открытие документа
  11. Сохранение существующего документа
  12. Сохранение нового документа
  13. Закрытие документов
  14. Активация документа
  15. Определение того, открыт ли документ
  16. Ссылка на активный документ
  17. Поддержка и обратная связь
  18. Метод Documents.Save (Word)
  19. Синтаксис
  20. Параметры
  21. Замечания
  22. Поддержка и обратная связь
  23. Document.SaveAs2 method (Word)
  24. Syntax
  25. Parameters
  26. Return value
  27. Example
  28. See also
  29. Support and feedback

Метод Document.SaveAs2 (Word)

Сохраняет указанный документ с новым именем или форматом. Некоторые аргументы для этого метода соответствуют параметрам в диалоговом окне Сохранить как (вкладка Файл ).

Синтаксис

выражение. SaveAs2 ( _FileName_ , _FileFormat_ , _LockComments_ , _Password_ , _AddToRecentFiles_ , _WritePassword_ , _ReadOnlyRecommended_ , _EmbedTrueTypeFonts_ , _SaveNativePictureFormat_ , _SaveFormsData_ , _SaveAsAOCELetter_ , _Encoding_ , _InsertLineBreaks_ , _AllowSubstitutions_ , _LineEnding_ , _AddBiDiMarks_ , _CompatibilityMode_ )

Выражение Выражение, возвращающее объект Document .

Параметры

Имя Обязательный или необязательный Тип данных Описание
FileName Необязательный Variant Имя документа. По умолчанию используется текущая папка и имя файла. Если документ никогда не сохранялся, используется имя по умолчанию (например, Doc1.doc). Если документ с указанным именем файла уже существует, документ перезаписывается без запроса пользователя.
FileFormat Необязательный Variant Формат, в котором сохраняется документ. Может быть любой константой WdSaveFormat . Чтобы сохранить документ в другом формате, укажите соответствующее значение для свойства SaveFormat объекта FileConverter .
LockComments Необязательный Variant Значение true , чтобы заблокировать документ для комментариев. Значение по умолчанию — false.
Password Необязательный Variant Строка пароля для открытия документа. (См. примечания ниже.)
AddToRecentFiles Необязательный Variant Значение true , чтобы добавить документ в список недавно использовавшихся файлов в меню Файл . По умолчанию используется значение True.
WritePassword Необязательный Variant Строка пароля для сохранения изменений в документе. (См. примечания ниже.)
ReadOnlyRecommended Необязательный Variant Значение true , чтобы microsoft Word предлагал состояние только для чтения при открытии документа. Значение по умолчанию — false.
EmbedTrueTypeFonts Необязательный Variant Значение true , чтобы сохранить шрифты TrueType в документе. Если этот параметр опущен, аргумент EmbedTrueTypeFonts принимает значение свойства EmbedTrueTypeFonts .
SaveNativePictureFormat Необязательный Variant Если графика была импортирована с другой платформы (например, Macintosh), значение True используется для сохранения только версии импортированной графики Microsoft Windows.
SaveFormsData Необязательный Variant Значение true для сохранения данных, введенных пользователем в форме в виде записи.
SaveAsAOCELetter Необязательный Variant Если к документу прикреплен почтовый адрес, значение True , чтобы сохранить документ как письмо AOCE (почтовый ящик сохраняется).
Encoding Необязательный Variant Кодовая страница или кодировка, используемая для документов, сохраненных в виде закодированных текстовых файлов. По умолчанию используется системная кодовая страница. С этим параметром нельзя использовать все константы MsoEncoding .
InsertLineBreaks Необязательный Variant Если документ сохраняется как текстовый файл, значение True для вставки разрывов строк в конце каждой строки текста.
AllowSubstitutions Необязательный Variant Если документ сохраняется в виде текстового файла, значение True позволяет Word заменить некоторые символы текстом, похожим на текст. Например, если символ авторских прав отображается как (c). Значение по умолчанию — false.
LineEnding Необязательный Variant Способ, который Word помечает строки и разрывы абзаца в документах, сохраненных в виде текстовых файлов. Может быть одной из следующих констант WdLineEndingType : wdCRLF (по умолчанию) или wdCROnly.
AddBiDiMarks Необязательный Variant True добавляет управляющие символы в выходной файл, чтобы сохранить двунаправленный макет текста в исходном документе.
CompatibilityMode Необязательный Variant Режим совместимости, который Word использует при открытии документа. Константа WdCompatibilityMode .

Важно!
По умолчанию, если для этого параметра не указано значение, Word вводит значение 0, указывающее, что текущий режим совместимости документа должен быть сохранен.

Возвращаемое значение

Пример

В следующем примере кода активный документ сохраняется как Test.rtf в формате RTF.

В следующем примере кода активный документ сохраняется в текстовом формате с расширением «.txt».

В следующем примере кода выполняется цикл по всем установленным преобразователям, и если он находит преобразователь WordPerfect 6.0, он сохраняет активный документ с помощью преобразователя.

В следующем примере кода показана процедура, которая сохраняет документ с паролем.

См. также

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

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

Источник

Работа с объектами документа

В Visual Basic методы изменения файлов являются методами объекта Document или коллекции Documents . В этом разделе приведены примеры Visual Basic, связанные с задачами, определенными в следующих разделах.

Создание нового документа

Коллекция Documents включает все открытые документы. Чтобы создать документ, используйте метод Add , чтобы добавить объект Document в коллекцию Documents . Следующая инструкция создает документ.

Лучший способ создания документа — назначить возвращаемое значение переменной объекта. Метод Add возвращает объект Document , который ссылается на новый документ. В следующем примере объект Document , возвращенный методом Add , назначается переменной объекта . Затем задаются несколько свойств и методов объекта Document . Вы можете легко управлять новым документом с помощью объектной переменной.

Открытие документа

Чтобы открыть существующий документ, используйте метод Open с коллекцией Documents . Следующая инструкция открывает документ с именем Sample.doc, расположенный в папке MyFolder.

Сохранение существующего документа

Чтобы сохранить один документ, используйте метод Save с объектом Document . Следующая инструкция сохраняет документ с именем Sales.doc.

Вы можете сохранить все открытые документы, применив метод Save к коллекции Documents . Следующая инструкция сохраняет все открытые документы.

Сохранение нового документа

Чтобы сохранить один документ, используйте метод SaveAs2 с объектом Document . Следующая инструкция сохраняет активный документ как «Temp.doc» в текущей папке.

Аргумент FileName может включать только имя файла или полный путь (например, «C:DocumentsTemporary File.doc»).

Закрытие документов

Чтобы закрыть один документ, используйте метод Close с объектом Document . Следующая инструкция закрывает и сохраняет документ с именем Sales.doc.

Вы можете закрыть все открытые документы, применив метод Close коллекции Documents . Следующая инструкция закрывает все документы без сохранения изменений.

В следующем примере пользователю предлагается сохранить каждый документ перед закрытием документа.

Активация документа

Чтобы изменить активный документ, используйте метод Activate с объектом Document . Следующая инструкция активирует открытый документ с именем Sales.doc.

Определение того, открыт ли документ

Чтобы определить, открыт ли документ, можно перечислить коллекцию Documents с помощью параметра For Each. Следующая инструкция. В следующем примере документ с именем Sample.doc активируется, если документ открыт, или открывается Sample.doc, если он в настоящее время не открыт.

Ссылка на активный документ

Вместо ссылки на документ по имени или по номеру индекса, например, Documents(«Sales.doc») свойство ActiveDocument возвращает объект Document , ссылающийся на активный документ (документ с фокусом). В следующем примере отображается имя активного документа или, если документы не открыты, отображается сообщение.

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

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

Источник

Метод Documents.Save (Word)

Сохраняет все документы в коллекции Документы .

Синтаксис

expression. Сохранить (NoPrompt, OriginalFormat)

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

Параметры

Имя Обязательный или необязательный Тип данных Описание
NoPrompt Необязательный Variant True , чтобы Word автоматически сохранял все документы. Значение false , чтобы приложение Word запрашивало у пользователя запрос на сохранение каждого документа, измененного с момента последнего сохранения.
OriginalFormat Необязательный Variant Указывает способ сохранения документов. Может быть одной из констант WdOriginalFormat .

Замечания

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

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

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

Источник

Document.SaveAs2 method (Word)

Saves the specified document with a new name or format. Some of the arguments for this method correspond to the options in the Save As dialog box (File tab).

Syntax

expression. SaveAs2 ( _FileName_ , _FileFormat_ , _LockComments_ , _Password_ , _AddToRecentFiles_ , _WritePassword_ , _ReadOnlyRecommended_ , _EmbedTrueTypeFonts_ , _SaveNativePictureFormat_ , _SaveFormsData_ , _SaveAsAOCELetter_ , _Encoding_ , _InsertLineBreaks_ , _AllowSubstitutions_ , _LineEnding_ , _AddBiDiMarks_ , _CompatibilityMode_ )

expression An expression that returns a Document object.

Parameters

Name Required/Optional Data type Description
FileName Optional Variant The name for the document. The default is the current folder and file name. If the document has never been saved, the default name is used (for example, Doc1.doc). If a document with the specified file name already exists, the document is overwritten without prompting the user.
FileFormat Optional Variant The format in which the document is saved. Can be any WdSaveFormat constant. To save a document in another format, specify the appropriate value for the SaveFormat property of the FileConverter object.
LockComments Optional Variant True to lock the document for comments. The default is False.
Password Optional Variant A password string for opening the document. (See Remarks below.)
AddToRecentFiles Optional Variant True to add the document to the list of recently used files on the File menu. The default is True.
WritePassword Optional Variant A password string for saving changes to the document. (See Remarks below.)
ReadOnlyRecommended Optional Variant True to have Microsoft Word suggest read-only status whenever the document is opened. The default is False.
EmbedTrueTypeFonts Optional Variant True to save TrueType fonts with the document. If omitted, the EmbedTrueTypeFonts argument assumes the value of the EmbedTrueTypeFonts property.
SaveNativePictureFormat Optional Variant If graphics were imported from another platform (for example, Macintosh), True to save only the Microsoft Windows version of the imported graphics.
SaveFormsData Optional Variant True to save the data entered by a user in a form as a record.
SaveAsAOCELetter Optional Variant If the document has an attached mailer, True to save the document as an AOCE letter (the mailer is saved).
Encoding Optional Variant The code page, or character set, to use for documents saved as encoded text files. The default is the system code page. You cannot use all MsoEncoding constants with this parameter.
InsertLineBreaks Optional Variant If the document is saved as a text file, True to insert line breaks at the end of each line of text.
AllowSubstitutions Optional Variant If the document is saved as a text file, True allows Word to replace some symbols with text that looks similar. For example, displaying the copyright symbol as (c). The default is False.
LineEnding Optional Variant The way Word marks the line and paragraph breaks in documents saved as text files. Can be one of the following WdLineEndingType constants: wdCRLF (default) or wdCROnly.
AddBiDiMarks Optional Variant True adds control characters to the output file to preserve bi-directional layout of the text in the original document.
CompatibilityMode Optional Variant The compatibility mode that Word uses when opening the document. WdCompatibilityMode constant.

Important
By default, if no value is specified for this parameter, Word enters a value of 0, which specifies that the current compatibility mode of the document should be retained.

Return value

Example

The following code example saves the active document as Test.rtf in rich-text format (RTF).

The following code example saves the active document in text-file format with the extension «.txt».

The following code example loops through all the installed converters, and if it finds the WordPerfect 6.0 converter, it saves the active document using the converter.

The following code example shows a procedure that saves a document with a password.

See also

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.

Источник

Понравилась статья? Поделить с друзьями:
  • Vba как создать файл word
  • Vba как скопировать формат ячейки excel
  • Vba как свернуть книгу excel
  • Vba как присвоить имя ячейке в excel
  • Vba как подключить библиотеку word