Vba excel all pdf

Home/ VBA/ Export All Sheets to PDF – Excel VBA

This tutorial looks at how you can create a macro in Excel to export all sheets to PDF. Each sheet of the workbook will be saved into the same folder. The name of the worksheet will be used as the filename of the PDF.

By creating a macro this seemingly repetitive task can be performed at the click of a button.

Although all sheets are used in this example. The macro can be adapted to include all except the first sheet, or some other variation.

The code below can be copied into a VBA module and adapted to your needs. An explanation for the main parts of the code can be found below.

Sub ExportAsPDF()
Dim FolderPath as string
Dim I as Integer
FolderPath = "C:UsersComputergagaDesktopPDFs"
MkDir FolderPath
For i = 1 To Worksheets.Count
Worksheets(i).ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & "" & _
Worksheets(i).Name, openafterpublish:=False
Next
MsgBox "All PDF's have been successfully exported."
End Sub

The MkDir function has been used to create a directory (folder) on the Desktop. This folder is then used as the destination for the export.

The ExportAsFixedFormat method of the Worksheets object is the key to this macro. This method allows you to export the active sheet to a specified format.

The ExportAsFixedFormat method accepts a variety of arguments. The code in this tutorial uses the following;

Type: This is to specify that the sheets are to be exported in PDF format.

Filename: The files are saved to the directory that was created using the MkDir function. They are saved under the worksheet names.

OpenAfterPublish: This is set to False so that the files are not opened when the macro is complete.

The code is wrapped in a For loop to export each sheet as a separate PDF. The loop is set to start from the first sheet and export all sheets to PDF.

The start and end point of the loop can be adjusted if there is a specific range of sheets that you wish to export.

More Useful Excel VBA Tutorials

Macro to export multiple sheets to a single PDF
Excel VBA Evaluate function
A Beginners guide to For Loops
5 ways to use the Immediate window

Reader Interactions

VBA Loop Through PDF Files in a Folder using built-in Dir() function. In this tutorial we loop through a folder or directory and list all available .PDF files in a folder. Lets learn how to use Dir, Right and Len VBA functions in this tutorial.

Example to find all .PDF files in a directory using Excel VBA

Let us see the example macro to loop through all .PDF files in a folder using Excel VBA. The output is displays in the immediate window. We are using Dir function to access all available files in a folder. Right function is used to check ‘’ is added or not to file path and PDF is available in file name or not. And finally Len function is used to check file length.

'VBA Loop Through .pdf files in a given Folder
Sub VBAF1_List_All_PDF_Files_Using_Dir()
    
    'Variable Declaration
    Dim sFilePath As String
    Dim sFileName As String
    
    'Specify File Path
    sFilePath = "C:Test"
    
    'Check for back slash
    If Right(sFilePath, 1) <> "" Then
        sFilePath = sFilePath & ""
    End If
        
    sFileName = Dir(sFilePath & "*.pdf")
    
    Do While Len(sFileName) > 0
        If Right(sFileName, 3) = "pdf" Then
            'Display file name in immediate window
            Debug.Print sFileName
            
        End If
        'Set the fileName to the next available file
        sFileName = Dir
    Loop
   
End Sub

Output: Here is the output screenshot of above macro.

VBA Loop Through PDF Files in a Folder Example

VBA Loop Through PDF Files in a Folder Example

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

I’m trying to open all appropriate PDFs found in the same directory as my Excel workbook using VBA. I’ve added the Adobe Acrobat xx.x Type Library reference to the project. But when I try to create the .App object I get a «Run-time error ‘429’:» error.

What am I missing?

Here’s the code;

Sub ImportNames()
Dim BlrInfoFileList() As String, NbrOfFiles As Integer, FileNameStr As String
Dim X As Integer, pdfApp As AcroApp, pdfDoc As AcroAVDoc


'Find all of the Contact Information PDFs
FileNameStr = Dir(ThisWorkbook.Path & "*Contact Information.pdf")
NbrOfFiles = 0
Do Until FileNameStr = ""
    NbrOfFiles = NbrOfFiles + 1
    ReDim Preserve BlrInfoFileList(NbrOfFiles)
    BlrInfoFileList(NbrOfFiles) = FileNameStr
    FileNameStr = Dir()
Loop

For X = 1 To NbrOfFiles
    FileNameStr = ThisWorkbook.Path & "" & BlrInfoFileList(X)
    Set pdfApp = CreateObject("AcroExch.App")
    pdfApp.Hide

    Set pdfDoc = CreateObject("AcroExch.AVDoc")
    pdfDoc.Open FileNameStr, vbNormalFocus

    SendKeys ("^a")
    SendKeys ("^c")
    SendKeys "%{F4}"

    ThisWorkbook.Sheets("Raw Data").Range("A1").Select
    SendKeys ("^v")
    Set pdfApp = Nothing
    Set pdfDoc = Nothing

    'Process Raw Data and Clear the sheet for the next PDF Document
Next X
End Sub

Pᴇʜ's user avatar

Pᴇʜ

56k9 gold badges49 silver badges73 bronze badges

asked Oct 4, 2013 at 15:36

user2668956's user avatar

If it’s a matter of just opening PDF to send some keys to it then why not try this

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:MyFile.pdf"
End Sub

I am assuming that you have some pdf reader installed.

answered Oct 4, 2013 at 15:54

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

1

Use Shell "program file path file path you want to open".

Example:

Shell "c:windowssystem32mspaint.exe c:usersadminx.jpg"

Bugs's user avatar

Bugs

4,4919 gold badges32 silver badges41 bronze badges

answered Mar 16, 2014 at 7:48

Cyaramar's user avatar

Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .

Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook

Application.ScreenUpdating = False

Set Basebk = ThisWorkbook

' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & ""
mFolder = diaFolder.SelectedItems(1) & ""
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & ""
Filename = Dir(subFldr & "*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
   Workbooks.Open Filename:=subFldr & "" & Filename, ReadOnly:=True
   For Each Sheet In ActiveWorkbook.Sheets
   Set Actbk = ActiveWorkbook
   s = ActiveWorkbook.Name
   HK = Left(s, Len(s) - 4)
   If InStrRev(HK, "_S") <> 0 Then
   HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
   Else
   HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
   End If
   Sheet.Copy After:=ThisWorkbook.Sheets(1)
   ActiveSheet.Name = HK

   ' Open pdf file to copy SIC Decsription
   pathAndFileName = subFlodr & J
   adobeReaderPath = "C:Program Files (x86)AdobeAcrobat Reader DCReaderAcroRd32.exe"
   shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
   Call Shell( _
    pathname:=shellPathName, _
    windowstyle:=vbNormalFocus)
    Application.Wait Now + TimeValue("0:00:2")

    SendKeys "%vpc"
    SendKeys "^a", True
    Application.Wait Now + TimeValue("00:00:2")

    ' send key to copy
     SendKeys "^c"
    ' wait 2 secs
     Application.Wait Now + TimeValue("00:00:2")
      ' activate this workook and paste the data
        ThisWorkbook.Activate
        Set ws = ThisWorkbook.Sheets(HK)
        Range("O1:O5").Select
        ws.Paste

        Application.Wait Now + TimeValue("00:00:3")
        Application.CutCopyMode = False
        Application.Wait Now + TimeValue("00:00:3")
       Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
       ' send key to close pdf file
        SendKeys "^q"
       Application.Wait Now + TimeValue("00:00:3")
 Next Sheet
 Workbooks(Filename).Close SaveAs = True
 Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub

I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement

Regards,
Hema Kasturi

answered Nov 17, 2017 at 17:57

user8959244's user avatar

WOW…
In appreciation, I add a bit of code that I use to find the path to ADOBE

Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _
    (ByVal lpFile As String, _
     ByVal lpDirectory As String, _
     ByVal lpResult As String) As Long

and call this to find the applicable program name

Public Function GetFileAssociation(ByVal sFilepath As String) As String
Dim i               As Long
Dim E               As String
    GetFileAssociation = "File not found!"
    If Dir(sFilepath) = vbNullString Or sFilepath = vbNullString Then Exit Function
    GetFileAssociation = "No association found!"
    E = String(260, Chr(0))
    i = FindExecutable(sFilepath, vbNullString, E)
    If i > 32 Then GetFileAssociation = Left(E, InStr(E, Chr(0)) - 1)
End Function

Thank you for your code, which isn’t EXACTLY what I wanted, but can be adapted for me.

answered Sep 12, 2018 at 23:48

Ian Hicks's user avatar

1

Here is a simplified version of this script to copy a pdf into a XL file.


Sub CopyOnePDFtoExcel()

    Dim ws As Worksheet
    Dim PDF_path As String

    PDF_path = "C:Users...DocumentsThis-File.pdf"


    'open the pdf file
    ActiveWorkbook.FollowHyperlink PDF_path

    SendKeys "^a", True
    SendKeys "^c"

    Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)

    Application.ScreenUpdating = False

    Set ws = ThisWorkbook.Sheets("Sheet1")

    ws.Activate
    ws.Range("A1").ClearContents
    ws.Range("A1").Select
    ws.Paste

    Application.ScreenUpdating = True

End Sub

answered Jul 12, 2019 at 16:13

Keith Swerling's user avatar

Содержание

  1. Vba excel all pdf
  2. Export All Sheets to PDF – Excel VBA
  3. More Useful Excel VBA Tutorials
  4. Related Posts:
  5. Reader Interactions
  6. Comments

