Word макрос для сохранения в pdf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Sub MakeDocs(flagPrint As Integer)
   Const wdExportFormatPDF As Integer = 17, _
         wdExportOptimizeForOnScreen As Integer = 1, _
         wdExportAllDocument As Integer = 0, _
         wdExportDocumentContent As Integer = 0, _
         wdExportCreateNoBookmarks As Integer = 0
   Dim i As Integer, OutDoc As String, OutPath As String, _
       Age As Integer, suffix As String, sAddr As String, sExt As String
 
   If Dir(ThisWorkbook.Path & "" & template) = "" Then
      Call MsgBox("Нет файла шаблона " & template, vbCritical + vbOKOnly, "Внимание!")
      Exit Sub
   End If
 
   Application.ScreenUpdating = False
   On Error Resume Next
   Set WA = GetObject(, "Word.Application")
   If WA Is Nothing Then Set WA = CreateObject("Word.Application")
 
   Set WD = WA.Documents.Open(Filename:=ThisWorkbook.Path & "" & template)
 
   Call FieldReplace("{NAME_R}", frmWork.txtFIO.Text)                      ' ФИО русское
'... поскипаны прочие операции с word-файлом ...
 
   Application.StatusBar = "Сохранение файла..."
 
   OutPath = frmWork.txtOut.Text ' каталог сохранения
   ' формируем полное имя файла из каталога и собственно имя из элементов на форме
   OutDoc = OutPath & "" & Replace(Replace(Replace(frmWork.txtFIO.Text & " " & frmWork.dtForm.Caption, " ", "_"), ".", "_"), ":", "_")
   ' Сохранить документ в PDF
   WD.ExportAsFixedFormat OutputFileName:=OutDoc, ExportFormat:=wdExportFormatPDF, _
      OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForOnScreen, _
      Range:=wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _
      IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:=wdExportCreateNoBookmarks, _
      DocStructureTags:=True, BitmapMissingFonts:=True, UseISO19005_1:=False
 
   Call WaitFor(1)   ' 1 сек ожидания
   ' и закрыть всё
   WD.Close SaveChanges:=False
   WA.Quit False
 
   Set WD = Nothing
   Set WA = Nothing
 
   Application.ScreenUpdating = True
   Application.StatusBar = "Готово"
End Sub

Приветствую всех читателей блога scriptcoding.ru. В этой статье мы рассмотрим, как сохранить документ Word в PDF формате, или в формате XPS.

По умолчанию, само приложение Word не позволяет сохранять документы в заданных форматах (исключением являются последние версии), что немного обидно, учитывая функциональные возможности самой компании Майкрософт. Но это и не удивительно, так как дядюшка Билл любит радовать своего потребителя различными косяками и багами – каких только нецензурных слов удостоился тот же Internet Explorer.

В первую очередь, стоит сообщить хорошую новость – есть расширение «SaveAsPDFandXPS«, которое находится в бесплатном доступе и его можно скачать с официального сайта Майкрософт. После установки данного расширения появляется возможность сохранить страницу как PDF в Word документе, причем, как в ручном режиме (соответствующий тип файла появится в диалоговом окне «Сохранить Как«), так и программным путем.

Собственно, программный метод получения формата pdf мы и рассмотрим, а именно, метод ExportAsFixedFormatобъекта Range, который позволяет экспортировать целиком или частично содержимое документа в нужный формат.

Данный метод содержит много параметров, и поэтому, я решил описать его в отдельной статье.

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

ExportAsFixedFormat(OutputFileName, ExportFormat, OpenAfterExport, OptimizeFor, ExportCurrentPage, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags, BitmapMissingFonts, UseISO19005_1, FixedFormatExtClassPtr) — Сохраняет часть документа Word как PDF или XPS формат. Только первые два параметра являются обязательными.

OutputFileName– Обязательный параметр, который задает путь и имя сохраняемого в Word PDF или XPS-файла.

ExportFormat– Обязательный параметр, который определяет формат сохранения в Word (PDF или XPS). Значение константы WdExportFormat:

  • wdExportFormatPDF — 17 — Экспортировать документ в формате PDF.
  • wdExportFormatXPS — 18 — Экспортировать документ в формате XML Paper Specification (XPS).

OpenAfterExport— Открыть новый файл после экспорта содержимого – значение true.

OptimizeFor– Параметр указывает, следует ли оптимизировать файл для экрана или для печати. Значение константы WdExportOptimizeFor:

  • wdExportOptimizeForOnScreen — 1 – Для экрана — низкое качество и маленький размер.
  • wdExportOptimizeForPrint — 0 — Для печати – высокое качество и большой размер.

