Vba word сохранить как pdf

I have some code that copies and pastes data from an Excel file into a word document, how can I get that word document to save as a PDF?

My code is as follows:

Sub RetailerGraphs()

Dim Location As String
Dim Detail As String

Worksheets("-Summary").Activate
Range("AE9").Select
While ActiveCell.Value <> ""
    ActiveCell.Offset(1, 0).Select
    Location = ActiveCell.Value
    Worksheets("Detail Summary").Activate
    Range("B7").Value = Location

    Dim objWord, objDoc As Object
    ActiveWindow.View = xlNormalView
    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Add

    Range("AH40").Select
    While ActiveCell <> ""
        ActiveCell.Offset(1, 0).Select
        Detail = ActiveCell.Value
        Range("B11").Value = Detail 
        Application.Wait (Now + TimeValue("0:00:05"))
        Range("A1:Z111").CopyPicture Appearance:=xlScreen, Format:=xlPicture
        objWord.Visible = True
        objWord.Selection.Paste
        objWord.Selection.TypeParagraph
        Set objSelection = objWord.Selection
        objSelection.InsertBreak (wdPageBreak)
        If ActiveCell.Value = "END" Then
             objWord.SaveAs2 "C:DocsMyDoc.pdf"
        End If
    Wend
    Worksheets("-Summary").Activate
Wend

End Sub

Within the lines:

If ActiveCell.Value = "END" Then

End If

I have tried the following code to try to get it to save as a PDF:

 objWord.ExportAsFixedFormat OutputFileName:="C:wordtest.pdf", _
  ExportFormat:=wdExportFormatPDF

 objWord.ExportAsFixedFormat OutputFileName:="C:Documents and SettingsAll UsersDesktopYourFile.pdf", ExportFormat:=wdExportFormatPDF

 objDoc.ExportAsFixedFormat OutputFileName:="C:Documents and SettingsAll UsersDesktopYourFile.pdf", ExportFormat:=wdExportFormatPDF

But I get the error on the line where I try to export it as a PDF, e.g. objWord.SaveAs2 "C:DocsMyDoc.pdf" :

Run-time error '438':
Object doesn't support this property or method

Can someone please help?

Note: I have ensured that «Microsoft Word 14.0 Object Library» is ticked in the references, and I change the location to the necessary directory rather than using the above.

SaveAs

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

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

Create and SaveAs

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

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

SaveAs PDF

This macro will save the Word document as a PDF:

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

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

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

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

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

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


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

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

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

Sub CallSaveAsPDF()

    Call MacroSaveAsPDFwParameters("c:/Documents", "example.docx")
    
End Sub
1
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
title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Range.ExportAsFixedFormat method (Word)

vbawd10.chm157155831

vbawd10.chm157155831

word

Word.Range.ExportAsFixedFormat

d1cf9c7d-f2f3-1962-eccf-262568a56ad9

05/23/2019

medium

Range.ExportAsFixedFormat method (Word)

Saves a portion of a document as PDF or XPS format.

Syntax

expression.ExportAsFixedFormat (OutputFileName, ExportFormat, OpenAfterExport, OptimizeFor, ExportCurrentPage, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags, BitmapMissingFonts, UseISO19005_1, FixedFormatExtClassPtr)

expression An expression that returns a Range object.

Parameters

Name Required/Optional Data type Description
OutputFileName Required String The path and file name of the new PDF or XPS file.
ExportFormat Required WdExportFormat Specifies either PDF or XPS format.
OpenAfterExport Optional Boolean Opens the new file after exporting the contents.
OptimizeFor Optional WdExportOptimizeFor Specifies whether to optimize for screen or print.
ExportCurrentPage Optional Boolean Specifies whether to export the current page. True exports the entire page. False exports only the current selection.
Item Optional WdExportItem Specifies whether the export process includes text only or includes text with markup.
IncludeDocProps Optional Boolean Specifies whether to include document properties in the newly exported file.
KeepIRM Optional Boolean Specifies whether to copy IRM permissions to an XPS document if the source document has IRM protections. Default value is True.
CreateBookmarks Optional WdExportCreateBookmarks Specifies whether to export bookmarks and the type of bookmarks to export.
DocStructureTags Optional Boolean Specifies whether to include extra data to help screen readers, for example information about the flow and logical organization of the content. Default value is True.
BitmapMissingFonts Optional Boolean Specifies whether to include a bitmap of the text. Set this parameter to True when font licenses don’t permit a font to be embedded in the PDF file. If False, the font is referenced, and the viewer’s computer substitutes an appropriate font if the authored one is not available. Default value is True.
UseISO19005_1 Optional Boolean Specifies whether to limit PDF usage to the PDF subset standardized as ISO 19005-1. If True, the resulting files are more reliably self-contained but may be larger or show more visual artifacts due to the restrictions of the format. Default value is False.
FixedFormatExtClassPtr Optional Variant Specifies a pointer to an add-in that allows calls to an alternate implementation of code. The alternate implementation of code interprets the EMF and EMF+ page descriptions that are generated by the applications to make their own PDF or XPS. For more information, see Extend the fixed-format export feature in Word Automation Services.

