Vba word сохранить все

В данной статье хочу показать 4 способа как экспортировать (сохранить) все изображения из Word документа в файлы в указанную папку на диске с помощью макроса VBA. Обращаю внимание, что речь идет про сохранение не авто-фигур и т.п., а импортированных изображений, которые входят в ворде в коллекцию InlineShapes объекты которой и будем сохранять.

Способ 1. Сохранение изображений из Word в формате EMF

Это самый короткий и быстрый способ экспортировать все изображения из Word-а. Формат изображений EMF (Microsoft Enhanced Metafile) — это медиа-формат, который Microsoft придумал на замену формату WMF. Однако, этот формат не всем приложениям понятен, в этом и минус этого способа.

ExportImages "C:Мои документыfile.doc", "C:Export"

Sub ExportImages(DocFile As String, ExportPath As String)
  ' Открываем документ
  Set Wrd = CreateObject("Word.Application")
  Set Doc = Wrd.Documents.Open(DocFile)
  ' Цикл по картинкам в документе
  For i = 1 To Doc.InlineShapes.Count
    FileName = ExportPath & "img" & CStr(i) & ".emf"
    SaveInlineShape FileName, Doc.InlineShapes(i)
  Next i
  ' Закрываем документ
  Doc.Close
  Wrd.Quit False
End Sub

Sub SaveInlineShape(FileName As Variant, iShape As InlineShape)
Dim vData() As Byte
  ' Открываем файл для записи
  Open FileName For Binary Access Write As #1
  ' Записываем данные
  vData = iShape.Range.EnhMetaFileBits
  Put #1, 1, vData
  ' Закрываем файл
  Close #1
End Sub

Способ 2. Распаковка Word файла как архива

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

ExportImages "C:Мои документыfile.doc", "C:Export"