Vba excel all pdf

Несмотря на мощные функциональные возможности, обеспечиваемые пользовательским интерфейсом Excel, существует ряд задач, выполнение которых возможно только программным путем. Книга «Использование макросов в Excel” представляет собой введение в программирование на Excel VBA, содержащее примеры решения различных практических задач, возникающих при работе в Excel. Материал книги рассчитан на пользователей Excel, а также программистов, которые не знакомых с объектной моделью Excel. Наряду с разделами, посвященными разработке макросов для Excel 2002, здесь излагается вводный курс по написанию макросов и программ в среде Excel.

Книга: Интенсивный курс программирования в Excel за выходные
Автор: П. Эйткен
Издательство: Диалектика
Страниц: 421
Формат: DJVU
Размер: 12.6 Мб
Качество: Нормальное
Язык: Русский
Жанр: программирование
Год издания: 2004
ISBN: 5-8459-0687-3

Возможности Microsoft Excel не ограничиваются только работой с таблицами данных. За средствами обработки электронных таблиц прячется сильный язык программирования — VBA (Visual Basic for Applications). Впрочем, практически хоть какой юзер имеет возможность выучиться писать программы на языке VBA для решения самых разнородных задач в Excel — от механического исполнения вычислений до создания системы для ввода данных с собственными экранными формами и с вероятностью ревизии корректности набираемых значений.

Книга: Программирование на VBA 2002
Автор: В.Г. Кузьменко
Качество: Нормальное
Язык: Русский
Жанр: программирование

В книге содержится курс по программированию на Visual Basic for Applications (VBA), являющимся базовым языком в приложениях Microsoft Office (Word, Excel, Access, PowerPoint, FrontPage, Visio и др.). Книга предназначена для начинающих программировать в среде Windows с применением Word-, Excel-, PowerPoint-объектов. Часть книги посвящена вопросам разработки Office-приложений, использующих базы данных, хранимых как в отдельных файлах, так и на удаленных серверах. Материала книги достаточно для изучения основ языка Visual Basic и создания простых макросов, помогающих автоматизировать рутинную повторяющуюся работу с документами, электронными таблицами, диаграммами, презентациями и т.д., а также для разработки довольно сложных приложений обработки баз данных с использованием диалоговых окон, обеспечивающих пользователя самыми современными интерфейсными средствами. Большинство примеров в книге посвящены актуальным в настоящее время вопросам коммерческой деятельности, поэтому книга будет очень полезной менеджерам различных уровней, которым, по-видимому, и предназначен как Microsoft Office, так и встроенный язык программирования VBA.
Приложения в конце книги могут послужить удобным справочником при работе как с VBA, так и с обычным VB.

Книга: Профессиональное программирование на VBA в Excel 2003
Автор: Джон Уокенбах
Издательство: Вильямс
Формат: PDF
Размер: 11 Мб
Качество: Отличное
Язык: Русский
Год издания: 2005
ISBN: 5-8459-0771-3
К книге прилагается диск

По Excel написано немало книг. Но эта книга является особенной — в ней разработка приложений электронных таблиц рассматривается в широком контексте. VBA — это всего лишь один из компонентов среды разработки пользовательских приложений, хотя и довольно существенный. Данная книга поможет вам разобраться в тонкостях разработки приложений с помощью VBA. В ней описаны многочисленные средства языка VBA, его возможности и среда использования.Вначале Вашему вниманию будет предложен обзор возможностей программы, далее Вы перейдете к определению концепций VBA-программирования, а затем познакомитесь с самим языком. Если вы начинающий программист на VBA, то в данном издании найдете всю необходимую информацию, которая потребуется для дальнейшей работы. если Вы уже обладаете завидным опытом работы с VBA, то эта книга обогатит и приумножит Ваши знания, пополнив их новыми методиками и примерами из реальной жизни.

Pdf-версия отредактирована и любезно предоставлена участником Alex_ST.

Книга: : Профессиональное программирование на VBA в Excel 2010
Автор: Джон Уокенбах
Издательство: Wiley
Формат: PDF
Страниц: 1308
Размер: 11,9 Мб
Качество: Отличное
Язык: Английский
Год издания: 2010

This book focuses on Visual Basic for Applications (VBA), the programming language built into Excel (and other applications that make up Microsoft Office). More specifically, it will show you how to write programs that automate various tasks in Excel. This book covers everything from recording simple macros through creating sophisticated user-oriented applications and utilities. This book does not cover Microsoft Visual Studio Tools for Office (VSTO). VSTO is a relatively new technology that uses Visual Basic .NET and Microsoft Visual C#. VSTO can also be used to control Excel and other Microsoft Office applications.
This is not a book for beginning Excel users. If you have no experience with Excel, a better choice might be Excel 2010 Bible, which provides comprehensive coverage of all the features of Excel. That book is meant for users of all levels.

Книга: : Профессиональное программирование на VBA в Excel 2010
Автор: Джон Уокенбах
Издательство: Диалектика
Формат: PDF
Страниц: 920
Размер: 22,1 Мб
Качество: Отличное
Язык: Русский
Год издания: 2010

Предмет рассмотрения этой книги — язык программирования Visual Basic for Applications (VBA), который встроен в Excel, а также в другие приложения, входящие в состав Microsoft Office. Здесь подробно описано создание программ, автоматизирую­щих выполнение различных задач в Excel, а также рассматривается широкий круг других тем — от написания простейших макросов до создания сложнейших приложений и ути­лит, рассчитанных на взаимодействие с пользователем. В этой книге нет описания программного пакета Microsoft Visual Studio Tools for Office (VSTO). Он представляет собой воплощение относительно новой технологии, ис­пользующей Visual Basic .NET и Microsoft Visual С#. Технология VSTO также может применяться для управления поведением программы Excel и других приложений Microsoft Office.

Книга не предназначена для начинающих пользователей Excel. Если у вас нет опыта работы с этим приложением, то прочтите сначала книгу Excel 2010. Библия пользо­вателя, в которой подробно рассказывается обо всех возможностях Excel (она адресована пользователям всех уровней).


Книга: Самоучитель VBA
Автор: Гарнаев А.
Издательство: bhv
Страниц: 512
Формат: html с картинками в rar
ISBN: 5-8206-0067-3
Размер: 2,22 Мб

Настоящая книга является с одной стороны, подробным справочником по Visual Basic for Applications (VBA), а с другой стороны, самоучителем по составлению и разработке приложений, написанных на этом языке. Это уникальное сочетание, которое, следуя рекламному подходу, можно назвать «два в одном», обеспечивает большую гибкость при решении читателем своих собственных задач. Самоучитель на большом количестве примеров умело и доступно обучает, как можно быстро и эффективно решать разнообразные задачи. В справочнике приводится подробное описание возможностей VBA, имея такие сведения под рукой у читателя исчезнет необходимость бегать по магазинам в поиске дополнительной литературы при написании самостоятельных приложений, что несомненно сбережет время и кошелек.

Microsoft Excel is much more than just a spreadsheet. With the introduction of the Visual Basic Editor in Excel 97, followed by the significantly improved stability of Excel 2000, Excel became a respected development platform in its own right. Excel applications are now found alongside those based on C++, Java, and the .NET development platform, as part of the core suite of mission-critical corporate applications.
Unfortunately, Excel is still too often thought of as a hobbyist platform, that people only develop Excel applications in their spare time to automate minor tasks. A brief look at many Excel VBA books seems to confirm this opinion. These books focus on the basics of automating Excel tasks using VBA. This book is the first of its kind in providing a detailed explanation of how to use Excel as the platform for developing professional quality applications.
While most other major development platforms seem to have a de facto standard text that explains the commonly agreed best practices for architecting, designing, and developing applications using that platform, until now Excel has not. This book attempts to fill that gap. The authors are professional Excel developers who create Excel-based applications for clients ranging from individuals to the largest multinational corporations. This book explains the approaches we use when designing, developing, distributing, and supporting the applications we write for our clients.

Источник

Export All Sheets to PDF – Excel VBA

This tutorial looks at how you can create a macro in Excel to export all sheets to PDF. Each sheet of the workbook will be saved into the same folder. The name of the worksheet will be used as the filename of the PDF.

By creating a macro this seemingly repetitive task can be performed at the click of a button.

Although all sheets are used in this example. The macro can be adapted to include all except the first sheet, or some other variation.

The code below can be copied into a VBA module and adapted to your needs. An explanation for the main parts of the code can be found below.

The MkDir function has been used to create a directory (folder) on the Desktop. This folder is then used as the destination for the export.

The ExportAsFixedFormat method of the Worksheets object is the key to this macro. This method allows you to export the active sheet to a specified format.

The ExportAsFixedFormat method accepts a variety of arguments. The code in this tutorial uses the following;

Type: This is to specify that the sheets are to be exported in PDF format.

Filename: The files are saved to the directory that was created using the MkDir function. They are saved under the worksheet names.

OpenAfterPublish: This is set to False so that the files are not opened when the macro is complete.

The code is wrapped in a For loop to export each sheet as a separate PDF. The loop is set to start from the first sheet and export all sheets to PDF.

The start and end point of the loop can be adjusted if there is a specific range of sheets that you wish to export.

More Useful Excel VBA Tutorials

Reader Interactions

Hi Alan, When I try and run the code, I get a run-time error 75
Path/File access error?

