Word application save as

Show All

SaveAs Method

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

expression.SaveAs(FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter, Encoding, InsertLineBreaks, AllowSubstitutions, LineEnding, AddBiDiMarks)

expression    Required. An expression that returns a Document
object.

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 the user being prompted first.

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.

WdSaveFormat can be one of these WdSaveFormat constants.
wdFormatDocument Saves as a Microsoft Word document. Default.
wdFormatDOSText Saves text without formatting. Converts all section breaks, page breaks, and new line characters to paragraph marks. Uses the ANSI character set. Use this format to share documents between Word and DOS-based programs.
wdFormatDOSTextLineBreaks Saves text without formatting. Converts all line breaks, section breaks, and page breaks to paragraph marks. Use this format when you want to maintain line breaks, for example, when transferring documents to an electronic mail system.
wdFormatEncodedText Saves as an encoded text file. Use the Encoding argument to specify the code page to use.
wdFormatFilteredHTML Saves text with HTML tags with minimal cascading style sheet formatting. The resulting document can be viewed in a Web browser.
wdFormatHTML Saves all text and formatting with HTML tags so that the resulting document can be viewed in a Web browser.
wdFormatRTF Saves all formatting. Converts formatting to instructions that other programs, including compatible Microsoft programs, can read and interpret.
wdFormatTemplate Saves as a Word template.
wdFormatText Saves text without formatting. Converts all section breaks, page breaks, and new line characters to paragraph marks. Uses the ANSI character set. Use this format if the destination program cannot read any of the other available file formats.
wdFormatTextLineBreaks Saves text without formatting. Converts all line breaks, section breaks, and page breaks to paragraph marks. Use this format when you want to maintain line breaks, for example, when transferring documents to an electronic mail system.
wdFormatUnicodeText Saves as a Unicode text file. Converts text between common character encoding standards, including Unicode 2.0, Mac OS, Windows, EUC and ISO-8859 series.
wdFormatWebArchive Saves the text, images, and formatting as a single-file Web page.
wdFormatXML Saves text and formatting using Extensible Markup Language (XML) and the Word XML schema.
Other File Types To save in a file type for which there isn’t a constant, use the FileConverters
object to obtain the SaveFormat
property; then set the FileFormat argument to the value of the SaveFormat property.

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 Windows version of the imported graphics.

SaveFormsData    Optional Variant. True to save the data entered by a user in a form as a data 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 MsoEncoding. The code page, or character set, to use for documents saved as encoded text files. The default is the system code page.