ExportCurrentPage– Определяет, что нужно экспортировать, всю страницу (true) или только выбранный диапазон (false). Word сохранение в PDF.

Item— Определяет процесс экспорта — включать только текст или текст с разметкой. Значение константы WdExportItem:

  • wdExportDocumentContent — 0 — Экспорт документа без разметки.
  • wdExportDocumentWithMarkup — 7 — Экспорт документа с разметкой.

IncludeDocProps— Указывает, следует ли включить свойства документа в недавно экспортируемый файл (true). Сохранить как PDF в Word.

KeepIRM— Указывает, следует ли копировать права доступа IRM в XPS документ, если исходный документ имеет защиту IRM. Значение по умолчанию True.

CreateBookmarks — Указывает, следует ли экспортировать закладки и тип закладки. Значение константы WdExportCreateBookmarks:

  • wdExportCreateHeadingBookmarks — 1 — Создание закладки в экспортируемом документе для всех заголовком, которые включают только заголовки внутри основного документа и текстовые поля не в пределах колонтитулов, концевых сносок, сносок или комментариев.
  • wdExportCreateNoBookmarks — 0 — Не создавать закладки в экспортируемом документе.
  • wdExportCreateWordBookmarks — 2 — Создание закладки в экспортируемом документе для каждой закладки, которая включает все закладки кроме тех, которые содержатся в верхнем и нижнем колонтитулах.

DocStructureTags— Указывает, следует ли включать дополнительные данные, которые помогут при чтении с экрана, например информацию о потоке и логическую организацию содержимого. Значение по умолчанию True. Документ Word сохранить в PDF.

BitmapMissingFonts— Указывает, следует ли включать растровое изображение текста. Установите этот параметр в значение True, когда шрифт не поддерживается в PDF.

UseISO19005_1 и FixedFormatExtClassPtr – Данные параметры не предоставляют практического интереса.

Теперь давайте рассмотрим два примера программного кода – на языке VBScript и JScript. Оба примера создают новый документ Word, далее вставляют в него текст, содержащий информацию о сервере сценариев Windows Script Host.

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

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

<

' ----------------------------------------------------------------------------
' Как документ word сохранить в pdf формате
' ExportAsFixedFormat.vbs
' ----------------------------------------------------------------------------
Option Explicit
 
dim oWord, oDoc, oSel, oFont, oShell, oRange, oPars, cur_dir, REnd
 
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
set oRange = oDoc(1).Range()
 
'Текущий каталог
cur_dir = oShell.CurrentDirectory
 
with oFont
    .Size = 20
    .Name = "Times New Roman"
    .Bold=true
    .Colorindex=2
end with
 
oSel.TypeText "Word - сохранение в PDF"
 
with oFont
    .Size = 12
    .Bold=false
    .Colorindex=0
end with
 
With oSel
     .TypeParagraph
     .TypeParagraph
End With
 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    '   документ word сохранить в pdf
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
 
set oPars = oRange.Paragraphs
REnd = oPars(oPars.Count).Range.End       
 
call LRange(4,7)
With oRange
     ' Сохраняем абзацы с 4 по 7 в PDF формате
     .ExportAsFixedFormat cur_dir & "WscInfo_VBS.pdf", 17, true
 
     .setRange 0, REnd
     ' Сохраняем весь документ Word в PDF формате
     .ExportAsFixedFormat cur_dir & "WscInfoFull_VBS.pdf", 17, true
End With
 
' Используем метод SaveAs для сохранения документа
oDoc(1).SaveAs cur_dir & "WscInfoFull_SaveAs_VBS.pdf", 17
 
' процедура выбора диапазона
Sub LRange(a, b)
     With oRange
                 .setRange 0, REnd
                 .setRange oPars(a).Range.Start, oPars(b).Range.End
     End With
End Sub
 
' Процедура для форматирования шрифта и вставки абзаца                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              как сохранить ворд в пдф
Sub TXInsert(a, b)
     With oSel
                 oFont.Bold=true
                 .TypeText a
                 .EndOf
                 oFont.Bold=false
                 .TypeText b
                 .TypeParagraph
     End With
End Sub

как сохранить файл ворд в пдф

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

// ----------------------------------------------------------------------------
// Как документ word сохранить в pdf формате
// ExportAsFixedFormat.js
// ----------------------------------------------------------------------------
var oWord1, oDoc1, oSel1, oFont1, oShell1, oRange1, oPars1, CurDir1, REnd;
 