Hi Chris,
This sounds like a problem with the line below.
FolderPath = “C:UsersComputergagaDesktopPDFs”
You will need to adjust the Folderpath to match your own system. For example Computergaga would be your username.
If you have already personalised this to your setup then the other possible reason is that you have run the macro more than once and the folder already exists.
Alan

I have an excel sheet that I need to produce the PDF file but I need it not to overwrite the one this code creates. Every time I hit the pdf button to create another one it replace the previous one. How would I get it to create a new one each time. I do have it saving with the work order number right now and that would be great if I can save the pdf with the work order number also. My form automatically generates a new number using the (+1) so it would go from 100 to 101 and so-on as I save the files. I would like to do that with pdf also. Here is the excel code used to create the excel sheets ——– Range(“K1”).Value = Range(“K1”).Value + 1

You should be able to concatenate the Range(“K1”).value onto the filename code in the ExportAsFixedFormat method. You are pretty much there. Just concatenate what you have on the end and this should be a new PDF each time.

Hi, how to make every time the pdf save,the old one would not be overwrite by the new one and the name will be in sequence?

You will need to find the old version of the PDF in the list. Then add 1 onto the old version number. If this is at the end the RIGHT function can locate it. Add 1 on top and concatenate them back together and save.

Hi there,
It was superb tutorial but I want to change it according to my needs and your help will be appreciated.
I want to collect some data from text box and combo box on vba form and then by pressing a button, i should be able to save selected data to a PDF file in xyz directory.
Many thanks
Regards,
Saif

Hi,
Thank you for your contributuion. It reallyhelped me in solving my needs.
But I have a question, the code which you provided to me I have to go in visual basic and rewrite it again and again whenever I want to create a new excel file.
How can I have the code present in the excel file whenever a new excel sheets is exported from a system?
Also, is there any other way to run and convert the files to PDF without going to visual basic?
Thanks,
Daljit Rahsi

If the macro is in the Personal Macro Workbook it will be available to any Excel file you need it to. As long as the macro is written generally and not referring to sheets or files by name it should work at any time.
No you need a macro unless there is some third party software that can also achieve it.

Hi, really appreciate your video tutorials on youtube, my vb skills are slim to none.
Can you give me an example, say i have 3 worksheets and i want to just export 1 sheet called “graphs”, so not all of them. Where do i put this in your code?

You would not need the loop through each sheet or the variable for the sheet. You could simply open it using worksheets(“graphs”).open
This would happen before the export. The rest of the code would be the same

Thanks alot for taking time out to reply, very helpful, much appreciated.

keep up the good work, great stuff! 🙂

This works great for what I want but I wondered if I can add additional variables? I have designated the sheet range (30 to 67) but within that range I would also like it to only convert to pdf, sheets with the word PRINT in cell F3
This is such a time saver! Thanks again

Looping through sheets 30 to 67 can be done with a simply For Next loop like below.
For i = 30 to 67
sheets(i).activate
next
The PDF export code from the video would be put within an IF statement to make it conditional like below.
If Range(“F3”).value = “PRINT” then
code to export to pdf
End If

Worked perfectly! Thanks

Hi Alan,
I am getting a error ‘1004’? how to get rid of it.
Please advise.
Thanks,
Subhranil

Hi Subhranil,
You could use the F8 key to step through the code line by line. At the point that it fails should help you identify the error.
Check the code again with the video also. It is very hard to tell without seeing what you have.
Alan

Hi alan,
How would I be able to modify this to only select a specific named worksheet in this code but still batch exporting from a specific file folder? I am very new to VBA and dont know too much but your videos have helped Tremendously.

This blog post shows you how to loop through the files of a folder and open one.
http://www.computergaga.com/blog/loop-through-all-files-in-a-folder-using-vba/
This code can be adapted to then export a specific sheet in each file by using the PDF code.

Hi Alan,
How to convert to PDF first three sheets repeating and fourth with fourth name as file name, first three and fifth with fifth name as file name etc….

Yes you can set the loop as For 1 to 3 rather then For 1 to worksheet.count.
You will then need an exterior loop for your fourth, fifth and however many more sheets you have. Using sheet names as file names is shown in the code. its all about this exterior loop.

Hi Alan,
Thanks for the update, i don’t have any idea about the coding or macro, i tried the above code, but it getting one sheet one PDF. please help me with code. My work book has 8 sheets, Sheet1, Sheet2,Sheet3,Employee1,Employee2…..Employee5.
I need to genertae Employee1.pdf, with Sheet1,Sheet2,Sheet3 and Employee1, then another PDF for Employee2 with Sheet1,Sheet2,Sheet3 and Employee2. Please help me, now i am doing manually each sheet and save as PDF.

Hi Biji,
This should work. You will need to copy it into a module and teak the folder path to your liking.
Sub ExportAsPDF()
Dim FolderPath As String
Dim EmpSheets As Byte
FolderPath = “C:UsersTrainee1DesktopPDFs”
MkDir FolderPath
For EmpSheets = 4 To 8
Sheets(Array(1, 2, 3, EmpSheets)).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & “” & _
Worksheets(EmpSheets).Name, openafterpublish:=False, ignoreprintareas:=False
Next
MsgBox “All PDF’s have been successfully exported.”
End Sub

Hi Alan,
sorry for the delay, i was on vocation. I tried and it worked nice, thank you very much for you help. Best wishes…..

I am trying to make the sheets 1 to 4 and it’s not working..any suggestions?

Change the worksheets.count bit to 4. So it will read For I = 1 to 4.

Hello! Great tutorial 🙂
I have one question, maybe you can help me out with this.
I need to export only the same 4 sheets in order into the same PDF (from sh 4 to 8, from the same workbook).
I tried to use what you answered to the user “Biji” but still couldn’t do it.
If you have some spare time, I would appreciate your help.
THANKS!

Hi Guzman,
The video link below will show you how to export multiple sheets to a single PDF.
https://youtu.be/BlzZdWco3bs
Alan

Instant reply! Your web has been added to favorites!
Thanks 🙂

Suscribed to you YouTube Channel as well 🙂
PS. I didn’t get any email notification of your answer. Don’t know what happened, by chance I enter the site again.

Hi ! Maybe you can help me with this. I’m trying to: loop through a folder of excel files, and export as PDF, sheets 2 to 5 of each file, the name of the PDF is located in Cells(1,1) of Sheet 1.
Sub export_PDF_Test()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ruta = ThisWorkbook.Path & “”
archivo = Dir(ruta & “*.xlsx”)
RutaCompleta = ruta & archivo
Do While archivo “”
Set l2 = Workbooks.Open(RutaCompleta)
l2.Sheets(Array(2, 3, 4, 5)).Select
*** code: to export as PDF (exportasfixedformat) *** .
l2.Close True
archivo = Dir()
Loop
I have tried many things but always get an error.
Thanks for the help!

Hi Guzman,
You want to combine the code you have showing how to loop through files in a folder with the code you have from the blog post below.
This shows you how to export to PDF. You seem to have the array sorted and using the cells(1,1).value as the PDF name.
Alan

Hi Alan!!
I don’t know why I’m not receiving notifications of your reply.
Silly me .
I was coding in Thisworkbook module and was always exporting thisworkbook.activesheet
Now I’ve inserted a module and code the following and apparently is working.
***
Do While archivo “”
Set l2 = Workbooks.Open(RutaCompleta)
l2.Activate
l2.Sheets(Array(2, 3, 4, 5)).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ruta & archivo
l2.Close True
Debug.Print archivo & ” archivo”
archivo = Dir()
Loop
***
I still have to add to take the name from A1, but that’s easy 😉
THANKS .