MsoEncoding can be one of these MsoEncoding constants.
msoEncodingArabic
msoEncodingArabicASMO
msoEncodingArabicAutoDetect Not used with this method.
msoEncodingArabicTransparentASMO
msoEncodingAutoDetect Not used with this method.
msoEncodingBaltic
msoEncodingCentralEuropean
msoEncodingCyrillic
msoEncodingCyrillicAutoDetect Not used with this method.
msoEncodingEBCDICArabic
msoEncodingEBCDICDenmarkNorway
msoEncodingEBCDICFinlandSweden
msoEncodingEBCDICFrance
msoEncodingEBCDICGermany
msoEncodingEBCDICGreek
msoEncodingEBCDICGreekModern
msoEncodingEBCDICHebrew
msoEncodingEBCDICIcelandic
msoEncodingEBCDICInternational
msoEncodingEBCDICItaly
msoEncodingEBCDICJapaneseKatakanaExtended
msoEncodingEBCDICJapaneseKatakanaExtendedAndJapanese
msoEncodingEBCDICJapaneseLatinExtendedAndJapanese
msoEncodingEBCDICKoreanExtended
msoEncodingEBCDICKoreanExtendedAndKorean
msoEncodingEBCDICLatinAmericaSpain
msoEncodingEBCDICMultilingualROECELatin2
msoEncodingEBCDICRussian
msoEncodingEBCDICSerbianBulgarian
msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese
msoEncodingEBCDICThai
msoEncodingEBCDICTurkish
msoEncodingEBCDICTurkishLatin5
msoEncodingEBCDICUnitedKingdom
msoEncodingEBCDICUSCanada
msoEncodingEBCDICUSCanadaAndJapanese
msoEncodingEBCDICUSCanadaAndTraditionalChinese
msoEncodingEUCChineseSimplifiedChinese
msoEncodingEUCJapanese
msoEncodingEUCKorean
msoEncodingEUCTaiwaneseTraditionalChinese
msoEncodingEuropa3
msoEncodingExtAlphaLowercase
msoEncodingGreek
msoEncodingGreekAutoDetect Not used with this method.
msoEncodingHebrew
msoEncodingHZGBSimplifiedChinese
msoEncodingIA5German
msoEncodingIA5IRV
msoEncodingIA5Norwegian
msoEncodingIA5Swedish
msoEncodingISO2022CNSimplifiedChinese
msoEncodingISO2022CNTraditionalChinese
msoEncodingISO2022JPJISX02011989
msoEncodingISO2022JPJISX02021984
msoEncodingISO2022JPNoHalfwidthKatakana
msoEncodingISO2022KR
msoEncodingISO6937NonSpacingAccent
msoEncodingISO885915Latin9
msoEncodingISO88591Latin1
msoEncodingISO88592CentralEurope
msoEncodingISO88593Latin3
msoEncodingISO88594Baltic
msoEncodingISO88595Cyrillic
msoEncodingISO88596Arabic
msoEncodingISO88597Greek
msoEncodingISO88598Hebrew
msoEncodingISO88599Turkish
msoEncodingJapaneseAutoDetect Not used with this method.
msoEncodingJapaneseShiftJIS
msoEncodingKOI8R
msoEncodingKOI8U
msoEncodingKorean
msoEncodingKoreanAutoDetect Not used with this method.
msoEncodingKoreanJohab
msoEncodingMacArabic
msoEncodingMacCroatia
msoEncodingMacCyrillic
msoEncodingMacGreek1
msoEncodingMacHebrew
msoEncodingMacIcelandic
msoEncodingMacJapanese
msoEncodingMacKorean
msoEncodingMacLatin2
msoEncodingMacRoman
msoEncodingMacRomania
msoEncodingMacSimplifiedChineseGB2312
msoEncodingMacTraditionalChineseBig5
msoEncodingMacTurkish
msoEncodingMacUkraine
msoEncodingOEMArabic
msoEncodingOEMBaltic
msoEncodingOEMCanadianFrench
msoEncodingOEMCyrillic
msoEncodingOEMCyrillicII
msoEncodingOEMGreek437G
msoEncodingOEMHebrew
msoEncodingOEMIcelandic
msoEncodingOEMModernGreek
msoEncodingOEMMultilingualLatinI
msoEncodingOEMMultilingualLatinII
msoEncodingOEMNordic
msoEncodingOEMPortuguese
msoEncodingOEMTurkish
msoEncodingOEMUnitedStates
msoEncodingSimplifiedChineseAutoDetect Not used with this method.
msoEncodingSimplifiedChineseGBK
msoEncodingT61
msoEncodingTaiwanCNS
msoEncodingTaiwanEten
msoEncodingTaiwanIBM5550
msoEncodingTaiwanTCA
msoEncodingTaiwanTeleText
msoEncodingTaiwanWang
msoEncodingThai
msoEncodingTraditionalChineseAutoDetect Not used with this method.
msoEncodingTraditionalChineseBig5
msoEncodingTurkish
msoEncodingUnicodeBigEndian
msoEncodingUnicodeLittleEndian
msoEncodingUSASCII
msoEncodingUTF7
msoEncodingUTF8
msoEncodingVietnamese
msoEncodingWestern

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 any WdLineEndingType
constant.

WdLineEndingType can be one of these WdLineEndingType constants.
wdCRLF Default.
wdCROnly
wdLFCR Not used with this method.
wdLFOnly Not used with this method.
wdLSPS Not used with this method.

AddBiDiMarks   Optional Variant. True adds control characters to the output file to preserve bi-directional layout of the text in the original document.

Remarks

Security   Avoid using hard-coded passwords in your applications. If a password is required in a procedure, request the password from the user, store it in a variable, and then use the variable in your code. For recommended best practices on how to do this, see Security Notes for Microsoft Office Solution Developers.

Example

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

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

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

    Sub SaveAsTextFile()
    Dim strDocName As String
    Dim intPos As Integer

    'Find position of extension in filename
    strDocName = ActiveDocument.Name
    intPos = InStrRev(strDocName, ".")

    If intPos = 0 Then

        'If the document has not yet been saved
        'Ask the user to provide a filename
        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.SaveAs FileName:=strDocName, _
        FileFormat:=wdFormatText
End Sub
  

This 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.SaveAs FileName:="MyWP.doc", _
                FileFormat:=cnvWrdPrf.SaveFormat
        End If
    Next cnvWrdPrf

End Sub
  

This example illustrates a procedure that saves a document with a password.

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