Remarks

You can save as a PDF or XPS file from a Microsoft Office system program only after you install an add-in. For more information, see Save or convert to PDF or XPS.

[!includeSupport and feedback]

  • Remove From My Forums
  • Вопрос

  • Hi there
    I am working on a Excel (2010) using VBA where I am creating a MS word document and I want to save the document as  pdf is it possible?

    If so how can I do it
    Thanks for your help and assistance

Ответы

  • Are you using Automation to control Word from Excel? If so, I assume that you have a variable of type Word.Document (or Object if you use late binding) that refers to the document that you create. Let’s say you have named this variable objDoc.

    You can save the document as PDF as follows:

        objDoc.SaveAs2 "C:DocsMyDoc.pdf", 17

    17 is the value of the symbolic constant wdFormatPDF.

    If you haven’t created a variable for the document, but refer to the active document in the Word application object, say objWordApp:

        objWordApp.ActiveDocument.SaveAs2 "C:DocsMyDoc.pdf", 17


    Regards, Hans Vogelaar

    • Помечено в качестве ответа

      19 апреля 2012 г. 15:13

How To Save Word Document as PDF?

PDF refers to “Portable Document Format”.

In order to avoid copying or alteration of information by the third party or unauthorized user, We convert the word document to PDF. PDF files cannot be altered.

While sending the important files as a word document, there are chances that it get modified by other user. By converting the Docx to PDF you can avoid the document getting edited by anyone.

Now, here are few easy ways to covert Word to PDF format.

We will see them one by one.

1. Easy Steps to Convert MS Word Docx to PDF

It is the simplest way of converting a word document to PDF.

Converting Docx to PDF - using VBA to save word to PDF

Converting Docx to PDF – using VBA to save word to PDF
  • Open Word file to be converted to PDF.
  • Choose Save As option from file tab (or accessibility tab or using ALT+F+A)
  • Change “save As type into PDF(*PDF)
  • Select “Option” box.
  • Tick these ‘check boxes’ in additional options -> Non-Printing Information section.
    • Create Bookmarks using: Headings
    • Document properties
    • Document structure tags for accessibility
    • Click Continue.
  • Then click “OK”.

Now, Your Word document will be saved as a “PDF” file.

Note: If your create bookmarks with ‘heading’ not checked in, then your document will not have a perfect heading. Proper heading and alignment will be followed along with the page number if you follow the above steps correctly.

This will convert all pages in the docx file to PDF. This option is available only in the higher version of office like 2010, 2013, 2016 etc.,

Now, lets see how to do this a Vba code.

2. VBA Code to Save Word as PDF

This vba code is written to run as Word document. From the word document that needs to be converted to PDF, press Alt + F11, then copy paste the bwlo code.

In case if you would like to automate this process from Excel or Outlook, then an object for word.application has to be created first. Then the use the PDF export function, so that word can be accessed using that object.

Sub ConvertWordDocxToPDF()
    'Code from Officetricks
    'Define variable fields
    Dim sFolderPath As String
    Dim sFileName As String
    Dim sNewFileName As String
    
    'Check if Folder Exists
    sFolderPath = ActiveDocument.Path & ""
    
    'Set New File Name
    sFileName = ActiveDocument.Name
    sNewFileName = VBA.Mid(sFileName, 1, VBA.InStrRev(sFileName, ".", , vbTextCompare) - 1)
    sNewFileName = sFolderPath & sNewFileName & ".pdf"
    
    'Save File
    ActiveDocument.ExportAsFixedFormat OutputFileName:=sNewFileName, _
        ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
        wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
        Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False