oWord1 = WScript.CreateObject("Word.Application");
oShell1 = WScript.CreateObject("WScript.Shell");
oDoc1 = oWord1.Documents;                                       
oDoc1.Add();                                                                           
oSel1 = oWord1.Selection;                                                    
oWord1.Visible = true;                                                           
oFont1 = oSel1.Font;
oRange1 = oDoc1(1).Range();
 
//Текущий каталог
CurDir1 = oShell1.CurrentDirectory;
 
with(oFont1){
    Size = 20;
    Name = "Times New Roman";
    Bold=true;
    Colorindex=2;
}
 
oSel1.TypeText("Word - сохранение в PDF");
 
with(oFont1){
    Size = 12;
    Bold=false;
    Colorindex=0;
}
 
oSel1.TypeParagraph();
oSel1.TypeParagraph();
 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         //  документ word сохранить в pdf
with(WScript){
     TXInsert("Name: ", Name + "");
     TXInsert("FullName: ", FullName + "");
     TXInsert("ScriptName: ", Name + "");
     TXInsert("ScriptFullName: ", FullName + "");
     TXInsert("Path: ", Path + "");
     TXInsert("Version: ", Version + "");
     TXInsert("Application: ", Application + "");
     TXInsert("Timeout: ", Timeout + "");
     TXInsert("BuildVersion: ", BuildVersion + "");
}
 
oPars1 = oRange1.Paragraphs;
REnd = oPars1(oPars1.Count).Range.End;       
 
LRange(4,7);
with(oRange1){
     // Сохраняем абзацы с 4 по 7 в PDF формате
     ExportAsFixedFormat (CurDir1 + "\WscInfo_JS.pdf", 17, true);
     setRange(0, REnd);
     // Сохраняем весь документ Word в PDF формате
     ExportAsFixedFormat (CurDir1 + "\WscInfoFull_JS.pdf", 17, true);
}
 
// Используем метод SaveAs для сохранения документа
oDoc1(1).SaveAs(CurDir1 + "\WscInfoFull_SaveAs_JS.pdf", 17);
 
// процедура выбора диапазона
function LRange(a, b){
     with(oRange1){
                 setRange(0, REnd)
                 setRange(oPars1(a).Range.Start, oPars1(b).Range.End)
     }
}
 
// Процедура для форматирования шрифта и вставки абзаца                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      как сохранить ворд в пдф
function TXInsert(a, b){
     with(oSel1){
                 oFont1.Bold=true;
                 TypeText(a);
                 EndOf();
                 oFont1.Bold=false;
                 TypeText(b);
                 TypeParagraph();
     }
}

Сами сценарии сохраняют документ Word в формате PDF в текущем каталоге, то есть, в каталоге, из которого произошел запуск сценария. Две функции LRange и TXInsert позволяют выбрать нужный диапазон текста (точнее нужные абзацы) и применить форматирование текста (тип шрифта и размер). Метод SaveAs также позволяет сохранить документ Word в PDF формате или в любом другом формате, данный метод принадлежит объекту Document. Более детально похожий пример я рассмотрел в этой статье.

In this article, we’re going to create an additional button in our Word toolbar which creates a PDF file of our loaded file with one simple click. We are going to use the function to create Macros, which are little ‘programs’ in How to Save Your Word Document as PDF with One Click (Using a Macro)Office applications. The Macro we are going to write will literally save the file as PDF in the same directory and with the same filename as the opened document. The image on the right is what it will look like.

We will modify our normal.dot Word-Template to include a VBA-Macro, which saves our file as PDF.

So, let’s get started!

Note

  • This article uses German interfaces, but the screenshots should be clear enough for all languages.

Step 1 Open Word and the VBA window

Open Microsoft Office Word.

Note

  • This tutorial is based on Microsoft Office Professional Plus 2010, but works with other versions, as well. For Office 2007 you’ll need the PDF extension.

Open the VBA menu by selecting the «Views» and selecting «Macros» -> «View Macros». All this can also be done by holding ALT and pressing F K M. If you are not using Word 2010, try this.

How to Save Your Word Document as PDF with One Click (Using a Macro)

How to Save Your Word Document as PDF with One Click (Using a Macro)

Create a new Macro: Enter a name for our Macro — let’s say «PDF» — and click on «Create». The name should appear in the list below. Click on «Edit» to open the coding window of our project.