Всем привет, с вами автор блога scriptcoding.ru. Данная публикация рассматривает сохранение документа в Word с помощью программирования и с помощью рядовых методов системы Windows.

По сути, что тут может быть особенно – нажал на кнопку «Сохранить» или «Сохранить Как» и все, радуйся жизни. Но, так как я очень люблю оперировать, тьфу ты… программировать, то я решил рассмотреть решение данной задачи программным путем.

Из всей объектной модели Word, компонентами, которые предоставляют средства для сохранения в ворде документа, являются объект Documentи коллекция Documents. По сути, у объекта Document есть два метода: Save и SaveAs, которые соответствуют диалоговым окнам «Сохранить» и «Сохранить Как«, а коллекция предоставляет только метод Save. Я уже рассматривал данный объект и коллекцию, но не углублялся в методы Save и SaveAs, а все потому, что у метода SaveAs огромное количество параметров, описание которых тянет на отдельную статью. Вот я и решил собрать все это воедино, и описать.

Объект Document – сохранение в ворде

как сохранить в ворде документ

Save(NoPrompt, OriginalFormat) – Показывает, как в ворде сохранить все файлы, которые входят в коллекцию Documents.

NoPrompt – Если значение true, то Word автоматически сохранит все файлы. Если значение false — Word предложит пользователю сохранить каждый файл, изменившийся с момента последнего сохранения.

OriginalFormat — Определяет, как документы будут сохранены в ворде. Содержит значение константы WdOriginalFormat:

  • wdOriginalDocumentFormat — 1 — Оригинальный формат.
  • wdPromptUser — 2 – Пользователю будет предложено выбрать формат.
  • wdWordDocument — 0 – Формат Microsoft Word.

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

SaveAs(FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter, Encoding, InsertLineBreaks, AllowSubstitutions, LineEnding, AddBiDiMarks, CompatibilityMode) – Сохранение файла Word с новым именем или форматом (Диалоговое окно «Сохранить Как»).

FileName – Позволяет задать путь и имя сохраняемого файла в ворде. Если задать только имя файла, то произойдет сохранение в ворд в папке по умолчанию – «Мои Документы». Если документ с таким именем уже существует, то произойдет перезапись без уведомления пользователя.

FileFormat – Задаем формат, в котором сохраняется документ в Word. Значение константы WdSaveFormat.

Константа WdSaveFormatпозволяет задать формат PDF (wdFormatPDF – 17) или XPS(wdFormatXPS — 18). Однако, что бы сохранить в ворде файл в этих форматах, вам придется установить расширение SaveAsPDFandXPS, которое доступно на сайте Майкрософт. Смотрите статью «Как в ворде сохранить документ в PDF формате»

LockComments – Содержит логические значения, true — заблокировать документ для комментариев. По умолчанию используется false.

Password – Пароль для открытия.

AddToRecentFiles – Содержит логическое значение, true — добавить документ в список недавно использовавшихся в меню Файл. По умолчанию используется True.

WritePassword — Пароль для сохранения в ворде изменений.

ReadOnlyRecommended — Содержит логические значения, true – открывать только для чтения. По умолчанию используется False.

EmbedTrueTypeFonts — Содержит логические значения, true – сохранить TrueType шрифты вместе с документом.

SaveNativePictureFormat – Параметр используется, если графики были импортированы из другой платформы (например, Macintosh). true — сохранить в ворд только версию Microsoft Windows импортируемых графиков.

SaveFormsData –true — сохранить в ворд данные, введенные пользователем в форме в виде записи.

SaveAsAOCELetter – Параметр актуален, если документ имеет прикрепленное почтовое вложение. true – сохраняем документ Word как AOCE письмо.

Encoding – Отвечает за кодировку текста. По умолчанию используется системная кодировка. Параметр должен содержать значение константы MsoEncoding.

InsertLineBreaks – Параметр используется, если происходит сохранение документа в Word в виде текстового файла. true — вставить разрывы строк в конце каждой строки текста.

AllowSubstitutions – Актуально, если файл ворд сохраняется в виде текстового файла. Значение true позволяет Word заменить некоторые символы в тексте их упрощенными аналогами. Например, символа авторского права. По умолчанию используется значение False.

LineEnding – Определяет форматирование строк и абзацев в документах, сохраненных в виде текстовых файлов. Может быть одним из следующих значений константы WdLineEndingType:

  • wdCRLF — 0 — возврат каретки и строки.
  • wdCROnly — 1 — Возврат только каретки.