Sub ExportImages(DocFile As String, ExportPath As String)
  ' Создаем временную папку
  TmpPath = ExportPath & "tmp"
  Set FSO = CreateObject("Scripting.FileSystemObject")
  If Not FSO.FolderExists(TmpPath) Then FSO.CreateFolder (TmpPath)
  ' Открываем документ и пересохраняем во временную папку в формате docx (на случай если он был какого-то другого формата)
  DocXFile = TmpPath & "1.docx"
  Set Wrd = CreateObject("Word.Application")
  Set Doc = Wrd.Documents.Open(DocFile)
  Doc.SaveAs FileName:=DocXFile, FileFormat:=wdFormatXMLDocument
  Doc.Close: Wrd.Quit False
  ' Переименовываем файл в zip
  ZipFile = TmpPath & "1.zip"
  Name DocXFile As ZipFile
  ' Распаковываем файлы
  Set objShell = CreateObject("Shell.Application")
  Set FilesInZip = objShell.NameSpace(ZipFile).items
  objShell.NameSpace(TmpPath).CopyHere (FilesInZip)
  ' Получаем список картинок, которые теперь находятся в wordmedia
  Set sFolder = FSO.GetFolder(TmpPath & "wordmedia")
  For Each FileItem In sFolder.Files
    FileCopy FileItem.Path, ExportPath & "" & FileItem.Name
  Next FileItem
  ' Удаляем временную папку и всё ее содержимое
  Shell "cmd /c rd /S/Q """ & TmpPath & """"
End Sub

Способ 3. Сохранение файла в HTML

Принцип похож на 2-й способ. При сохранении в html формат создается папка, содержащая картинки и другие вложенные файлы и всё, что нужно, это взять из нее изображения. Минус в том, что изображения выгружаются по несколько раз в разных форматах.

ExportImages "C:Мои документыfile.doc", "C:Export"

Sub ExportImages(DocFile As String, ExportPath As String)
  ' Создаем временную папку
  TmpPath = ExportPath & "tmp"
  Set FSO = CreateObject("Scripting.FileSystemObject")
  If Not FSO.FolderExists(TmpPath) Then FSO.CreateFolder (TmpPath)
  ' Открываем файл и пересохраняем во временную папку в формате HTML
  Set Wrd = CreateObject("Word.Application")
  Set Doc = Wrd.Documents.Open(DocFile)
  Doc.SaveAs TmpPath & "tmp.html", FileFormat:=wdFormatHTML
  Doc.Close: Wrd.Quit False
  ' Получаем список файлов в папке с вложениями tmp.files
  Set sFolder = FSO.GetFolder(TmpPath & "tmp.files")
  For Each FileItem In sFolder.Files
    If FSO.GetExtensionName(FileItem.Name) = "jpg" Or _
       FSO.GetExtensionName(FileItem.Name) = "gif" Or _
       FSO.GetExtensionName(FileItem.Name) = "png" Then
      ' Копируем только картинки
      FileCopy FileItem.Path, ExportPath & "" & FileItem.Name
    End If
  Next FileItem
  ' Удаляем временную папку и всё ее содержимое
  Shell "cmd /c rd /S/Q """ & TmpPath & """"
End Sub

Способ 4. Экспорт изображений в формате BMP с использованием буфера обмена

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

Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
Private Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
Private Declare Function CloseClipboard Lib "user32" () As Long
Private Declare Function OleCreatePictureIndirect Lib "olepro32.dll" (PicDesc As uPicDesc, RefIID As GUID, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
Private Declare Function CopyImage Lib "user32" (ByVal handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
Const CF_BITMAP = 2
Const IMAGE_BITMAP = 0
Const LR_COPYRETURNORG = &H4
Private Type GUID
  Data1 As Long
  Data2 As Integer
  Data3 As Integer
  Data4(0 To 7) As Byte
End Type
Private Type uPicDesc
  Size As Long
  Type As Long
  hPic As Long
  hPal As Long
End Type

ExportImages "C:Мои документыfile.doc", "C:Export"

Sub ExportImages(DocFile As String, ExportPath As String)
  ' Открываем документ
  Set Wrd = CreateObject("Word.Application")
  Set Doc = Wrd.Documents.Open(DocFile)
  ' Цикл по картинкам в документе
  For i = 1 To Doc.InlineShapes.Count
    Doc.InlineShapes(i).Range.CopyAsPicture
    Clip2File ExportPath & "" & CStr(i) & ".bmp"
  Next i
  ' Закрываем документ
  Doc.Close
  Wrd.Quit False
End Sub

' Процедуры для работы с буфером обмена

Public Function Clip2File(OutputPath As String)
  Dim strOutputPath As String, oPic As IPictureDisp
  Set oPic = GetClipPicture()
  If Not oPic Is Nothing Then
    SavePicture oPic, OutputPath
    Clip2File = OutputPath
  Else
    Clip2File = ""
    MsgBox "Unable to retrieve bitmap from clipboard"
  End If
End Function

Private Function GetClipPicture() As IPicture
Dim h As Long, hPicAvail As Long, hPtr As Long, hPal As Long, hCopy As Long
  hPicAvail = IsClipboardFormatAvailable(CF_BITMAP)
  If hPicAvail <> 0 Then
    h = OpenClipboard(0&)
    If h > 0 Then
      hPtr = GetClipboardData(CF_BITMAP)
      hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)
      h = CloseClipboard
      If hPtr <> 0 Then Set GetClipPicture = CreatePicture(hCopy, 0, CF_BITMAP)
    End If
  End If
End Function

Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture
  Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, _
  IPic As IPicture
  Const PICTYPE_BITMAP = 1
  With IID_IDispatch
    .Data1 = &H7BF80980
    .Data2 = &HBF32
    .Data3 = &H101A
    .Data4(0) = &H8B
    .Data4(1) = &HBB
    .Data4(2) = &H0
    .Data4(3) = &HAA
    .Data4(4) = &H0
    .Data4(5) = &H30
    .Data4(6) = &HC
    .Data4(7) = &HAB
  End With
  With uPicInfo
    .Size = Len(uPicInfo)
    .Type = PICTYPE_BITMAP
    .hPic = hPic
    .hPal = 0
  End With
  r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)
  Set CreatePicture = IPic
End Function

У каждого из способов экспорта картинок есть свои плюсы и минусы. Самые быстрые в плане производительности скорее всего 1-й и 4-й способы. У 3-го способа есть плюс — сохраняет в файлы не только вставленные картинки, но так же и автофигуры, диаграммы и т.д. Какой из способов удобнее всего для вас — решайте сами.

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]

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

A couple quick things will get you to a solution.

The first is to loop through the worksheets in your workbook, like this:

Dim ws As Worksheet
For Each ws in ThisWorkbook.Sheets
    Debug.Print "The used range is " & ws.UsedRange.Address
Next ws

The next part is to understand how adding content to a Word document is accomplished. The main concept involves where the insertion point for the document is located — generally this is the current Selection.

When you cut and paste into a Word document, the content just pasted is still «selected». This means that any subsequent paste will effectively replace what you just inserted. So you have to move the selection point to the end of the document.

Putting it all together in an example program:

Option Explicit

Public Sub ExcelToWord()
    Dim wb As Workbook
    Set wb = ThisWorkbook

    '--- create the Word document
    Dim objWd As Word.Application
    Set objWd = CreateObject("word.application")
    objWd.Visible = True

    Dim objDoc As Word.Document
    Set objDoc = objWd.Documents.Add
    objDoc.PageSetup.Orientation = 1             '  portrait = 0

    Const wdPageBreak As Long = 7

    Dim ws As Worksheet
    For Each ws In wb.Sheets
        ws.UsedRange.Copy
        objWd.Selection.Paste
        '--- advance the selection point to the end of
        '    the document and insert a page break, then
        '    advance the insertion point past the break
        objDoc.Characters.Last.Select
        objWd.Selection.InsertBreak wdPageBreak
        objDoc.Characters.Last.Select
    Next ws
    'objDoc.SaveAs Application.ThisWorkbook.Path & ".dokument.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.

Источник

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

Documents.Save method (Word)

vbawd10.chm158072845

vbawd10.chm158072845

word

Word.Documents.Save

547ba7a6-3ef5-10db-834d-58fc62502454

06/08/2017

medium

Documents.Save method (Word)

Saves all the documents in the Documents collection.

Syntax

expression.Save (NoPrompt, OriginalFormat)

expression Required. A variable that represents a Documents object.

Parameters

Name Required/Optional Data type Description
NoPrompt Optional Variant True to have Word automatically save all documents. False to have Word prompt the user to save each document that has changed since it was last saved.
OriginalFormat Optional Variant Specifies the way the documents are saved. Can be one of the WdOriginalFormat constants.

Remarks

If a document has not been saved before, the Save As dialog box prompts the user for a file name.

[!includeSupport and feedback]

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