End Sub

Run the code by pressing F5. It will export the current Word document to a PDF file with the new name given in the code.

Related topic: Convert Excel to PDF

We could use this conversion from word to pdf to save the intermediate work we do while editing a word document or while reviewing for any quality.

3. Convert Word File to PDF – Using Adobe

The other method for creating the PDF file of your word document is using Adobe Acrobat Professional. Adobe Acrobat Professional version 10 or above are suitable for converting document created with Microsoft word 2010 in PDF.

If you have already installed this version of Adobe Acrobat, along with plug in for Word, then the acrobat tab will appear in the word document itself. When you open the tab you will find the options under “Acrobat tab”. You will see a Create PDF icon & a Preferences icon in the Create.

3.1 Adobe PDF Group

3.1.1. Settings Tab:

In the “Settings tab” first configure the settings that are needed to convert the word to PDF file. Click preferences to open the, Acrobat PDF Maker dialog.

  • Then, in the Application Settings section of the Settings tab, make sure that below three check boxes are ,checked:
    • Create Bookmarks,
    • Add Links, and
    • Enable Accessibility and Reflow with tagged Adobe PDF.
  • Make sure the Prompt for Adobe PDF file name check box is checked in, leave the other tab(s) unaltered (even you can add password to the document in the same settings tab else you can leave it as it is).

3.1.2. Word Tab:

On the Word tab, make sure the following check boxes are checked:

  • Convert footnote and end note links.
  • Enable advanced tagging.

3.1.3. Bookmarks Tab:

  • Make sure the Convert Word Headings to Bookmarks check box is checked, and make sure all of the heading levels are selected in the element list.
  • Save the Preferences, once you have completed your selections, click the OK button to save your preferences and exit the PDF Maker dialog.

Configuration is completed. Now start Converting Word to PDF.

3.2 Word to PDF Conversion Steps

If you selected the option to prompt for Adobe PDF file name in the preferences,

  1. you will see a dialog titled “Save Adobe PDF File As,” where you can specify a new file name & location.
  2. In that case, update the file name and click save to finish.
  3. While the file is being processed, a status dialog will display briefly, but because the process happens so quickly, it may disappear as quickly as it appeared.
  4. Finally, if you selected the option to View the PDF result in your preferences, the new PDF file displayed.

You can also use online converters to convert the documents. Some of the free online editors are available in online you can use those things to convert.

External Reference: Discussion on saving Word Doc to PDF

What This VBA Macro Code Does

The business world has increasingly become more reliant on mobile computing with devices such as tablets and smartphones becoming mainstream. This, in turn, has provided an elevated demand for analysts to turn spreadsheets into PDF documents so management can view your reports on the go. 

Below is a simple VBA macro that will allow you to quickly turn your Microsoft Word Document into a PDF file in a snap. The code is written to save your PDF in the same folder as the Word Document file currently resides. If you need to make modifications, hopefully, you will be able to follow along with my code comments and customize the code to your specific needs.

Sub Word_ExportPDF()
‘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
  myPath = ActiveDocument.FullName
  CurrentFolder = ActiveDocument.Path & «»
  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(«File Already Exists! Click » & _
       «[Yes] to override. Click [No] to Rename.», vbYesNoCancel)

            If UserAnswer = vbYes Then
        UniqueName = True
      ElseIf UserAnswer = vbNo Then
        Do
          ‘Retrieve New File Name
            FileName = InputBox(«Provide New File Name » & _
             «(will ask again if you provide an invalid file name)», _
             «Enter File Name», 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
  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

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.»
  Exit Sub

End Sub

Function To Validate Save File Name

Below is a function that you will need to paste in along with the above macro. The VBA function provides a way of testing any file name your users provide to save the PDF document as.

Same Macro Functionality For Other Office Applications

Upon request, I have made similar macros for other Office Applications you may use on a regular basis to convert their files into PDF documents. The links to those specific posts are as follows:

Microsoft Excel Version

Microsoft PowerPoint Version

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris
Founder, TheSpreadsheetGuru.com

Like this post? Please share to your friends:
  • Vba word сохранить все
  • Vba word создать папку
  • Vba word создание таблиц
  • Vba word случайное число
  • Vba word скопировать весь текст