AddBiDiMarks – true — добавить управляющие символы в выходной файл.

CompatibilityMode — Режим совместимости, который Word2010 использует при открытии документа. Значение константы WdCompatibilityMode:

  • wdCurrent — 65535 — Совместимость режим эквивалентен последней версии Microsoft Word.
  • wdWord2003 — 11 — Word2010 введен в режиме, который наиболее совместим с Word2003.
  • wdWord2007 — 12 — Word2010 введен в режиме, который наиболее совместим с Office Word2007.
  • wdWord2010 — 14 — Word2013 введен в режиме, который наиболее совместим.
  • wdWord2013 — 15 — По умолчанию. Все функции Word 2013 включены.

Если данный параметр отсутствует, то принимается значение 0 – сохраняется текущий режим совместимости.

Коллекция Documents – как в ворде сохранить документ

сохранение в word документа

Save(NoPrompt, OriginalFormat) – Метод выполняет ту же функцию, что и Save объекта Document, только для коллекции Documents.

Хорошо, с теорией закончили, теперь привожу два примера программного кода на языке VBScript и JScript, котрые создают новый документ, вставляют в него форматированный текст, содержащий информацию о сервере сценариев Windows Script Host и сохраняют в ворде данный документ в текущем каталоге (каталог, откуда был произведен запуск сценария).

Программный код на языке VBSCRIPT:

' ----------------------------------------------------------------------------
' Сохранение документа в Word
' SaveAs.vbs
' ----------------------------------------------------------------------------
Option Explicit
 
dim oWord, oDoc, oSel, oFont, oShell, CurDir
 
set oWord = WScript.CreateObject("Word.Application")   
set oShell = WScript.CreateObject("WScript.Shell")
set oDoc = oWord.Documents                       
oDoc.Add()                                                            
set oSel = oWord.Selection                           
oWord.Visible = True                                           
set oFont = oSel.Font
 
CurDir = oShell.CurrentDirectory        'текущая папка
 
with oFont
    .Size = 20
    .Name = "Times New Roman"
    .Bold=true
    .Colorindex=2
end with
 
oSel.TypeText "как в ворде сохранить документ"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       ' word сохранение файла
 
with oFont
    .Size = 12
    .Bold=false
    .Colorindex=0
end with
 
With oSel
     .TypeParagraph
     .TypeParagraph
End With
 
With WScript
     call TXInsert("Name: ", .Name & "")
     call TXInsert("FullName: ", .FullName & "")
     call TXInsert("ScriptName: ", .Name & "")
     call TXInsert("ScriptFullName: ", .FullName & "")
     call TXInsert("Path: ", .Path & "")
     call TXInsert("Version: ", .Version & "")
     call TXInsert("Application: ", .Application & "")
     call TXInsert("Timeout: ", .Timeout & "")
     call TXInsert("BuildVersion: ", .BuildVersion & "")
End With
 
oDoc(1).SaveAs CurDir & "WscInfo_vbs.doc", 0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      ' сохранение в ворде
 
Sub TXInsert(a, b)
     With oSel
                 oFont.Bold=true
                 .TypeText a
                 .EndOf
                 oFont.Bold=false
                 .TypeText b
                 .TypeParagraph
     End With
End Sub

сохранение файла в Word

Программный код на языке JSCRIPT:

// ----------------------------------------------------------------------------
// Сохранение документа в Word
// SaveAs.js
// ----------------------------------------------------------------------------
var oWord1, oDoc1, oSel1, oFont1, oShell1, CurDir1;
 
oWord1 = WScript.CreateObject("Word.Application");
oShell1 = WScript.CreateObject("WScript.Shell");
oDoc1 = oWord1.Documents;                       
oDoc1.Add();                                                           
oSel1 = oWord1.Selection;                            
oWord1.Visible = true;                                           
oFont1 = oSel1.Font;
 
CurDir1 = oShell1.CurrentDirectory;        //текущая папка
 
with(oFont1){
    Size = 20;
    Name = "Times New Roman";
    Bold=true;
    Colorindex=2;
}
 
oSel1.TypeText("как в ворде сохранить документ");                                                                                                                                                                                                                                                                                                                                                                                                                      // word сохранение файла
 
with(oFont1){
    Size = 12;
    Bold=false;
    Colorindex=0;
}
 
with(oSel1){
     TypeParagraph();
     TypeParagraph();
}
 