Hi Alan, to make clearer my solution I posted here again (in the reply section looks so small).
To loop through a folder of excel files and export as PDF, sheets 2 to 5 of each file.
I`ve reached to the following:
***
Sub export_PDF()
Application.ScreenUpdating = True
Application.DisplayAlerts = True
ruta = ThisWorkbook.Path & “”
archivo = Dir(ruta & “*.xlsx”)
RutaCompleta = ruta & archivo
Do While archivo “”
Set l2 = Workbooks.Open(RutaCompleta)
l2.Activate
l2.Sheets(Array(2, 3, 4, 5)).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ruta & archivo
l2.Close True
Debug.Print archivo & ” archivo”
archivo = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
***
Sorry that I didn’t declare the variables.

Probably this code should be adjusted so the sheets to export is not a fixed number, but a variable.

Источник

Excel VBA Tutorial about to save file as PDFPower Spreadsheets focuses on Microsoft Excel.

However, I’ve written several tutorials (such as here and here) that have to do with PDF and, more particularly, with the topic of converting PDF files to Excel.

The reason why I write about PDF is relatively straightforward: PDF is one of the most widely used file formats.

This particular Excel tutorial also focuses on the topic of working with Excel and PDF files. More precisely, I explain in detail how you can save Excel files as PDF using VBA, and provide 10 examples of VBA code that you can start using immediately.

In fact, in this blog post, I go much further than simply showing you how to simply convert Excel files to PDF. Among others, I also:

  • Provide a thorough introduction to how you can use Visual Basic for Applications for purposes of adjusting the page setup attributes.
  • Introduce some different ways in which you can specify the filename of the PDF file that results after the Excel to PDF conversion.
  • Explain how you can save each worksheet from an Excel workbook in a separate PDF file.

The following table of contents lists the different sections of this blog post.

This Excel VBA Save as PDF Tutorial is accompanied by files containing the data and macros I use in the examples below. You can get immediate free access to these example files by clicking the button below.

Get immediate free access to the Excel VBA Save as PDF file examples

The basic VBA method you use for converting Excel files to PDF is ExportAsFixedFormat. Therefore, let’s start this blog post by taking a look at it:

How To Save An Excel File As PDF Using VBA: The ExportAsFixedFormat Method

The main purpose of the ExportAsFixedFormat method is to export a particular Excel object (such as a file, worksheet, cell range or chart) to another file format, usually PDF.

You can apply the ExportAsFixedFormat method to several Excel objects. To be more precise, you’ll generally be working with 1 of the following versions of this method, depending on which particular object you want to save as PDF.

  • The Workbook.ExportAsFixedFormat method, when saving an Excel workbook as PDF.
  • The Worksheet.ExportAsFixedFormat method, if you’re saving a worksheet as PDF.
  • The Range.ExportAsFixedFormat method, when working with a Range object.
  • The Chart.ExportAsFixedFormat method, if saving a chart as PDF.

The basic syntax of the ExportAsFixedFormat method is generally as follows:

expression.ExportAsFixedFormat (Type, Filename, Quality, IncludeDocProperties, IgnorePrintAreas, From, To, OpenAfterPublish)

For these purposes, “expression” is a variable representing a Workbook, Worksheet, Chart or Range object, depending on the particular version of the method you’re working with. In other words, “expression” is the placeholder for the object that you want to actually save as PDF.

This particular VBA method has 9 different parameters. Let’s take a look at each of them:

Parameter #1: Type

You use the Type parameter to specify the type of file format to which the Excel file must be exported to. In other words, you determine in which file format the new (resulting) file is saved by specifying it in the Type parameter.

In order to specify the type of file you want to convert the Excel file to, you use the xlFixedFormatType enumeration. There are 2 types of file formats you can choose from:

  • File Type #1: xlTypePDF, represented by the value of 0. xlTypePDF corresponds to PDF files, the subject of this Excel tutorial.
  • File Type #2: xlTypeXPS, whose value is 1. xlTypeXPS corresponds to XPS files, Microsoft’s alternative to PDF.

The purpose of this Excel tutorial is to explain how you can use Visual Basic for Applications to save an Excel file as PDF. Therefore, whenever using the Type parameter in this blog post, I only use xlTypePDF.

Furthermore, XPS never seemed to gain much traction. Therefore, you’re unlikely to encounter (or have to work with) many XPS files.

Type is the only required parameter of the ExportAsFixedFormat method.

Parameter #2: Filename

As implied by its name, you use the Filename parameter of the ExportAsFixedFormat method for purposes of specifying the filename of the new (converted) file.

When specifying the Filename parameter, you have 2 broad options:

  • Option #1: You can specify the full path and filename of the resulting file.
  • Option #2: You can omit the full file path and, instead, just include the filename. In this case, Excel simply saves the converted file in the current default folder.

Filename is a string.

Parameter #3: Quality

You have the option of choosing the quality of the resulting PDF file (standard or minimum).

For these purposes, you use the Quality parameter of the ExportAsFixedFormat method. More precisely, you can choose 1 of the 2 xlFixedFormatQuality options:

  • Quality Option #1: xlQualityStandard, whose value is 0. This is, simply, standard file quality.
  • Quality Option #2: xlQualityMinimum (value is 0). This represents minimum file quality.

Parameter #4: IncludeDocProperties

The IncludeDocProperties parameter of the ExportAsFixedFormat method allows you to determine whether the document properties are included in the converted PDF file or not.

To make this choice, you simply need to set the IncludeDocProperties parameter to True or False as follows:

  • True: Includes the document properties.
  • False: Doesn’t include the document properties.

Parameter #5: IgnorePrintAreas

By using the IgnorePrintAreas parameter of the ExportAsFixedFormat method, you can specify whether Visual Basic for Applications should ignore (or not) the print areas that have been set for the relevant Excel file.

To specify whether the print areas should (or shouldn’t) be ignored, set the IgnorePrintAreas parameter to True or False as follows:

  • True: Ignore print areas.
  • False: Don’t ignore print areas.

Parameters #6 And #7: From And To

The From and To parameters of the ExportAsFixedFormat method allow you to specify the pages at which the publishing to PDF should begin and end. More precisely:

  • From is the number of the page at which Visual Basic for Applications starts to publish. If the From argument is omitted, VBA starts at the beginning.
  • To is the number of the last page that VBA publishes. If you omit the To argument, publishing goes on until the last page.

Parameter #8: OpenAfterPublish

By using the OpenAfterPublish parameter of the ExportAsFixedFormat method, you can determine whether the converted PDF file should be displayed in the PDF viewer as soon as the export process is completed.

You specify whether the file is displayed or not by setting the OpenAfterPublish parameter to True or False, as follows:

  • True: Display file in PDF viewer after conversion.
  • False: Don’t display file in PDF viewer after conversion.

Parameter #9: FixedFormatExtClassPtr

The FixedFormatExtClassPtr parameter of the ExportAsFixedFormat method is a pointer to the FixedFormatExt class.

How To Save An Excel File As PDF Using VBA: Basic Code Examples (Examples #1 And #2)

Now that you are familiar with the ExportAsFixedFormat VBA method, let’s take a look at some code examples.

For purposes of this example, I have prepared a sample Excel workbook. This workbook contains 2 worksheets. Each worksheet includes a table that lists 100 persons and their contact details, along with (i) their food preferences, and (ii) their favorite animal and the name of their pet.

Sample Excel table for PDF conversion

Example of Excel table to save as PDF

How To Save An Excel File As PDF Using VBA: Code Example #1

As I explain above when introducing the ExportAsFixedFormat VBA method, the only required parameter is Type. Therefore, strictly speaking, you can create a very simple macro for purposes of saving an Excel file as a PDF.

The following sample macro (named Save_Excel_As_PDF_1) is, probably, one of the simplest way to save an Excel worksheet as PDF using VBA.

Sample VBA code to save Excel as PDF

This macro consists of a single simple statement:

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF

This statement, can be separated in the following 3 items:

3 items within example of ExportAsFixedFormat VBA method

Let’s take a closer look at each of these elements:

Item #1: ActiveSheet

As I explain when introducing the Worksheet.ExportAsFixedFormat method above, the reference to the method must be preceded by a variable representing a Worksheet object.

In the case of the sample Save_Excel_As_PDF_1 macro above, the Application.ActiveSheet property is used for these purposes. More precisely, ActiveSheet return an object representing the active sheet within the active (or specified) workbook.

You can, as a general matter, also for any of the following:

  • Make reference to a Workbook object, and use the Workbook.ExportAsFixedFormat method.
  • Use a variable that represents a Range object, and use the Range.ExportAsFixedFormat method.
  • Use a representation of a Chart object, and work with the Chart.ExportAsFixedFormat method.

Item #2: ExportAsFixedFormat

The ExportAsFixedFormat method is the main subject of this Excel tutorial. The purpose of this method is to save the relevant object (a worksheet returned by ActiveSheet in the example above) as a PDF file.

In this particular case, ExportAsFixedFormat uses a single parameter, which is…

Item #3: Type:=xlTypePDF

Type is the only required parameter of the ExportAsFixedFormat method. Its purpose is to specify the type of file format to which the relevant worksheet should be exported to.

You specify the relevant file type by choosing the appropriate value from the XLFixedFormatType enumeration. xlTypePDF is 1 of the 2 values in such enumeration.

For the reasons that I explain above, most (if not all) of your macros whose purpose is to save Excel files as PDF will set the Type parameter to be xlTypePDF (or 0). Therefore, you’re likely to use this particular line of VBA code often when creating such VBA Sub procedures.

Excel To PDF Conversion Results: Example #1

The sample Save_Excel_As_PDF_1 macro is very simple and relatively easy to follow. However, this doesn’t mean that you should be using this macro to convert all of your Excel files to PDF.

The reason for this is that, as I show below, the macro (literally) just saves the active worksheet to a PDF file. Since it doesn’t make any adjustment prior to the conversion, the results aren’t necessarily the best.

For purposes of this example, I have executed the Save_Excel_As_PDF_1 macro to save 1 of the worksheets within the sample Excel file that accompanies this tutorial as PDF. The following image shows the resulting PDF file:

Result of saving Excel file as PDF

As first glance, the resulting PDF files looks OK. However, there are several things that can be improved. The following are 2 examples:

  • The resulting page layout is not accurate.

    Notice how there’s 1 column (corresponding to the Favorite Food Ingredient) missing in the image above. Within the resulting PDF, this column appears by itself in separate pages. The following screenshot shows how this looks like:

    Sample PDF file after conversion from Excel

  • The converted PDF file is saved automatically to the default local file location (in this example, the Documents folder) and the file name is the same as that of the original Excel workbook (in this case, Book1).

    Example of PDF file saved using VBA

I show you how to solve several of these issues in the other VBA code examples within this Excel tutorial.

Let’s start to tackle some of these problems by using the additional arguments of the ExportAsFixedFormat method:

How To Save An Excel File As PDF Using VBA: Code Example #2

The sample Save_Excel_As_PDF_1 macro above used the Worksheet.ExportAsFixedFormat method with its only required parameter (Type). However, as I explain further above, the ExportAsFixedFormat method has 9 parameters that allow you to further specify how Visual Basic for Applications carries out the conversion from Excel to PDF.

Therefore, in this second example, I include most of the parameters that you can use when working with the ExportAsFixedFormat method.

Let’s start by taking a look at the VBA code behind the macro (which is called Save_Excel_As_PDF_2):

Example of VBA code to save Excel as PDF

The statements within the body of this new macro are as follows:

ActiveSheet.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="Sample Excel File Saved As PDF", _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, _
    IgnorePrintAreas:=False, _
    From:=1, _
    To:=5, _
    OpenAfterPublish:=True

Let’s take a closer look at each of these lines of VBA code:

Lines #1 And #2: ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF

This new macro (Save_Excel_As_PDF_2) is simply an extension of the first sample macro I provide above (Save_Excel_As_PDF_1).

These first 2 lines are the whole body of that previous macro. In this particular case, they have the same purpose as that which I explain above. Namely:

  • Tell VBA that the ExportAsFixedFormat method should be applied to the current active worksheet.
  • Set PDF as the file format to which the worksheet should be exported to.

Line #3: Filename:=”Sample Excel File Saved As PDF”

This line uses the Filename parameter of the ExportAsFixedFormat method for purposes of specifying the name of the final PDF file.

As I explain above, the previous sample macro simply used the name of the active Excel workbook to name the PDF file that was created after executing the ExportAsFixedFormat method. By using the Filename parameter, you can choose a different filename.

In this particular case, the filename that I’m using is quite simple and only includes the actual filename. Therefore, the PDF file is saved in the default file location.

However, as I explain above, you can use this same parameter for purposes of determining the full path of the converted PDF file.

Line #4: Quality:=xlQualityStandard

This line of VBA code determines the quality of the published PDF file. The Quality parameter of the ExportAsFixedFormat can be set to either of 2 values:

  • xlQualityStandard (or 0), as in this case, which specifies standard quality.
  • xlQualityMinimum (or 1), which represents minimum quality.

Line #5: IncludeDocProperties:=False

You can use the IncludeDocProperties parameter of the ExportAsFixedFormat VBA method for purposes of determining whether the document properties are included or not. IncludeDocProperties can be set to either of the following 2 values:

  • True indicates that the document properties should be included in the resulting file.
  • False (as in this case) indicates that the document properties shouldn’t be included.

Line #6: IgnorePrintAreas:=False

The purpose of the IgnorePrintAreas parameter of the ExportAsFixedFormat method is to determine whether any print areas that are set when publishing should be ignored or not. Just as the previous parameter (IncludeDocProperties), IgnorePrintAreas can be set to either True or False.

  • If IgnorePrintAreas is set to True, the macro ignores any print areas.
  • If you set IgnorePrintAreas to False (as in this example) the macro uses the print areas set when publishing.

Lines #7 And #8: From:=1, To:=5

You can use the From and To parameters of the ExportAsFixedFormat VBA method for purposes of setting the first and last pages that are published in the converted file. More precisely:

  • From allows you to set the page at which publishing begins.
  • To allows you to determine the last page that is published.

In the case of the sample Save_Excel_As_PDF_2 macro, I use the From and To parameters for establishing that only pages 1 (From) through 5 (To) should be published. Had I omitted any of these parameters, the effect would have been as follows:

  • If the omitted parameter is From, publishing begins at the beginning.

    Notice how, in the case we’re analyzing, I’ve set the value of From to 1 (the beginning). Therefore, I can omit the From parameter from the Save_Excel_As_PDF_2 macro while continuing to obtain the same results.

  • If you omit the To parameter, publishing goes all the way to the last page.

    In the Save_Excel_As_PDF_2 macro, I’ve set the To parameter to 5. This isn’t the last page.

    Therefore, if I omit the To parameter, the conversion results differ. Instead of stopping the publishing process at page 5 (as the sample VBA code above does), Visual Basic for Applications would only end publishing at the last page.

Line #9: OpenAfterPublish:=True

The purpose of this line of VBA code is to display the resulting PDF file in the PDF viewer once the conversion process has been completed.

You can also set OpenAfterPublish to False. In this case, the published PDF file isn’t displayed.

Excel To PDF Conversion Results: Example #2

For purposes of comparing the results obtained by the first 2 macro examples (this and example #1 above), I convert the same Excel worksheet of the sample workbook using the Save_Excel_As_PDF_2 macro.

The following image shows how the results look like.

Screenshot of PDF saved by Excel macro

At first glance, this looks very similar to the results obtained when executing the Save_Excel_As_PDF_1 macro above. However, notice some of the effects of the additional parameters that I included in this second macro:

  • The name of the file, as determined by the Filename parameter is “Sample Excel File Saved As PDF”.

    PDF file saved by macro with filename

  • Publishing goes from pages 1 through 5, as specified using the From and To parameters.

    Effect of From and To parameters in Excel to PDF conversion

  • The PDF file is displayed automatically when the macro is executed and immediately after the conversion process is completed.

    Execution of macro to save Excel file as PDF

Overall, the explanations and examples in the sections above show most of what you need to know about the ExportAsFixedFormat VBA method.

You may notice, however, that there are a few things that you can’t fix with the ExportAsFixedFormat method alone. This includes, among others, one that I mention above:

The page layout isn’t properly adjusted. Therefore, the resulting PDF file only shows the first 4 columns of the table within the original Excel source file. The last column (which corresponds to Favorite Food Ingredient in the example above) is missing.

Converted PDF file without Excel column

Screenshot of Excel with table and right column

There are many ways in which you can use other VBA constructs to create more complex and sophisticated macros to save Excel files as PDF. I show you some of the constructs you can use in the following sections, along with some further examples.

Let’s start by taking a look at how you can solve the issue I mention above: How to adjust the page layout of the Excel file you’re going to convert to PDF using VBA.

To do this, you must understand…

How To Adjust The Page Setup To Save An Excel File As PDF Using VBA: The PageSetup Object

Within Excel, whenever you need to manually adjust the page setup before printing an Excel file or saving it as PDF, you go to the Page Setup dialog box.

Excel Page Setup dialog screenshot

Whenever you’re working with Visual Basic for Applications, you can use the Page Setup object for purposes of modifying any page setup attributes. The reason for this is that, as explained at the Microsoft Dev Center (in the webpage I link to above), the Page Setup object:

  • “Represents the page setup description”; and
  • Contains all of the page setup attributes. Each of these page setup attributes is a property of the Page Setup object.

As a consequence of this, the list of properties that are members of the Page Setup object is quite extensive. Let’s take a look at it:

The PageSetup Object: Properties

By my count, the PageSetup object has the 48 properties that I introduce in the table below.

The purpose of this table is simply to introduce these properties and their main purpose. Some of these properties aren’t relevant for the purpose of this Excel tutorial on how to save an Excel file as PDF using VBA. However, I explain some of the properties you may want to explore when working with the ExportAsFixedFormat method below.

Property Purpose
CenterHorizontally Specifies whether the sheet is centered horizontally when printed.
CenterVertically Specifies whether the sheet is centered vertically when printed.
DifferentFirstPageHeaderFooter Determines whether the header or footer on the first page is different.
OddAndEvenPagesHeaderFooter Specifies whether there are different headers and footers for odd and even pages.
CenterFooter Returns or sets the center section of the footer.
CenterHeader Returns or sets the center section of the header.
LeftFooter Returns or sets the left section of the footer.
LeftHeader Returns or sets the left section of the header.
RightFooter Returns or sets the right section of the footer.
RightHeader Returns or sets the right section of the header.
CenterFooterPicture Returns a Graphic object representing the picture in the center section of the footer. Use the properties of CenterFooterPicture to set the attributes of the picture.
CenterHeaderPicture Returns a Graphic object representing the picture in the center section of the header. Use the properties of CenterHeaderPicture to set the attributes of the picture.
LeftFooterPicture Returns a Graphic object representing the picture in the left section of the footer. Use the properties of LeftFooterPicture to set the attributes of the picture.
LeftHeaderPicture Returns a Graphic object representing the picture in the left section of the header. Use the properties of LeftHeaderPicture to set the attributes of the picture.
RightFooterPicture Returns a Graphic object representing the picture in the right section of the footer. Use the properties of RightFooterPicture to set the attributes of the picture.
RightHeaderPicture Returns a Graphic object representing the picture in the right section of the header. Use the properties of RightHeaderPicture to set the attributes of the picture.
BottomMargin Returns or sets the bottom margin.
FooterMargin Returns or sets the margin between the bottom of the page and the footer.
HeaderMargin Returns or sets the margin between the top of the page and the header.
LeftMargin Returns or sets the left margin.
RightMargin Returns or sets the right margin.
TopMargin Returns or sets the top margin.
AlignMarginsHeaderFooter Determines whether to align the header and the footer with the margins.
Application When you use it with an object qualifier, returns an Application object representing the creator of that object.
BlackAndWhite Specifies whether the document is printed in black and white.
Creator Returns a 32-bit integer indicating the application in which the relevant object was created.
Draft Specifies whether a sheet is printed without graphics.
EvenPage Returns or sets the text alignment for the even pages of an Excel workbook (or a section).
FirstPage Returns or sets the text alignment for the first page of an Excel workbook (or a section).
FirstPageNumber Returns or sets the first page number to be used when a sheet is printed.
FitToPagesTall Returns or sets the number of pages (tall) to which an Excel worksheet is scaled to when printed.
FitToPagesWide Returns or sets the number of pages (wide) to which an Excel worksheet is scaled to when printed.
Order Returns or sets the value representing the order that Excel uses to number pages when printing large worksheets.
Orientation Returns or sets the value representing portrait or landscape printing mode.
Pages Returns or sets the count or item number of the pages within the Pages collection.
PaperSize Returns or sets the size of the paper.
Parent Returns the parent object for the relevant object.
PrintArea Returns or sets the range to be printed.
PrintComments Returns or sets the way comments are printed.
PrintErrors Returns or sets the constant specifying the type of print error displayed.
PrintGridlines Determines whether cell gridlines are printed.
PrintHeadings Determines whether row and column headings are printed.
PrintNotes Determines whether cell notes are printed as end notes.
PrintQuality Returns or sets the print quality.
PrintTitleColumns Returns or sets the columns to be repeated on the left side of each page.
PrintTitleRows Returns or sets the rows to be repeated at the top of each page.
ScaleWithDocHeaderFooter Returns or sets whether the header and footer should (also) be scaled with the rest of the Excel file when the size changes.
Zoom Returns or sets a value representing the percentage by which Excel scales the Excel worksheet for printing.

Let’s take a look at how you can use the PageSetup VBA object to improve the results obtained when saving an Excel file as PDF with the ExportAsFixedFormat method.

How To Save An Excel File As PDF Using VBA: Code Example #3

The previous 2 macro examples within this Excel tutorial focus on how you can use the ExportAsFixedFormat method for purposes of saving an Excel file as PDF using VBA.

This third example builds on those 2 examples (in particular example #2 above) to show how you can improve the results you obtain when carrying out an Excel to PDF conversion using VBA.

Let’s start by taking a look at the VBA code behind the sample macro which, in this case, is called Save_Excel_As_PDF_3:

Sample macro to save Excel file as PDF

The statements in the body of this macro are the following:

With ActiveSheet.PageSetup
    .CenterHeader = "Sample Excel File Saved As PDF"
    .Orientation = xlPortrait
    .PrintArea = "$B$5:$F$105"
    .PrintTitleRows = ActiveSheet.Rows(5).Address
    .Zoom = False
    .FitToPagesTall = False
    .FitToPagesWide = 1
End With

ActiveSheet.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="Sample Excel File Saved As PDF 2", _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, _
    IgnorePrintAreas:=False, _
    From:=1, _
    To:=5, _
    OpenAfterPublish:=True

Notice that the second part of the VBA Sub procedure (the block that starts with “ActiveSheet.ExportAsFixedFormat”) is exactly the same as the body of macro example #2 above (Save_Excel_As_PDF_2), which I have explain in detail there.

Therefore, in this particular section, I only explain (line-by-line) the first section of the macro. In other words, the With… End With block.

With... End With statement in VBA code to save as PDF

Let’s take a look at each of the rows in this With… End With block:

Row #1: With ActiveSheet.PageSetup

The With statement allows you to execute a series of statements on a particular object (ActiveSheet.PageSetup in this case) without having to repeat the object qualification every single time.

In other words, all of the statements within the With… End With block (rows #2 to #8 below) make reference to the object that appears on the opening statement (ActiveSheet.PageSetup). The With… End With block ends on row #9, with the End With statement.

The object that appears on the opening statement is the page setup description of the active sheet. The object is obtained by using the Worksheet.PageSetup property. In this particular situation, the Worksheet object is the active sheet (ActiveSheet).

Row #2: .CenterHeader = “Sample Excel File Saved As PDF”

The PageSetup.CenterHeader property allows you to set what appears in the center section of the page header.

You specify the text that you want to appear in this section as a string. In the example above, the text that I specify as header is “Sample Excel File Saved As PDF”.

You can generally apply the syntax and explanation I provide here for the CenterHeader property to the following (roughly equivalent) properties:

  • The PageSetup.CenterFooter property.
  • The PageSetup.LeftFooter property.
  • The PageSetup.LeftHeader property.
  • The PageSetup.RightFooter property.
  • The PageSetup.RightHeader property.

Row #3: .Orientation = xlPortrait

You can use the PageSetup.Orientation property for purposes of setting the xlPageOrientation value that specifies the page orientation. The Orientation property can take the following 2 values:

  • xlPortrait or 0, which (as in this example) represents portrait mode.
  • xlLandscape or 1, which represents landscape mode.

Row #4: .PrintArea = “$B$5:$F$105”

By using the PageSetup.PrintArea property, you can set the print area.

You generally specify the relevant range using A1-style references and as a string. Under the A1-style cell referencing style, you use letters for column headings and numbers for rows.

In the case of the sample macro Save_Excel_As_PDF_3, I use the PrintArea property to specify the range to be converted to PDF. This range is from cells B5 to F105.

Row #5: .PrintTitleRows = ActiveSheet.Rows(5).Address

The PageSetup.PrintTitleRows property allows you to specify that a particular row (or set of rows) should be repeated at the top of each page.

Generally, you specify the rows to be repeated as a string using A1-style references. In this particular example, I don’t explicitly type A1-style references in the code. Let’s take a look at what “ActiveSheet.Rows(5).Address” does:

  • ActiveSheet.Rows(5): Here, I use the Worksheet.Rows property to represent Row 5 of the active worksheet.
  • Address: This makes reference to the Range.Address property, which returns a string representing the relevant range reference.

In other words, “ActiveSheet.Rows(5).Address” also returns an A1-style address as a string, which is precisely what the PrintTitleRows property requires.

You can generally use the same principles and syntax that I explain here in connection with the (roughly equivalent) PageSetup.PrintTitleColumns property.

Row #6: .Zoom = False

By using the PageSetup.Zoom property, you can determine how Excel scales the relevant Excel worksheet for printing or, in this case, conversion to PDF.

As a general rule, you specify the zoom as a Variant value between 10 and 400 percent.

However, notice that in the sample Save_Excel_As_PDF_3 macro, I set the Zoom property to False. Whenever PageSetup.Zoom is set to False, the properties that determine how Excel scales the Excel worksheet are PageSetup.FitToPagesWide and PageSetup.FitToPagesTall. At the same time, if the PageSetup.Zoom property is True, both the FitToPagesWide and FitToPagesTall properties are ignored.

This leads us to…

Row #7: .FitToPagesTall = False

You can use the PageSetup.FitToPagesTall property for purposes of setting the number of pages tall to which the relevant Excel worksheet is scaled to when printing or, in the case of the example in this tutorial, converted to PDF.

In the example we’re taking a look at, I set the FitToPagesTall property to False. In such cases, Excel scales the worksheet in accordance with the FitToPagesWide property. This is done in…

Row #8: .FitToPagesWide = 1

The syntax and purpose of the PageSetup.FitToPagesWide property is roughly the same as that of the FitToPagesTall property above.

In other words, you use the FitToPagesWide property to specify the number of pages wide the relevant Excel worksheet is scaled to when printing or converting to PDF (as in this example). In the sample Save_Excel_As_PDF_3 macro, I set this value to 1 (page wide).

Row #9: End With

As anticipated above, this End With statement simply ends the With… End With block that we’ve just analyzed.

Excel To PDF Conversion Results: Example #3

The Save_Excel_As_PDF_3 uses the ExportAsFixedFormat method in exactly the same way as the previous example #2 (Save_Excel_As_PDF_2), to the point that the relevant block of VBA code is exactly the same.

As I show in this example, you can make several changes or adjustments that influence the resulting PDF file by using the PageSetup object. Let’s take a look at the results of executing the Save_Excel_As_PDF_3 macro on the same Excel worksheet and note down the main differences:

Example of PDF file saved with Excel macro

Note the effects of each of the properties of the PageSetup object that the sample Save_Excel_As_PDF_3 macro uses:

  • The center section of the header says “Sample Excel File Saved As PDF”, as required by the PageSetup.CenterHeader property in row #2 above.

    Example of PDF file saved from Excel with center header

  • The printed area doesn’t include the Power Spreadsheets logo, the preliminary title of this blog post or the hyperlinked text to this page which appear in the first 3 rows of the Excel worksheet. This is a direct consequence of using the PageSetup.PrintArea property to specify the range from cells B5 to F105 as the print area, as done in row #4 above.

    Excel spreadsheet with rows excluded from PDF file

  • The header row of the Excel table is repeated in all of the pages within the converted PDF file. This is achieved by the appropriate use of the PageSetup.PrintTitleRows property in row #5 above.

    Screenshot of PDF file with Excel table and repeated rows

  • All of the columns in the original Excel table appear in an appropriate manner. In other words, the table that appears in the PDF file has been scaled in such a way that it is 1 page wide.

    If you go back up, you’ll notice that both previous examples (macro #1 and macro #2) didn’t fit the print area appropriately to the page. The fifth column (Favorite Food Ingredient) was left out (in macro example #2) or published by itself in the last pages of the PDF file (in macro example #1). This problem is solved by using the Zoom, FitToPagesTall and (particularly) FitToPagesWide properties of the PageSetup object. You can go back to rows #6, #7 and #8 above to see how the VBA code looks like.

    Excel file saved as PDF fitting in 1 page

How To Change The Filename When Saving An Excel File As PDF Using VBA: How To Work With The Filename Parameter Of The ExportAsFixedFormat Method

Parameter #2 of the ExportAsFixedFormat method that I explain above is Filename. You can use this parameter to set the filename of the resulting PDF file. Visual Basic for Applications allows you to do either of the following:

  • Specify the full path and filename of the file.
  • Specify just the filename. In this case, the file is saved in the current default folder.

In the previous macro examples, I’ve not done much with the Filename parameter. More precisely:

  • In the first macro example, I didn’t even include the Filename parameter (it’s optional).

    VBA code to convert Excel to PDf

  • In the (slightly more sophisticated) macros #2 (Save_Excel_As_PDF_2) and #3 (Save_Excel_As_PDF_3), I only included the filename (without the path).

    VBA code to save Excel file as PDF

    Excel VBA code sample to export to PDF

    This resulted in the converted PDF files being saved in the default folder (the Documents folder, in my case).

    Default folder for file saved as PDF with Excel macro

The use of the Filename that I make in these first 3 examples may work for you in certain circumstances. After all, the material structure of those macros is enough to help you save Excel worksheets, workbooks, ranges or charts as PDF files.

However, in several situations, you’ll want to use the Filename parameter in a slightly different way for purposes of creating more sophisticated macros that save Excel files as PDF. Let’s take a look at some different ways you can use the Filename parameter:

Use #1 (Examples #4, #5, #6 And #7): How To Specify The Full Path And Name Of A PDF File Using The Filename Parameter Of The ExportAsFixedFormat Method

If you’re creating a macro to save Excel files as PDF, and those PDF files must always be saved in the same folder, you can simply hard-code the relevant file path and name using the Filename parameter of ExportAsFixedFormat.

Take a look, for example, at the VBA Sub procedure, named Save_Excel_As_PDF_4, which appears below.

This is, substantially, the same as example #3 above (Save_Excel_As_PDF_3). Notice, however, how I’ve specified the full path of the file using the Filename argument.

Example of Excel macro to export file to PDF

The consequence of this change is that the resulting PDF file is no longer saved in the default folder. Instead, the PDF is saved in the folder that you specify with the Filename argument. In the example above, the file is saved to a OneDrive folder called Power Spreadsheets.

Save PDF in OneDrive using Excel VBA

You don’t necessarily need to hard-code all of the details in the Filename parameter. You can, for example, concatenate different items for purposes of building a more flexible filename structure.

The following macro (named Save_Excel_As_PDF_5) example shows the possibilities you have when doing this. Notice how the only difference between this macro and the previous example (Save_Excel_As_PDF_4) is in the Filename parameter.

VBA code to save as PDF with file path

The consequence of including the statement “ActiveWorkbook.Path &” prior to the actual filename (“Sample Excel File Saved As PDF 4”) is that, now, Visual Basic for Applications saves the resulting PDF file in the same folder as the active workbook. In other words, if you use this Filename structure, the new PDF file is saved in the same folder as the source Excel workbook.

The reason for this is that the Workbook.Path property returns a string with the complete path to the relevant workbook. In the case of the example above, the relevant workbook is the active Excel workbook (returned by the Application.ActiveWorkbook property).

I use the ampersand operator (&) to concatenate the file path to the active workbook and the filename, which is surrounded by quotations (“”).

You can take this flexibility even further.

For example, the macro below (Save_Excel_As_PDF_6) uses the name of the active worksheet as the name of the converted PDF file.

Notice how the only difference with the previous macro (Save_Excel_As_PDF_5) is the concatenation of the Worksheet.Name property (using the Application.ActiveSheet property to return the name of the active worksheet) as the actual filename within the Filename parameter. The file path continues to be provided by the Workbook.Path property.

VBA code to save Excel worksheet as PDF using worksheet name

As a final example for this particular section, let’s take a look at the following macro (Save_Excel_As_PDF_7), which saves the active Excel worksheet as a PDF named after the value in cell F5 of the active sheet.

VBA code to save Excel file as PDF using name in cell

In this particular case, the macro uses (i) the Application.ActiveSheet and Worksheet.Range properties to return cell F5, and (ii) the Range.Value property to return the value in that cell.

You can achieve similar results using slightly different structures. This includes, for example, naming the (converted) PDF file by concatenating several strings of text.

In some cases (such as when concatenating several strings of text to specify the PDF filename), it may be more appropriate to declare a variable at the beginning of the procedure to store the applicable string.

Whenever you use a worksheet cell as the source for the PDF filename (as in the example above), make sure that the cell contains no forbidden characters. If the cell from which you take the filename contains characters such as , /, :, ^, ?, “, <, > or |, the macro may not work properly.

The VBA code samples that I provide in this section are just some of the examples of the different ways you can work with (and generate) the Filename argument of the ExportAsFixedFormat method. As you can see, Visual Basic for Applications provides significant flexibility in this regard.

In this blog post, I explain how to save an Excel workbook using VBA. Even though the topic isn’t precisely the same as that of this blog post, some of the principles and examples I provide there may be helpful to you when working with the Filename parameter of the ExportAsFixedFormat VBA method.

Use #2 (Example #8): How To Name A PDF File Using The Application.GetSaveAsFilename Method

You can use the Application.GetSaveAsFilename method to allow your PDF-saving macro to get a filename from the user. This allows the user of your VBA application to specify the full path and filename.

I cover the Application.GetSaveAsFilename method in detail in my Excel tutorial about the topic (I link to it above). For purposes of this macro example, it’s enough to know that the GetSaveAsFilename method:

  1. Displays the Save As dialog box.

    Example of Save As dialog box for PDF from Excel

  2. Gets the filename that the user enters in the Save As dialog box.
  3. Doesn’t actually save or export a file.

    This is the reason why, as shown below, you must anyway use the ExportAsFixedFormat method for purposes of saving an Excel workbook as PDF.

The following sample macro (Save_Excel_As_PDF_8) shows how you can use the Application.GetSaveAsFilename method to provide the Filename parameter when using the ExportAsFixedFormat method:

VBA code example to export file to PDF

Let’s take a closer look at the VBA code behind the Save_Excel_As_PDF_8 macro to understand what’s going on:

First, notice that 2 blocks of VBA code look are quite familiar:

VBA code to save as PDF with highlighted blocks

The 2 blocks of code I highlight in the image above are substantially the same as those that appear in other examples of VBA code within this Excel tutorial. More precisely:

  • Block #1 is a With… End With block that appears in macro examples #3 (where I explain each line of code), #4, #5, #6 and #7.
  • Block #2, which uses the Worksheet.ExportAsFixedFormat method, is substantially the same as the equivalent blocks of code in macro examples #2 (where it is explained in detail), #3, #4, #5, #6 and #7.

The only difference is in the Filename parameter, which is the topic we’re focusing on in this section.

VBA code to convert file to PDF with filename parameter

Considering that I explain each of these 2 blocks of VBA code in detail in the previous sections of this Excel tutorial, we can now go through each of the blocks of code in the Save_Excel_As_PDF_8 macro:

Block #1: Dim PdfFilename As Variant

The purpose of this line is to declare a variable called PdfFilename.

I cover the topic of VBA variables in more detail here and here. A variable is simply a storage location that you pair with a name. You use the variable to represent a certain value.

In this example, I use the PdfFilename variable for purposes of storing the filename that the user enters into the Save As dialog box (displayed by the Application.GetSaveAsFilename method in block #3 below). The variable is later used in the Filename parameter of the ExportAsFixedFormat in block #3 below.

The PdfFilename variable is of the Variant data type. Variant:

  • Is the default data type; and
  • Changes (the exact) type depending on the particular scenario.

Even though Variant isn’t the most efficient data type, it’s probably the most desirable for this particular case. The reason for this is that the GetSaveAsFilename method can return different types. For example:

  • If the user cancels the Save As dialog box displayed by the GetSaveAsFilename method, the returned value is a Boolean (False).
  • If the user provides the filename that should be used to save the converted PDF file, GetSaveAsFilename returns a String.

Variant is able to handle both of these situations and allows your macro to be more flexible.

Block #2: PdfFilename = Application.GetSaveAsFilename( InitialFileName:=”Sample Excel File Saved As PDF 5″, FileFilter:=”PDF, *.pdf”, Title:=”Save As PDF”)

This statement assigns a value to the PdfFilename variable declared in block #1 above.

The value that is assigned to PdfFilename is the file name provided by the user through the Save As dialog. This Save As dialog box is displayed by the Application.GetSaveAsFilename method.

In this particular example, the GetSaveAsFilename method uses the following 3 parameters:

  • InitialFileName: Specifies a suggested/default filename. In this example, the default filename is “Sample Excel File Saved As PDF 5”.
  • FileFilter: Specifies the file filtering criteria. In the example above, the only file filter makes reference to PDF files.
  • Title: Determines the title of the Save As dialog box that is actually displayed. In the sample Save_Excel_As_PDF_8 macro, the title of the dialog box is “Save As PDF”.

The following screenshot shows the Save As dialog box that is displayed by the GetSaveAsFilename method that uses the parameters above. Notice the effect of each of the arguments that I list above:

Save As PDF from Excel dialog box

Block #3: If… Then Statement

The third main block of VBA code within the sample Save_Excel_As_PDF_8 macro is an If… Then statement.

VBA code to export file to PDF using If... Then statement

From a broad perspective, an If… Then statement does 2 things:

  • Step #1: Tests whether a condition is met.
  • Step #2: If the condition is met, performs one action. If the condition isn’t met, performs no action.

The If… Then statement within the example macro above can be broken down into the 3 following sections:

Section #1: If PdfFilename <> False Then.

The condition tested by this particular statement is whether the variable PdfFilename is different from False.

If the condition is met (PdfFilename isn’t False), the statements within the If… Then block are executed. These statements are the ones that adjust the page setup (as explained in macro example #3 above) and export the active worksheet to a PDF file (as I explain in macro examples #1 and #2 above).

If... Then statement in macro that saves Excel file as PDF

If the condition isn’t met (PdfFilename is False), the statements within the If… Then block aren’t executed. In such a case, execution of the macro ends without the Excel worksheet being converted to PDF.

As I explain above, if the user of the VBA application cancels the Save As dialog box, the GetSaveAsFilename method returns False. Therefore, PdfFilename is False whenever the user cancels the Save As dialog box. In such cases, you probably don’t want to proceed with the process of saving the Excel file as PDF.

Section #2: With… End With Statement And Worksheet.ExportAsFixedFormat Method.

These statements are executed when the condition tested by the If… Then statement above (PdfFilename <> False) is met.

VBA code to save Excel file using If... Then statement

I explain all of these statements in great detail within the previous macro examples (here and here).

One of these rows of VBA code is, however, not exactly the same as in the previous examples:

Filename:=PdfFilename

VBA code to save as PDF with variable for filename

This is the line that specifies the value of the Filename parameter of the ExportAsFixedFormat method. In other words, this line is the one that specifies the filename of the PDF file that results from the conversion.

In this particular case, the filename that is assigned to the PDF file is the value of the PdfFilename variable. In turn, the value of the PdfFilename is determined by the Application.GetSaveAsFilename method in block #2 above.

As a consequence of this, the filename is simply the one that is specified by the user of the application by using the Save As dialog displayed by the GetSaveAsFilename method.

For example, in the situation displayed in the following screenshot, if you press the Save button (on the lower right corner of the dialog box), the PDF file is saved under the filename “Sample Excel File Saved As PDF 5”.

Save As PDF dialog box from macro

Section #3: End If.

The last row of the If… Then statement (and the sample macro in general) signals the end of the If… Then statement.

Example of VBA code to export to PDf with End If statement

How To Save Each Worksheet As A Separate PDF Using VBA: How To Use Loops With The ExportAsFixedFormat Method (Examples #9 And #10)

As a general rule, whenever you want to save all of the worksheets within an Excel workbook, you can simply use the Workbook.ExportAsFixedFormat method. The explanations I provide throughout this Excel tutorial (particularly the first section) are generally applicable to the Workbook.ExportAsFixedFormat method.

For example, the following (very simple) macro (Save_Excel_As_PDF_9) is the equivalent to the one in example #1 above.

VBA code to export full workbook from Excel to PDF

The difference between the 2 macros is that:

  • The macro in example #1 uses (i) the Application.ActiveSheet property to return the active sheet and (ii) the Worksheet.ExportAsFixedFormat method to export the worksheet to a PDF file.
  • The example in this section uses (i) the Application.ActiveWorkbook property to return the active sheet and (ii) the Workbook.ExportAsFixedFormat method to convert the whole workbook to PDF.

However, when you use the Workbook.ExportAsFixedFormat method, all the worksheets are exported to the same PDF file. This may be what you want in certain situations.

However, in other situations, you may want to save each worksheet within a workbook in a separate file. You can achieve this by working with the Worksheet.ExportAsFixedFormat method and loops.

In the context of the ExportAsFixedFormat method and saving Excel files as PDF, the following 2 are the main things you must understand in connection to loops:

  • The term looping, in very broad terms, makes reference to the execution of certain statements several (more than 1) time.
  • Loops help you to save each worksheet as a separate PDF file because of the way they proceed. More precisely, such a loop proceeds (very roughly) as follows:
    • Step #1: Executes all of the statements that save an Excel worksheet as PDF.
    • Step #2: Moves on to the next worksheet.
    • Step #3: Goes back to step #1 above. In other words, executes (again) all of the statements that save the Excel worksheet as PDF.

    When properly structured, a loop allows your VBA code to go through every single worksheet and saves it as a separate PDF file.

Let’s take a look at a macro that combines the ExportAsFixedFormat method with loops in order to save each worksheet as a separate PDF file:

VBA code that saves each Excel worksheet as separate PDF

Notice how most of the VBA code in the sample Save_Excel_As_PDF_10 macro is (once more) substantially the same as that of previous macro examples in this tutorial. The following screenshot shows the new items, which I explain further below.

Sample VBA to export Excel worksheets to separate PDF files

Let’s take a closer look at each of the rows that contain new items within this sample macro:

Row #1: Dim iCounter As Integer

This statement declares a variable called iCounter. The selected data type is Integer which, as explained in this tutorial, can store integers between -32,768 and 32,767.

The iCounter variable is used as a loop counter, a topic I explain further when covering the following rows.

Row #2: For iCounter = 1 To Worksheets.Count

This is the opening statement for the loop. In this particular example, I use a For… Next loop.

This is, however, not the only type of loop you can use for these purposes. You can, for example, (also) use the For Each… Next loop when exporting each worksheet to a separate PDF file.

The initial value of the counter is 1 (iCounter = 1). The end value of the counter, which determines when the looping stops, is specified by the Sheets.Count property. The value returned by Worksheets.Count is the number of worksheets.

Each time the VBA code goes through the loop, the value of the iCounter variable increases by 1.

As a consequence of the above, the macro loops a number of times equal to the number of worksheets in the active workbook.

Row #3: With Worksheets(iCounter).PageSetup

As I explain above, this is the opening statement of the With… End With block that adjusts the page setup. All of the statements within a With… End With block (rows #4 to #10) make reference to the object that appears in this statement (Worksheets(iCounter).PageSetup).

In previous examples, this statement made reference to the page setup settings of the active sheet by making reference to “ActiveSheet.PageSetup” instead of “Worksheets(iCounter).PageSetup”.

The difference between both statements is, therefore, on the specific Worksheet object used within the syntax of the Worksheet.PageSetup property.

  • ActiveSheet makes reference to the current active worksheet.
  • Worksheets(iCounter) makes reference to the iCounter-th element of the Worksheets collection. The iCounter variable in the statement above is a worksheet index number. The specific number is determined by how many times the VBA code has gone through the loop. Therefore:
    • On the first loop, iCounter is equal to 1. Therefore, Worksheets(iCounter) makes reference to the first worksheet in the workbook (Worksheets(1)).
    • The second time, iCounter is equal to 2. In such a case, Worksheets(iCounter) is the equivalent of Worksheets(2) and refers to the second worksheet within the workbook.
    • … and so on, until…
    • On the last loop, iCounter is equal to the number of worksheets in the workbook. Therefore, Worksheets(iCounter) makes reference to the last worksheet in the workbook.

Rows #4 To #11: With… End With Block

I explain Rows #4 to #11 in example #3 above.

VBA code to export file to PDF

The purpose of this block is to adjust the relevant properties of the PageSetup object for the relevant worksheet (as determined by the loop).

Rows #12 To #20: Worksheets(iCounter).ExportAsFixedFormat

I explain, in detail, this statement and all the parameters of the ExportAsFixedFormat method used therein in a previous section of this tutorial.

VBA code to export Excel to PDF

There are, however, 2 rows that differ from what appears in the previous examples:

  • Row #12: Worksheets(iCounter).ExportAsFixedFormat.
  • Row #14: Filename:=ActiveWorkbook.Path & “” & Worksheets(iCounter).Name.

In both cases, the difference is in the use of the Worksheets collection and an index (Worksheets(iCounter)) to refer to the relevant worksheet.

Counter within VBA code to save Excel file as PDF

The reason for this is, as I explain above, related to the For… Next loop. More precisely:

  • The statement “Worksheets(iCounter).ExportAsFixedFormat” exports the relevant sheet (as determined by the current loop number) to PDF.
  • The use of “Worksheets(iCounter).Name” within the value of the Filename parameter sets the name of the resulting PDF file to be equal to the name of the current worksheet (which depends on the current loop number). This is very similar to the Filename parameter value used in example #6 above, where the name of the active sheet is used to name the relevant PDF file. However, in this particular macro (Save_Excel_As_PDF_10), the use of a loop means that each worksheet is saved under its own worksheet name.

Conclusion

After reading this Excel tutorial, you’re ready to start creating macros for purposes of saving Excel files as PDF.

This Excel VBA Save as PDF Tutorial is accompanied by files containing the data and macros I use in the examples above. You can get immediate free access to these example files by clicking the button below.

Get immediate free access to the Excel VBA Save as PDF file examples

In addition to having a very good understanding of the ExportAsFixedFormat VBA method, you’ve also seen how you can:

  • Combine the ExportAsFixedFormat method with the PageSetup object in order to adjust the page setup attributes prior to the Excel to PDF conversion.
  • Use different methods for determining the filename of the PDF file you save.
  • Use loops for purposes of saving each worksheet as a separate PDF file.

In addition to the above, you’ve seen 10 different examples of VBA code that allow you to save Excel files as PDF using several different settings and parameters.

As with most topics related to Excel and VBA, I’ve not exhausted the topic despite writing this very comprehensive tutorial. You can use the knowledge and ideas you’ve gained here in order to create different macros that achieve similar purposes.

Понравилась статья? Поделить с друзьями:
  • Vba excel all opened
  • Vba excel all files in folder
  • Vba excel ado примеры
  • Vba excel address ячейки
  • Vba excel add form