Step 2 Coding our Macro

Be sure that «Normal»->»Modules»->»NewMacros» is selected in the upper left tree-structure (like in the image)

How to Save Your Word Document as PDF with One Click (Using a Macro)

These two lines of VBA-Code should already be there:

Sub PDF()

End Sub

Add the following lines in-between those two predefined function lines:

If InStr(1, ActiveDocument.Name, «.») = 0 Then

    MsgBox «File has to be saved first!»

    Exit Sub

End If

ActiveDocument.SaveAs2 Replace(ActiveDocument.FullName, ActiveDocument.Name, «») + Mid(ActiveDocument.Name, 1, InStr(1, ActiveDocument.Name, «.») — 1) + «.pdf», Word.WdSaveFormat.wdFormatPDF

It should look like this now:

How to Save Your Word Document as PDF with One Click (Using a Macro)

Click «Save» in the upper left of the window and close it.

Step 3 Creating a new button for our Macro

So, this is also different in all the Office versions. But it’s common that you have to right-click on your toolbar / ribbon and select the «Edit Toolbar» item.

How to Save Your Word Document as PDF with One Click (Using a Macro)

Select «Macros» in the left drop-down list. There should be our Macro.

How to Save Your Word Document as PDF with One Click (Using a Macro)

Open «View» in the tree-structure on the right and click «Create Group». You can edit the properties with the context menu (right-click). Enter something like «Macro Shortcuts».

Select the Macro (on the left) and the new group (on the right) and click «Add» (top button in the middle).

After adding rename our Macro (on the right side — right-click) to something you like. I’d say «Export to PDF».

Now close Word.

Step 4 You’re done!

Now on any new document — after you saved it — clicking this button will instantly save your file as a PDF. No more «Save As» dialogs and adventures through file type menus.

I know this is a bit tricky because of the differences in the details of the Office Versions (e.g. Ribbon and non-Ribbon UI). If you’re stuck at any point feel free to:

  1. Google your problem
  2. Google some more — there are solutions all over the Internet
  3. Leave a comment

Want to master Microsoft Excel and take your work-from-home job prospects to the next level? Jump-start your career with our Premium A-to-Z Microsoft Excel Training Bundle from the new Gadget Hacks Shop and get lifetime access to more than 40 hours of Basic to Advanced instruction on functions, formula, tools, and more.

Buy Now (97% off) >

Other worthwhile deals to check out:

  • 97% off The Ultimate 2021 White Hat Hacker Certification Bundle
  • 98% off The 2021 Accounting Mastery Bootcamp Bundle
  • 99% off The 2021 All-in-One Data Scientist Mega Bundle
  • 59% off XSplit VCam: Lifetime Subscription (Windows)
  • 98% off The 2021 Premium Learn To Code Certification Bundle
  • 62% off MindMaster Mind Mapping Software: Perpetual License
  • 41% off NetSpot Home Wi-Fi Analyzer: Lifetime Upgrades

WORD Макросы для сохранения слияния и рассылки в отдельные файлы формата DOC или PDF


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

Sub ToTranslitDoc()
Dim i As Long
Dim oMerge As MailMerge
Dim oData As MailMergeDataSource
Set oMerge = ActiveDocument.MailMerge
Set oData = oMerge.DataSource
Application.ScreenUpdating = False
For i = 1 To oData.RecordCount
With oData
.FirstRecord = i
.LastRecord = i
.ActiveRecord = i
End With
With oMerge
.Destination = wdSendToNewDocument
.Execute Pause:=False
End With
With ActiveDocument
.SaveAs («d:TMP» & oData.DataFields(«Translit»).Value & «.doc»)
.Close
End With
Next i
Set oData = Nothing
Set oMerge = Nothing
Application.ScreenUpdating = True
End Sub
Sub ToTranslitPdf()
Dim i As Long
Dim oMerge As MailMerge
Dim oData As MailMergeDataSource
Set oMerge = ActiveDocument.MailMerge
Set oData = oMerge.DataSource
Application.ScreenUpdating = False
For i = 1 To oData.RecordCount
With oData
.FirstRecord = i
.LastRecord = i
.ActiveRecord = i
End With
With oMerge
.Destination = wdSendToNewDocument
.Execute Pause:=False
End With
With ActiveDocument
.SaveAs FileName:=«d:TMP» & oData.DataFields(«Translit»).Value & «.pdf», FileFormat:=wdFormatPDF
.Close (False)
End With
Next i
Set oData = Nothing
Set oMerge = Nothing
Application.ScreenUpdating = True
End Sub