with(WScript){
     TXInsert1("Name: ", Name + "");
     TXInsert1("FullName: ", FullName + "");
     TXInsert1("ScriptName: ", Name + "");
     TXInsert1("ScriptFullName: ", FullName + "");
     TXInsert1("Path: ", Path + "");
     TXInsert1("Version: ", Version + "");
     TXInsert1("Application: ", Application + "");
     TXInsert1("Timeout: ", Timeout + "");
     TXInsert1("BuildVersion: ", BuildVersion + "");
}
 
oDoc1(1).SaveAs(CurDir1 + "\WscInfo_js.doc", 0);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              // сохранение в ворде
 
function TXInsert1(a, b){
     with(oSel1){
                 oFont1.Bold=true;
                 TypeText(a);
                 EndOf();
                 oFont1.Bold=false;
                 TypeText(b);
                 TypeParagraph();
     }
}

И так, с программированием закончили, теперь можно приступить к разбору программного кода. Обратите внимание, что в примере для JSCRIPT я изменил имена переменных, добавив к ним единицу.

В самом начале происходит подключение различных классов и коллекций, которые позволяет подключить объектную модель Word, и создать новый документ. Далее следует объявление переменной CurDir, она будет хранить путь к текущему каталогу, именно в этот каталог произойдет сохранение документа в ворде. Доступ к текущему каталогу осуществляется через класс WScript.Shell – смотрите статью «Объект WScript.Shell метод ExpandEnvironmentStrings и свойство CurrentDirectory — Переменные среды Windows и текущий каталог«.

Далее с помощью класса Font – статья «Объект Word Font — параметры форматирования шрифта«, происходит настройка параметров текста: цвет, размер и так далее. После с помощью метода TypeText класса Selection происходит вставка фразы «как в ворде сохранить документ«, данная фраза также будет отформатирована: жирный шрифт и увеличенный размер символов. После мы дважды вставляет параграф – метод TypeParagraph.

Следующим этапом является использование несколько раз процедуры TXInsert, который будет передаваться два параметра: две текстовые строки. Все происходит так, что процедура вставляет в документ параметры свойств класса WScript – имя свойства и его значение.

После всей проделанной работы происходит вызов метода SaveAs, которые отвечает за сохранение файла Word. В нашем случае, в сценарии на языке VBSCRIPT произойдет сохранение документа в ворде под именем «WscInfo_vbs.doc«, а в сценарии на языке JSCRIPT – сохранение файла в ворде под именем «WscInfo_js.doc«

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

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

Использование Word в приложениях на Visual Basic 6 открывает широчайшие возможности для создания профессионально оформленных документов (например отчетов). Это часто необходимо при работе в фирме или на предприятии для обеспечения документооборота. Основным преимуществом использования Wordа в этом случае является то, что практически на всех компьютерах, используемых в фирмах и на предприятиях установлены Windows и пакет Microsoft Office. Поэтому подготовленные документы Word не требуют каких-либо дополнительных усилий для их просмотра, печати и редактирования. Единственное что нужно помнить, это то что работа через автоматизацию OLE (связывание и внедрение объектов) на деле оказывается довольно медленной технологией, хотя и очень полезной.

Чтобы использовать объекты Word в Visual Basic , необходимо инсталлировать сам Word. После этого вы получаете в своё распоряжение библиотеку Microsoft Word Object Library, которую нужно подключить к текущему проекту через диалоговое окно «Разработать»>>»Ссылки» (References) и указать Microsoft Word 9.0 Object Library (для Word 2000).

Два самых важных объекта Word это Word.Application и Word.Document. Они обеспечивают доступ к экземпляру приложения и документам Word.

Поэтому в раздел Generals «Общее» формы введите следующий код для объявления объектных переменных приложения Word и документа Word.

Dim WordApp As Word.Application '  экземпляр приложения
Dim DocWord As Word.Document'  экземпляр документа

Чтобы создать новый экземпляр Word, введите такой код кнопки;

Private Sub Комманда1_Click()

'создаём  новый экземпляр Word-a
Set WordApp = New Word.Application

'определяем видимость Word-a по True - видимый,
'по False - не видимый (работает только ядро)
WordApp.Visible = True

'создаём новый документ в Word-e
Set DocWord = WordApp.Documents.Add

'// если нужно открыть имеющийся документ, то пишем такой код
'Set DocWord = WordApp.Documents.Open("C:DDD.doc")

'активируем его
DocWord.Activate

End Sub

Для форматирования печатной области документа используйте данный код:

(вообще-то Word использует для всех размеров своих элементов пункты, поэтому для использования других единиц измерения, необходимо использовать встроенные функции форматирования.)

