title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Document.Save method (Word) |
vbawd10.chm158007404 |
vbawd10.chm158007404 |
word |
Word.Document.Save |
7e329abc-0530-7016-7712-687de2c780a8 |
06/08/2017 |
medium |
Document.Save method (Word)
Saves the specified document.
Syntax
expression.Save
expression Required. A variable that represents a Document object.
Parameters:
NoPrompt (Optional)
If true
, then Word automatically saves all documents.
If false
, then Word prompts the user to save each document that has changed since it was last saved.
OriginalFormat (Optional)
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.
Example
This example saves the active document if it has changed since it was last saved.
If ActiveDocument.Saved = False Then ActiveDocument.Save
This example saves each document in the Documents collection without first prompting the user.
Documents.Save NoPrompt:=True, _ OriginalFormat:=wdOriginalDocumentFormat
See also
Document Object
[!includeSupport and feedback]
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
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
Автор lapin9126, 21 мая 2017, 08:33
Добрый день. Как сохранить открытый документ с другим именем, в другую папку расположенную в той же директории откуда открыт документ, и в нём выполнить макрос.
Например: документ с именем «Исходный» («С:оригиналы»), сохранить как «Исходный (копия)» в папку «обработано»(«С:оригиналыобработано») и в «Исходный (копия)» выполнить макрос.
Администратор
- Administrator
- Сообщения: 2,253
- Записан
Исходный файл после создания копии нужно закрыть или нужно, чтобы он оставался открытым?
Администратор
- Administrator
- Сообщения: 2,253
- Записан
Папка «обработано» должна быть создана (можно и с помощью макроса её создать).
Макрос
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,253
- Записан
Переменную «doc» не обязательно использовать, можно и без неё обойтись:
Макрос
Sub Макрос()
‘ Создание копии активного файла, при этом он закроется.
ActiveDocument.SaveAs2 FileName:=ActiveDocument.Path & «обработаноИсходный (копия).docx», FileFormat:=wdFormatXMLDocument
‘ Здесь делаете действия с новым созданным файлом, используя «ActiveDocument».
‘ Вывод имени активного файла в View — Immediate Window.
Debug.Print ActiveDocument.Name
End Sub
[свернуть]
При сохранении файла нужно присваивать имя исходного (открытого) файла с добавлением (копия), а не конкретно «Исходный (копия)» Это для примера было.
Администратор
- Administrator
- Сообщения: 2,253
- Записан
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?
I spent a lot of time doing this recently, because I disliked having to delete previous files when I did «Save As» — I wanted a «Save as and delete old file» answer. My answer is copied from here.
I added it to the quicklaunch bar which works wonderfully.
- Insert following code into normal.dotm template (found in
C:Documents and Settingsuser nameApplication DataMicrosoftTemplates
for Windows 7 for Word) - Save normal.dotm
- Add this to the quicklaunch toolbar in Word.
- Optional — remap a keyboard shortcut to this
- Optional — digitally sign your template (recommended)
Note this actually moves the old file to the Recycle Bin rather than trashing completely and also sets the new file name in a very convenient fashion.
Option Explicit
'To send a file to the recycle bin, we'll need to use the Win32 API
'We'll be using the SHFileOperation function which uses a 'struct'
'as an argument. That struct is defined here:
Private Type SHFILEOPSTRUCT
hwnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAnyOperationsAborted As Long
hNameMappings As Long
lpszProgressTitle As Long
End Type
' function declaration:
Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
'there are some constants to declare too
Private Const FO_DELETE = &H3
Private Const FOF_ALLOWUNDO = &H40
Private Const FOF_NOCONFIRMATION = &H10
Private Const FOF_SILENT = &H4
Function RecycleFile(FileName As String, Optional UserConfirm As Boolean = True, Optional HideErrors As Boolean = False) As Long
'This function takes one mandatory argument (the file to be recycled) and two
'optional arguments: UserConfirm is used to determine if the "Are you sure..." dialog
'should be displayed before deleting the file and HideErrors is used to determine
'if any errors should be shown to the user
Dim ptFileOp As SHFILEOPSTRUCT
'We have declared FileOp as a SHFILEOPSTRUCT above, now to fill it:
With ptFileOp
.wFunc = FO_DELETE
.pFrom = FileName
.fFlags = FOF_ALLOWUNDO
If Not UserConfirm Then .fFlags = .fFlags + FOF_NOCONFIRMATION
If HideErrors Then .fFlags = .fFlags + FOF_SILENT
End With
'Note that the entire struct wasn't populated, so it would be legitimate to change it's
'declaration above and remove the unused elements. The reason we don't do that is that the
'struct is used in many operations, some of which may utilise those elements
'Now invoke the function and return the long from the call as the result of this function
RecycleFile = SHFileOperation(ptFileOp)
End Function
Sub renameAndDelete()
' Store original name
Dim sOriginalName As String
sOriginalName = ActiveDocument.FullName
' Save As
Dim sFilename As String, fDialog As FileDialog, ret As Long
Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
'set initial name so you don't have to navigate to
fDialog.InitialFileName = sOriginalName
ret = fDialog.Show
If ret <> 0 Then
sFilename = fDialog.SelectedItems(1)
Else
Exit Sub
End If
Set fDialog = Nothing
'only do this if the file names are different...
If (sFilename <> sOriginalName) Then
'I love vba's pretty code
ActiveDocument.SaveAs2 FileName:=sFilename, FileFormat:= _
wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False, CompatibilityMode:=14
' Delete original (don't care about errors, I guess)
Dim hatersGonnaHate As Integer
hatersGonnaHate = RecycleFile(sOriginalName, False, True)
End If
End Sub