Группа: Пользователи

Ранг: Участник

Сообщений: 59


Репутация:

0

±

Замечаний:
20% ±


2010

Привет. Есть макрос, который сохраняет документ word в формат pdf по названию файла. Проблема состоит в том, что при сохранении макрос запрашивает «Перезаписать или изменить название», если я меняю название то ошибка. Прошу поправить ошибку
[vba]

Код

Sub Word_ExportPDF()
‘https://www.thespreadsheetguru.com/the-code-vault/microsoft-word-vba-to-save-document-as-a-pdf-in-same-folder
‘PURPOSE: Generate A PDF Document From Current Word Document
‘NOTES: PDF Will Be Saved To Same Folder As Word Document File
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim CurrentFolder As String
Dim FileName As String
Dim myPath As String
Dim UniqueName As Boolean

UniqueName = False

‘Store Information About Word File
‘Сохранить информацию о файле Word
  myPath = ActiveDocument.FullName
  ‘CurrentFolder = ActiveDocument.Path & «»  ‘Сохранить файл pdf там же где и doc
  CurrentFolder = «D:YandexDisk1C Счета и договора»  ‘Сохранить файл pdf по пути..
  FileName = Mid(myPath, InStrRev(myPath, «») + 1, _
   InStrRev(myPath, «.») — InStrRev(myPath, «») — 1)

‘Does File Already Exist?
‘Уже существует ли файл?
  Do While UniqueName = False
    DirFile = CurrentFolder & FileName & «.pdf»
    If Len(Dir(DirFile)) <> 0 Then
      UserAnswer = MsgBox(«Файл уже существует. Нажмите » & _
       «[Yes] что бы перезаписать. Нажмите [No] что бы переименовать.», vbYesNoCancel)

            If UserAnswer = vbYes Then
        UniqueName = True
      ElseIf UserAnswer = vbNo Then
        Do
          ‘Retrieve New File Name
          ‘Получить новое имя файла
            FileName = InputBox(«Укажите новое имя файла » & _
             «(спросит снова, если вы указали недопустимое имя файла)», _
             «Введите имя файла», FileName)

                    ‘Exit if User Wants To
          ‘Выход, если пользователь хочет
            If FileName = «False» Or FileName = «» Then Exit Sub
        Loop While ValidFileName(FileName) = False
      Else
        Exit Sub ‘Cancel
      End If
    Else
      UniqueName = True
    End If
  Loop

  ‘Save As PDF Document
‘Сохранить как документ в формате PDF
  On Error GoTo ProblemSaving
    ActiveDocument.ExportAsFixedFormat _
     OutputFileName:=CurrentFolder & FileName & «.pdf», _
     ExportFormat:=wdExportFormatPDF
  On Error GoTo 0

‘Confirm Save To User
‘Подтвердить Сохранить пользователю
  With ActiveDocument
    FolderName = Mid(.Path, InStrRev(.Path, «») + 1, Len(.Path) — InStrRev(.Path, «»))
  End With

    ‘MsgBox «PDF Saved in the Folder: » & FolderName
  MsgBox «Файл pdf создан в указанную папку»

Exit Sub

‘Error Handlers
ProblemSaving:
  ‘MsgBox «There was a problem saving your PDF. This is most commonly caused» & _
   » by the original PDF file already being open.»
  MsgBox «Не удалось скопировать»
  Exit Sub

End Sub
Function ValidFileName(FileName As String) As Boolean
‘PURPOSE: Determine If A Given Word Document File Name Is Valid
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim TempPath As String
Dim doc As Document

‘Determine Folder Where Temporary Files Are Stored
  TempPath = Environ(«TEMP»)

‘Create a Temporary XLS file (XLS in case there are macros)
  On Error GoTo InvalidFileName
    Set doc = ActiveDocument.SaveAs2(ActiveDocument.TempPath & _
     «» & FileName & «.doc», wdFormatDocument)
  On Error Resume Next

‘Delete Temp File
  Kill doc.FullName

‘File Name is Valid
  ValidFileName = True

Exit Function

‘ERROR HANDLERS
InvalidFileName:
‘File Name is Invalid
  ValidFileName = False

End Function

[/vba]

Понравилась статья? Поделить с друзьями:
  • Word м?тіндік редакторы 3 сынып слайд
  • Word любой скачать бесплатно
  • Word ломаный скачать бесплатно
  • Word ломаный для андроид
  • Word логотип на каждой странице