Например:

  • CentimetersToPoints(Х.ХХ) — переводит сантиметры в пункты.
  • MillimetersToPoints(X.XX) — переводит миллиметры в пункты
Private Sub Комманда2_Click()

'отступ слева "2,0 сантиметра"
DocWord.Application.Selection.PageSetup.LeftMargin = CentimetersToPoints(2)

'отступ справа "1,5 сантиметра"
DocWord.Application.Selection.PageSetup.RightMargin = CentimetersToPoints(1.5)

'отступ сверху "3,5 сантиметра"
DocWord.Application.Selection.PageSetup.TopMargin = CentimetersToPoints(3.5)

'отступ снизу "4,45 сантиметра"
DocWord.Application.Selection.PageSetup.BottomMargin = CentimetersToPoints(4.45)

End Sub

Небольшое отступление.

Для того чтобы в своём приложении не писать постоянно одно и тоже имя объекта, можно использовать оператор With.

Например код находящейся выше можно переписать так:

With DocWord.Application.Selection.PageSetup
.LeftMargin = CentimetersToPoints(2)
.RightMargin = CentimetersToPoints(1.5)
.TopMargin = CentimetersToPoints(3.5)
.BottomMargin = CentimetersToPoints(4.45)
End With

Если вам необходимо создать документ Word с нестандартным размером листа, то используйте данный код:

With DocWord.Application.Selection.PageSetup
.PageWidth = CentimetersToPoints(20)    'ширина листа (20 см)
.PageHeight = CentimetersToPoints(25)   'высота листа (25 см)
End With

Данный код меняет ориентацию страницы (практически меняет местами значения ширины и высоты листа):

 
DocWord.Application.Selection.PageSetup.Orientation = wdOrientLandscape
  • wdOrientLandscape — альбомная ориентация ( число 1)
  • wdOrientPortrait — книжная ориентация ( число 0)

Для сохранения документа под новым именем и в определенное место
используйте данный код код:

'сохраняем документ как
DocWord.SaveAs "c:DDD.doc"

После такого сохранения вы можете про ходу работы с документом сохранять его.

'сохраняем документ
DocWord.Save

Или проверить, были ли сохранены внесенные изменения свойством Saved и если изменения не были сохранены — сохранить их;

If DocWord.Saved=False Then DocWord.Save

Завершив работу с документом, вы можете закрыть сам документ методом Close и сам Word методом Quit.

'закрываем документ (без запроса на сохранение)
DocWord.Close True

'закрываем Word (без запроса на сохранение)
WordApp.Quit True

'уничтожаем обьект - документ
Set DocWord = Nothing

'уничтожаем обьект - Word
Set WordApp = Nothing

Если в методах Close и Quit не использовать необязательный параметр True то Word запросит согласие пользователя (если документ не был перед этим сохранён) на закрытие документа.

Если вам необходимо оставить Word открытым, просто не используйте методы Close и Quit.

Если вам необходимо поставить пароль на документ, то используйте код:

DocWord.Protect wdAllowOnlyComments, , "123456789"

Пример программы можно скачать здесь.

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]

I have a vba macro that makes some changes to the current document and determines a filename that should be used for it — if the document isn’t saved as that filename yet the user should be prompted to do so (but should be able to alter the default setting).

I found two possibilities that both are not perfect (I’d need a mix of those two).

First approach:

Application.Dialogs(wdDialogFileSaveAs).Show

Opens the Save As dialog and lets you change the format and name of the file, but the default file name is the old filename or the title (up to the first special character like blank or -) of the document (in case it wasn’t saved yet — changing the title of the document is of little help as the suggested filename will contain -). Is it possible to change the initial filename shown in the Save As dialog?

Second approach:

Application.FileDialog(msoFileDialogSaveAs).InitialFileName = filename
Dim choice As Integer
choice = Application.FileDialog(msoFileDialogSaveAs).Show
If choice <> 0 Then
    filename = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
    Call ActiveDocument.SaveAs(filename:=filename, FileFormat:=wdFormatDocumentDefault)
End If

The FileDialog will choose a filename only, so we have to save it explicitely.
This approach will show the filename I want, but if the user changes the suffix to e.g .pdf the file will still be saved in the .docx format (using the suffix .pdf). I didn’t plan to have huge distinction of cases here for the rare case the user needs a different format than .docx. Is there an easy way to save the file in the correct format using this second approach?

Понравилась статья? Поделить с друзьями:
  • Word application open document
  • Word application on close
  • Word application new document
  • Word application is running
  • Word application in net