Сохранение в PDF книги Excel, группы листов, одного листа или отдельного диапазона с помощью кода VBA. Метод ExportAsFixedFormat. Примеры экспорта.
Метод ExportAsFixedFormat
Метод ExportAsFixedFormat сохраняет рабочую книгу Excel или выбранную группу листов этой книги в один PDF-файл. Чтобы экспортировать каждый лист в отдельный файл, необходимо применить метод ExportAsFixedFormat к каждому сохраняемому листу.
Синтаксис
Expression.ExportAsFixedFormat (Type, FileName, Quality, IncludeDocProperties, IgnorePrintAreas, From, To, OpenAfterPublish, FixedFormatExtClassPtr) |
Expression – это выражение, представляющее объект Workbook, Worksheet или Range.
Параметры
Единственный обязательный параметр – Type, остальные можно не указывать – в этом случае будут применены значения по умолчанию.
Параметр | Описание |
---|---|
Type | Задает формат файла для экспорта книги или листа: xlTypePDF(0) – сохранение в файл PDF; xlTypeXPS(1) – сохранение в файл XPS*. |
FileName | Задает имя файла. При указании полного пути, файл будет сохранен в указанную папку, при указании только имени – в папку по умолчанию (в Excel 2016 – «Документы»). Если имя не задано (по умолчанию), файл будет сохранен с именем экспортируемой книги. |
Quality | Задает качество сохраняемых электронных таблиц: xlQualityMinimum(1) – минимальное качество; xlQualityStandard(0) – стандартное качество (по умолчанию). |
IncludeDocProperties | Включение свойств документа Excel в PDF: True(1) – включить; False(0) – не включать; мне не удалось обнаружить разницу и значение по умолчанию. |
IgnorePrintAreas | Указывает VBA, следует ли игнорировать области печати, заданные на листах файла Excel: True(1) – игнорировать области печати; False(0) – не игнорировать области печати (по умолчанию). |
From** | Задает номер листа книги Excel, с которого начинается экспорт. По умолчанию сохранение в PDF начинается с первого листа книги. |
To** | Задает номер листа книги Excel, на котором заканчивается экспорт. По умолчанию сохранение в PDF заканчивается на последнем листе книги. |
OpenAfterPublish | Указывает VBA на необходимость открыть созданный файл PDF средством просмотра: True(1) – открыть файл PDF для просмотра; False(0) – не открывать файл PDF для просмотра (по умолчанию). |
FixedFormatExtClassPtr | Указатель на класс FixedFormatExt (игнорируем этот параметр). |
* XPS – это редко использующийся фиксированный формат файлов, разработанный Microsoft, который похож на PDF, но основан на языке XML.
** Применимо только к книге (Workbook.ExportAsFixedFormat), при экспорте листа (Worksheet.ExportAsFixedFormat) указание параметров From и/или To приведет к ошибке.
Сохранение в PDF книги Excel
Экспорт всей книги
Sub Primer1() ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=«C:Testfile1.pdf», OpenAfterPublish:=True End Sub |
Если вы указываете путь к файлу, он должен существовать, иначе VBA сохранит файл с именем и в папку по умолчанию («ИмяКниги.pdf» в папку «Документы»).
Экспорт части книги
Этот способ позволяет сохранить в PDF группу листов, расположенных подряд:
Sub Primer2() ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=«C:Testfile2.pdf», _ From:=2, To:=4, OpenAfterPublish:=True End Sub |
Сохранение в PDF рабочих листов
Экспорт одного листа
Sub Primer3() ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=«C:Testfile3.pdf», OpenAfterPublish:=True End Sub |
Экспорт диапазона
Sub Primer2() Лист4.Range(«A1:F6»).ExportAsFixedFormat Type:=xlTypePDF, Filename:=«C:Testfile4.pdf», OpenAfterPublish:=True End Sub |
Если экспортируемый диапазон расположен на активном листе, имя листа указывать не обязательно.
Экспорт группы листов
Этот способ удобен тем, что экспортировать в PDF можно листы, расположенные не подряд:
Sub Primer5() Sheets(Array(«Лист2», «Лист3», «Лист5»)).Select Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:=«C:Testfile5.pdf», OpenAfterPublish:=True End Sub |
Jun 01 2017
01:26 AM
— edited
Jun 01 2017
08:21 AM
Further to my previous post I have managed to adapt the code to do what I required: 1. Create a pdf of ActiveSheet 2. Save pdf into a specific location 3. Name the pdf with a file name based on the sheet date 4. Open an email, with selected recipients, and attach the current pdf to and email If you have any suggestions to develop the code or see any possible errors please let me know. Sub Sent_Email() Dim olApp As Object s = Range(«h1»).Value ‘ ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _ s, Quality:=xlQualityStandard, IncludeDocProperties _ :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False PDF_File = «I:2017 — 2018Operations UnitDay SheetsDS_» & Format(Now, «YYMMDD») & «.pdf» Set olApp = CreateObject(«Outlook.Application») With olApp.CreateItem(0) .Subject = «Daily Resource Sheet» .To = ActiveSheet.Range(«C50») .Cc = ActiveSheet.Range(«C55») .Body = «Hi,» & vbLf & vbLf _ & «Please find attached the Daily Resource Sheet.» & vbLf & vbLf _ & «Regards,» & vbLf & vbLf _ & «Roads Operations Unit» .Attachments.Add PDF_File .Save .Display End With End Sub
best response confirmed by
Joe Gray (New Contributor)
Jun 01 2017
06:31 PM
— edited
Jun 01 2017
06:38 PM
Solution
This is code I use.
End Sub
Private Sub Email() Dim objOutlook As Object Dim objMail As Object Dim signature As String Dim oWB As Workbook Set oWB = ActiveWorkbook Set objOutlook = CreateObject("Outlook.Application") Set objMail = objOutlook.CreateItem(0) With objMail .Display End With signature = objMail.HTMLbody With objMail .To = oWB.Sheets("Sheet1").Range("A1").Value ''.SentOnBehalfOfName = "" .Subject = strMySubject ''.body = "Dear Sir," & vbNewLine & vbNewLine & "Add stuff here" & vbNewLine & vbNewLine & signature .HTMLbody = "<font face=" & Chr(34) & "Calibri" & Chr(34) & " size=" & Chr(34) & 4 & Chr(34) & ">" & "Dear Sir," & "<br> <br>" & "Add stuff here" & "<br> <br>" & signature & "</font>" .Attachments.Add (strSaveFileName + ".pdf") .Display End With Set objOutlook = Nothing Set objMail = Nothing End Sub
Jun 01 2017
06:37 PM
— edited
Jun 01 2017
06:37 PM
And this is code to export to PDF
You obviously need a full path as a string to save the file to
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strSaveFileName, Quality:=xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False ThisWorkbook.SaveAs Filename:=strSaveFileName, FileFormat:=xlOpenXMLTemplateMacroEnabled
Jun 02 2017
01:59 AM
Thank you Andrew
You‘re no doubt aware that I am new to Coding and very much appreciate your response. I will hopefully be able to pass on assistance to others in the very near future.
Jun 02 2017
07:33 AM
Andrew
Just to let you know that the code below works well for me, and thank you again.
Command Button: —
- Generates a pdf of the ActiveSheet
- Saves pdf to a specific location, indicated in Cell H1, with an auto Filename based on the Sheet Date within Cell I3, formatted as YYMMDD
- Opens Outlook and displays email with pdf attached (file with date «Now»)
- Auto fills Recipients, reading from Cell C50
- Email Body as required
When i’m happy i will change code to automatically send email not display.
for reference:-
Cell H1: =»I:2017 — 2018Operations UnitDay Sheets»&»DS_»&TEXT(I3,»yymmdd»)&».PDF»
Private Sub Email_Sheet_Click() Dim objOutlook As Object Dim objMail As Object Dim signature As String Dim oWB As Workbook Set oWB = ActiveWorkbook s = Range("h1").Value ' ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _ s, Quality:=xlQualityStandard, IncludeDocProperties _ :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False PDF_File = "Insert Path hereDS_" & Format(Now, "YYMMDD") & ".pdf" Set objOutlook = CreateObject("Outlook.Application") Set objMail = objOutlook.CreateItem(0) With objMail .Display End With signature = objMail.HTMLbody With objMail .To = ActiveSheet.Range("C50") .Cc = ActiveSheet.Range("C55") .Subject = "Insert Subject Here" .HTMLbody = "<font face=" & Chr(34) & "Calibri" & Chr(34) & " size=" & Chr(34) & 4 & Chr(34) & ">" & "Hi," & "<br> <br>" & "Insert email body here" & "<br> <br>" & signature & "</font>" .Attachments.Add PDF_File .Save .Display End With Set objOutlook = Nothing Set objMail = Nothing End Sub
May 14 2018
08:28 AM
I’m very new to coding, so I wanted to add a little twist to this thread. Is it possible to have a code to convert the current spreadsheet to PDF, create an email through Outlook, but not save the document?
Thanks!
May 14 2018
12:47 PM
— edited
May 14 2018
12:47 PM
From what I remember it’s necessary to save the document to attach the file. However, you can save the PDF to a temporary directory and then once done using it you can just delete it:
It would look something like this:
TempFilePath = Environ$("temp") & "" 'This defines the filepath ---> C:UsersusernameAppDataLocalTemp TempFileName = "Your File Name Goes Here" 'Name File
ActiveWorkbook.SaveAs TempFilePath & TempFileName 'Save file in Temporary Directory 'Email Workbook to people With OutMail .To = "YourName@Email.Com" .CC = "" .BCC = "" .Subject = "This is the Subject line" .Body = "This is the email body" 'Use "Blah Blah Blah" & Chr(13) & "This is another line" .Attachments.Add TempFilePath & TempFileName .Send End With 'Delete the Temporary File Kill TempFilePath & TempFileName
May 23 2018
12:34 PM
Please help…
This code is perfect for what I want to do in order to simplify a procees repeated at work but am a little stuck. I have it working to a point..
PDF Is saving in the directory pre set in Cell A1 all ok.
Outlook then opens (no attachment and no email addresses inserted) and I then get the following error (See attached)
I do not need to save the doc with date. Happy to Modify Cell A1 (C:UsersmarkDesktopquotes12345.pdf each time its used with the prefered directory/filename. Clearly there is some of the code and how it works am not understanding.
I dont understand why the email addresses dont pull through from cells A2 and A3 and not sure what I need to do in order to have the file which has saved ok in the required directy attach to the email.
If anyone can help me get this working would be much appreciated also if any additional information is required just ask. Full VBA below….
Sub Email_Sheet_Click()
Dim objOutlook As Object
Dim objMail As Object
Dim signature As String
Dim oWB As Workbook
Set oWB = ActiveWorkbook
s = Range(«A1»).Value
‘
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
s, Quality:=xlQualityStandard, IncludeDocProperties _
:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
PDF_File = «Insert Path hereDS_» & Format(Now, «YYMMDD») & «.pdf»
Set objOutlook = CreateObject(«Outlook.Application»)
Set objMail = objOutlook.CreateItem(0)
With objMail
.Display
End With
signature = objMail.HTMLbody
With objMail
.To = ActiveSheet.Range(«A2»)
.Cc = ActiveSheet.Range(«A3»)
.Subject = «Insert Subject Here»
.HTMLbody = «<font face=» & Chr(34) & «Calibri» & Chr(34) & » size=» & Chr(34) & 4 & Chr(34) & «>» & «Hi,» & «<br> <br>» & «Insert email body here» & «<br> <br>» & signature & «</font>»
.Attachments.Add PDF_File
.Save
.Display
End With
Set objOutlook = Nothing
Set objMail = Nothing
End Sub
Any help will be much appreciated!
May 23 2018
12:49 PM
These small edits should make the code work (Please see changes in bold):
Sub Email_Sheet_Click() Dim objOutlook As Object Dim objMail As Object Dim signature As String Dim PDF_FileName As String Dim oWB As Workbook Set oWB = ActiveWorkbook 'Change your string to this.... PDF_FileName 'or change your cell value in A1 'This is the name of your PDF... 'Change accordingly.... PDF_FileName = "C:Usersmmickle1DesktopDS_" & Format(Now, "YYMMDD") & ".pdf" ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ PDF_FileName, Quality:=xlQualityStandard, IncludeDocProperties _ :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False Set objOutlook = CreateObject("Outlook.Application") Set objMail = objOutlook.CreateItem(0) With objMail .Display End With signature = objMail.HTMLbody With objMail .To = ActiveSheet.Range("A2") .Cc = ActiveSheet.Range("A3") .Subject = "Insert Subject Here" .HTMLbody = "<font face=" & Chr(34) & "Calibri" & Chr(34) & " size=" & Chr(34) & 4 & Chr(34) & ">" & "Hi," & "<br> <br>" & "Insert email body here" & "<br> <br>" & signature & "</font>" .Attachments.Add PDF_FileName 'Now that the name is correct it will work. .Save .Display End With Set objOutlook = Nothing Set objMail = Nothing End Sub
If you have additional questions it may be beneficial to attach a sample file for testing.
Jun 07 2018
12:36 PM
— edited
Jun 07 2018
01:37 PM
Thanks Matt sorted now appreciate the quick response. For anyone attempting a similar code I have also added a few things as wanted email subjectfield to display a variable cell value from an INDEX/lookup and also wanted the body of the email to include a variable cell value (I am too lazy to actually type the information in when the email opens!)
Sub emailsavePDF()Dim objOutlook As Object
Dim objMail As Object
Dim signature As String
Dim oWB As Workbook
Set oWB = ActiveWorkbooks = Range("O7").Value
'
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
s, Quality:=xlQualityStandard, IncludeDocProperties _
:=True, IgnorePrintAreas:=False, OpenAfterPublish:=FalsePDF_File = Range("O7").Value & ".pdf"
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)With objMail
.display
End With
signature = objMail.HTMLbody
With objMail
.To = Sheets("Estimate").Range("O9")
.Cc = Sheets("Estimate").Range("O10")
.Subject = Range("N23").Value
.HTMLbody = "<BODY style=font-size:11pt;font-family:Calibri>Hi;<p>Please find attached estimate for trailer " & Range("N24") & "<p> Any questions please don't hesitate to ask." & "<br> <br>" & signature & "</font>"
.Attachments.Add PDF_File
.Save
.display
End WithSet objOutlook = Nothing
Set objMail = Nothing
End Sub
Jun 08 2018
01:25 PM
Hey Mark-
Glad you were able to get it working! Please feel free to post back to the community if you have additional Excel questions.
Jun 27 2018
08:33 AM
— edited
Jun 27 2018
09:06 AM
Formula works great but I need to make an amendment and struggling to get it working correctly.
I want a error message to appear telling the user to check they have met certain conditions should they forget to complete certain cells which constitute the file name the doc is to be saved as.
There are x2 Macros that run together email and save PDF and save Excel doc both below.
I have inserted a goto On Error command but struggling getting it right. It either displays as soon as the Macros are run regardless of error existing or it displays x2 times for each macro and then (even if the cells are left blank) continues to save the excel doc with no file name which I did not think was possible.
I need the message to box to simply appear once and then end/do nothing after the user sees the message rather than save the excel doc with no filename.
Sub emailsavePDF()Dim objOutlook As Object
Dim objMail As Object
Dim signature As String
Dim oWB As Workbook
Set oWB = ActiveWorkbook
On Error GoTo ErrMsg
s = Range("O7").Value
'
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
s, Quality:=xlQualityStandard, IncludeDocProperties _
:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
PDF_File = Range("O7").Value & ".pdf"
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With objMail
.display
End With
signature = objMail.HTMLbody
With objMail
.To = Sheets("Estimate").Range("O9")
.Cc = Sheets("Estimate").Range("O10")
.Subject = Range("O12").Value
.HTMLbody = "<BODY style=font-size:11pt;font-family:Calibri>Hi;<p>Please find attached estimate for trailer " & Range("O13") & "<p> Any questions please don't hesitate to ask." & "<br> <br>" & signature & "</font>"
.Attachments.Add PDF_File
.Save
.display
Exit Sub
ErrMsg:
MsgBox "1: A customer must been selected in cell C4" & vbNewLine & "" & vbNewLine & "2: A trailer number must be entered in cell C5 and must not contain any symbols" & vbNewLine & "" & vbNewLine & "3: A breif repair description must be entered in Cell C9 and must not contain any symbols" & vbNewLine & "" & vbNewLine & "4: You are connected to the network", , "THE FOLLOWING STEPS MUST BE COMPLETED"
Exit Sub
End With
Set objOutlook = Nothing
Set objMail = Nothing
End Sub
Sub emailsaveexcel()
Dim newWB As Variant
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
With wb1
.SaveCopyAs Sheets("Estimate").Range("O5").Text & ".xlsm"
Exit Sub
End With
End Sub
Jun 27 2018
04:17 PM
If your filename only consists of range O7 then you will want to make sure that it is not left blank. If this is the only scenario where you’re getting an error you may not need any complex error handling. YOu could probably get by with something like this:
If Range("O7") = vbNullString Then MsgBox "Please fill in cell O7 which contains the filename. " _ & "It has been left blank", vbCritical, "Error Message" Exit Sub End If
Jun 27 2018
04:19 PM
— edited
Jun 27 2018
11:51 PM
Hi Mark,
I’m glad to see this code has been helpful and is still being developed.
1. you are not using the error function correctly.
2. your PDF_FILE variable does not reference a sheet
3. your s variable does not reference a sheet and is a duplicate of PDF_FILE
Example
Public wb As Workbook
Public sh As Worksheet
Private Sub Test()
On Error GoTo errormessage
Set wb = ActiveWorkbook
Set sh = ActiveSheet
With sh
If .Range(«C4») = Empty Then
MsgBox («please enter values in C4»)
End
ElseIf .Range(«C5») = Empty Then
MsgBox («please enter values in C5»)
End
ElseIf .Range(«C9») = Empty Then
MsgBox («please enter values in C9»)
End
End If
End With
Dim Filename As String
Filename = «C:UsersPublicDocuments» & sh.Range(«O5»).Value & «.xlsm»
wb.SaveAs Filename:=Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
errormessage:
With Err
Select Case .Number
Case 1004 ‘add code for 1004 error
MsgBox «Error: » & Err.Number & vbNewLine & vbNewLine & Err.Description, vbOKOnly + vbExclamation, «Error»
Case Else
MsgBox «Error: » & Err.Number & vbNewLine & vbNewLine & Err.Description, vbOKOnly + vbExclamation, «Error»
End Select
Resume Next
End With
EndOfSub:
End Sub
Jun 28 2018
12:23 AM
— edited
Jun 28 2018
01:16 AM
Hi Matt/Andrew
O7 Contains a formula something like =O6&C5&» «&C9 so the filename/directory is the combined contents of cells c5 (Unit number) and c9 (repair description) the directory the file is being saved in (Which varies on a drop down placed in cell C4) must also be selected or the formula will not know where to save it. The directory varies depending on customer the spreadsheet is being used for.
Just the elaborate the Macro works perfectly for me I just need a pop up message if cells 06 C6 and C9 are left blank as this will cause an error as the Macro will not know where to save if C4 is blank (Technically the user only needs to put text in one box for the file name O6 or C5) an error will only occur if both are blank. The only other time an error would occur is if the user is not connected to our network as all of the directory’s are on our network drive. The user does not see or edit Cell O7
I need an error handling code reminding the user to fill in these cells if they forget rather than the standard Excel message which doesn’t really help the user. It may be possible to have a Macro telling the user to fill in these cells but an error will still occur if they are not connected to our network/VPN so error message will still occur.
Code without my attempt at error goto below:
Sub emailsavePDF()
Dim objOutlook As Object
Dim objMail As Object
Dim signature As String
Dim oWB As Workbook
Set oWB = ActiveWorkbook
s = Range(«O7»).Value
‘
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
s, Quality:=xlQualityStandard, IncludeDocProperties _
:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
PDF_File = Range(«O7»).Value & «.pdf»
Set objOutlook = CreateObject(«Outlook.Application»)
Set objMail = objOutlook.CreateItem(0)
With objMail
.display
End With
signature = objMail.HTMLbody
With objMail
.To = Sheets(«Estimate»).Range(«O9»)
.Cc = Sheets(«Estimate»).Range(«O10»)
.Subject = Range(«O12»).Value
.HTMLbody = «<BODY style=font-size:11pt;font-family:Calibri>Hi;<p>Please find attached estimate for trailer » & Range(«O13») & «<p> Any questions please don’t hesitate to ask.» & «<br> <br>» & signature & «</font>»
.Attachments.Add PDF_File
.Save
.display
End With
Set objOutlook = Nothing
Set objMail = Nothing
End Sub
Sub emailsaveexcel()
Dim newWB As Variant
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
With wb1
.SaveCopyAs Sheets(«Estimate»).Range(«O5»).Text & «.xlsm»
End With
End Sub
Jun 28 2018
05:19 AM
Mark-
Try something like this:
Sub WhateverSub() On Error GoTo ErrHandler 'Your Code Here.... Exit Sub ErrHandler: 'If one of these cells is blank.... If Range("C4") = vbNullString Or Range("C6") = vbNullString Or Range("C9") = vbNullString Then MsgBox "Please fill in cells O7, C6 and C9 they are mandatory fields that " _ & "have been left blank!!", vbCritical, "Error Message" Exit Sub Else 'Some other error like a VPN error MsgBox "Please make sure you have a network connection!", vbCritical, "Error Message" Exit Sub End If End Sub
You can check to see if a directory exists like this….
If Dir("C:Usersmmickle1Documents", vbDirectory) = "" Then MsgBox "Directory does not exist..." End If
You may consider having some data validation to light up a cell red if the mandatory fields are not filled in as an extra safe guard…
Here’s the original article I learned about error handling with… it’s pretty thorough. In fact I still reference it occasionally :
Chip Pearson Error Handling
Jun 29 2018
12:08 AM
You could use WScript.Network to connect to/ test for mapped drives? (the network)
https://ss64.com/vb/network.html
the error handler is very general and will display a message showing any code problems it catches. its up to you to decide what to do with the errors.
Sub emailsavePDF()on error Goto ErrHandler
Dim objOutlook As Object
Dim objMail As Object
Dim signature As String
Dim oWB As WorkbookSet oWB = ActiveWorkbook
' MsgBox "
'1: A customer must been selected in cell C4" & vbNewLine & "" & vbNewLine & "
'2: A trailer number must be entered in cell C5 and must not contain any symbols" & vbNewLine & "" & vbNewLine & "
'3: A breif repair description must be entered in Cell C9 and must not contain any symbols" & vbNewLine & "" & vbNewLine & "
'4: You are connected to the network", , "THE FOLLOWING STEPS MUST BE COMPLETED"With Sheets("Estimate")
If .Range("C4") = Empty Then
MsgBox ("A customer must been selected in cell C4 and must not contain any symbols")
End
ElseIf .Range("C5") = Empty Then
MsgBox ("A trailer number must be entered in cell C5 and must not contain any symbols")
End
ElseIf .Range("C9") = Empty Then
MsgBox ("A breif repair description must be entered in Cell C9 and must not contain any symbols")
End
End IfEnd With
s = Range("O7").Value 'excel file name
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=s, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
PDF_File = s & ".pdf" 'pdf file name
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)With objMail
.display
End With
signature = objMail.HTMLbody
With objMail
.To = Sheets("Estimate").Range("O9")
.Cc = Sheets("Estimate").Range("O10")
.Subject = Range("O12").Value
.HTMLbody = "<BODY style=font-size:11pt;font-family:Calibri>Hi;<p>Please find attached estimate for trailer " & Range("O13") & "<p> Any questions please don't hesitate to ask." & "<br> <br>" & signature & "</font>"
.Attachments.Add PDF_File
.Save
.displayEnd With
Set objOutlook = Nothing
Set objMail = Nothing
ErrHandler:
With ErrSelect Case .Number
Case 1004 'add code for 1004 error
MsgBox "Error: " & Err.Number & vbNewLine & vbNewLine & Err.Description, vbOKOnly + vbExclamation, "Error"
Case Else
MsgBox "Error: " & Err.Number & vbNewLine & vbNewLine & Err.Description, vbOKOnly + vbExclamation, "Error"
End Select
Resume Next
End With
End SubSub emailsaveexcel()
Dim newWB As Variant
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
With wb1
.SaveCopyAs Sheets("Estimate").Range("O5").Text & ".xlsm"
End With
End Sub
Jul 11 2018
11:12 AM
Thanks Andrew
The below works great thanks with one exception. Is there any way if the user enters any of the following / : * ? ” < > |anywhere in both cell C5 or C9 a warning appears as these cells form the filename and the file cannot be saved if these symbols are contained anywhere within the text of these cells
Sub emailsavePDF()Dim objOutlook As Object
Dim objMail As Object
Dim signature As String
Dim oWB As Workbook
Set oWB = ActiveWorkbook' MsgBox "
'1: A customer must been selected in cell C4" & vbNewLine & "" & vbNewLine & "
'2: A trailer number must be entered in cell C5 and must not contain any symbols" & vbNewLine & "" & vbNewLine & "
'3: A breif repair description must be entered in Cell C9 and must not contain any symbols" & vbNewLine & "" & vbNewLine & "
'4: You are connected to the network", , "THE FOLLOWING STEPS MUST BE COMPLETED"With Sheets("Estimate")
If .Range("C4") = Empty Then
MsgBox ("A customer must been selected in cell C4 and must not contain any symbols")
End
ElseIf .Range("C5") = Empty Then
MsgBox ("A trailer number must be entered in cell C5 and must not contain any symbols")
End
ElseIf .Range("C9") = Empty Then
MsgBox ("A breif repair description must be entered in Cell C9 and must not contain any symbols")
End
End IfEnd With
s = Range("O7").Value
'
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
s, Quality:=xlQualityStandard, IncludeDocProperties _
:=True, IgnorePrintAreas:=False, OpenAfterPublish:=FalsePDF_File = Range("O7").Value & ".pdf"
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)With objMail
.display
End With
signature = objMail.HTMLbody
With objMail
.To = Sheets("Estimate").Range("O9")
.Cc = Sheets("Estimate").Range("O10")
.Subject = Range("O12").Value
.HTMLbody = "<BODY style=font-size:11pt;font-family:Calibri>Hi;<p>Please find attached estimate for trailer " & Range("O13") & "<p> Any questions please don't hesitate to ask." & "<br> <br>" & signature & "</font>"
.Attachments.Add PDF_File
.Save
.display
End WithSet objOutlook = Nothing
Set objMail = NothingEnd Sub
Sub emailsaveexcel()
Dim newWB As Variant
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
With wb1
.SaveCopyAs Sheets("Estimate").Range("O5").Text & ".xlsm"
End WithEnd Sub
ggg
Jul 11 2018
11:43 AM
Mark-
You can just error handle for that scenario by using the Replace() Function.
s = Replace(Replace(Replace(Range("O7"), "/", "_"), "", "_"), ":", "_")
This will replace those special characters with an «_» which is acceptable for file names…
Цитата |
---|
Sanja написал: С чего это вдруг ‘недостаток’? По условию задачи этого не требовадось |
Я имела ввиду, что лучше сделать, чтобы можно было сохранять более одного раза без лишних действий)
Sub SafeAsPdf()
Dim arrSelSheets(), i As Long
Application.ScreenUpdating = False
ReDim arrSelSheets(1 To ActiveWindow.SelectedSheets.Count)
For i = 1 To UBound(arrSelSheets)
arrSelSheets(i) = ActiveWindow.SelectedSheets(i).Name
Next
Worksheets(Array(«КП»)).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & «» & «КП » & Format(Now, «YYYYMMDD») & » » & Format(Now, «hhmm») & «.pdf», Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Worksheets(arrSelSheets).Select
Application.ScreenUpdating = True
MsgBox «Урррааа!», vbInformation
End Sub
Сохранить определенные листы excel в PDF |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Добрый день уважаемые Форумчане!
Получилось частично сделать макрос, который выполняет сохранение нужного листа в данном случае(«Лист2») в PDF формате, при этом присваивая ему имя из заданной ячейки.
Но имеются 2 вопроса:
1. Почему-то если в ячейки стоит формула, а она мне нужна, по сколько я соединяю ей тек. дату и текст, макрос не вставляет ее значение в название файла автоматом, а если написать просто текст, то вставляет. Собственно в чём тут проблема пожалуйста подскажите.
2. Как указать нужную папку для сохранения(например C:UsersВладелецDesktopЕжедневный), если я правильно понял, то к ExportAsFixedFormat надо задать еще переменную OutputFileName, но правильных примеров не нашёл.
Спасибо.
Since Excel 2010, it has been possible to save Excel as PDF. The PDF format was then and continues to be, one of the most common file formats for distributing documents.
The code examples below provide the VBA macros to automate the creation of PDFs from Excel using the ExportAsFixedFormat method. This means you do not require a PDF printer installed, as Excel can print directly to a PDF document.
The example codes can be used independently or as part of a larger automation process. For example, check out this post to see an example of how to loop through a list and print a PDF for each item: Create multiple PDFs based on a list
Rather than going from Excel to PDF, you might want to go the other way; from PDF to Excel. Check out these posts for possible solutions for that scenario:
- How to Import PDF Files into Excel with Power Query
- Get data from PDF into Excel
Download the example file: Click the link below to download the example file used for this post:
Saving Excel workbooks, sheets, charts, and ranges as PDF
This section contains the base code to save Excel as PDF from different objects (workbooks, worksheets, ranges, and charts). From a VBA perspective, it is the ExportAsFilxedFormat method combined with the Type property set to xlTypePDF that creates a PDF.
Save active sheet as PDF
The following code saves the selected sheets as a single PDF.
Sub SaveActiveSheetsAsPDF()
'Create and assign variables
Dim saveLocation As String
saveLocation = "C:UsersmarksOneDriveDocumentsmyPDFFile.pdf"
'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
End Sub
Save active workbook as PDF
Use the following macro to save all the visible sheets from a workbook.
Sub SaveActiveWorkbookAsPDF()
'Create and assign variables
Dim saveLocation As String
saveLocation = "C:UsersmarksOneDriveDocumentsmyPDFFile.pdf"
'Save active workbook as PDF
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
End Sub
Save selection as PDF
Sometimes, we only want to save a small part of a worksheet to a PDF. The following code prints only the selected cells.
Sub SaveSelectionAsPDF()
'Create and assign variables
Dim saveLocation As String
saveLocation = "C:UsersmarksOneDriveDocumentsmyPDFFile.pdf"
'Save selection as PDF
Selection.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
End Sub
Save a range as PDF
The macro below saves a specified range as a PDF.
Sub SaveRangeAsPDF()
'Create and assign variables
Dim saveLocation As String
Dim ws as Worksheet
Dim rng As Range
saveLocation = "C:UsersmarksOneDriveDocumentsmyPDFFile.pdf"
Set ws = Sheets("Sheet1")
Set rng = ws.Range("A1:H20")
'Save a range as PDF
rng.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
End Sub
Save a chart as PDF
The VBA code below saves a specified chart as a PDF.
Sub SaveChartAsPDF()
'Create and assign variables
Dim saveLocation As String
Dim ws As Worksheet
Dim cht As Chart
saveLocation = "C:UsersmarksOneDriveDocumentsmyPDFFile.pdf"
Set ws = Sheets("Sheet1")
Set cht = ws.ChartObjects("Chart 1").Chart
'Save a chart as PDF
cht.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
End Sub
Rather than naming a specific chart, the macro could run based on the active chart. Change this:
Set cht = ws.ChartObjects("Chart 1").Chart
To this:
Set cht = ActiveChart
Adapting the code to your scenario
To adapt the code examples to your specific needs, you should adjust certain lines of code.
Change the save location
To save the file in the correct location, change this list of code:
saveLocation = "C:UsersmarksOneDriveDocumentsmyPDFFile.pdf"
If you would prefer the save location to be included in a cell, change the code to reference the sheet and cell containing the file path.
saveLocation = Sheets("Sheet1").Range("B2").Value
Change the worksheet
In this line of code, change the text “Sheet1” to the sheet name in your workbook.
Set ws = Sheets("Sheet1")
Change the range
The following line of codes references the range to be printed to PDF.
Set rng = ws.Range("A1:H20")
Change the chart
To print a chart to PDF, change the chart’s name in the following line of code.
Set cht = ws.ChartObjects("Chart 1").Chart
If you are unsure of the chart name, it is shown in the Name box when the chart is selected.
Notes for saving PDF documents
While the Filename property is optional, it is important to know where the file is saved.
- If the Filename property is not provided, the PDF saves in your default folder location using the Excel workbook’s name with the .pdf file extension.
- Where a file name is provided, but not a file path, the document saves in your default folder location with the name provided.
- When the .pdf file extension is not provided, the suffix is added automatically.
- If a PDF exists in the specified save location, the existing file is overwritten. Therefore, it may be necessary to include file handling procedures to prevent overwriting existing documents and handling errors.
- To save as an XPS document format, change xlTypePDF for xlTypeXPS.
Selecting specific worksheets before saving as PDF
If more than one worksheet is active, the PDF created includes all the active sheets. The following code selects multiple worksheets from an array before saving the PDF.
Sub SelectSheetsAndSaveAsPDF()
'Create and assign variables
Dim saveLocation As String
Dim sheetArray As Variant
saveLocation = "C:UsersmarksOneDriveDocumentsmyPDFFile.pdf"
sheetArray = Array("Sheet1", "Sheet2")
'Select specific sheets from workbook, the save all as PDF
Sheets(sheetArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
End Sub
In the code above, an array is used to select the specific sheets. Alternatively, the Split array function with a text string could provide a more dynamic solution. This method is covered here: VBA Arrays.
Looping and saving as separate PDFs
To save multiple PDFs quickly, we can use VBA to loop through sheets or charts and save each individually.
Loop through sheets
The following macro loops through each worksheet in the active workbook and saves each as its own PDF. Each PDF is saved in the same folder as the workbook, where each PDF’s name is based on the worksheet’s name.
Sub LoopSheetsSaveAsPDF()
'Create variables
Dim ws As Worksheet
'Loop through all worksheets and save as individual PDF in same folder
'as the Excel file
For Each ws In ActiveWorkbook.Worksheets
ws.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "/" & ws.Name & ".pdf"
Next
End Sub
Loop through selected sheets
The following macro loops through only the selected worksheets in the active workbook and saves each as its own PDF.
Sub LoopSelectedSheetsSaveAsPDF()
'Create variables
Dim ws As Worksheet
Dim sheetArray As Variant
'Capture the selected sheets
Set sheetArray = ActiveWindow.SelectedSheets
'Loop through each selected worksheet
For Each ws In sheetArray
ws.Select
ws.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "/" & ws.Name & ".pdf"
Next ws
'Reselect the selected sheets
sheetArray.Select
End Sub
Loop through charts
The following code loops through each chart on the active sheet and saves each as a separate PDF.
Sub LoopChartsSaveAsPDF()
'Create and assign variables
Dim chtObj As ChartObject
Dim ws As Worksheet
Set ws = ActiveSheet
'Loop through all charts and save as individual PDF in same folder
'as the Excel file
For Each chtObj In ws.ChartObjects
chtObj.Chart.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "/" & chtObj.Name & ".pdf"
Next chtObj
End Sub
Other PDF print options
When using ExportAsFixedFormat, there are other optional settings available:
'Open the document after it is saved - options are True / False
OpenAfterPublish:=False
'Include the Excel document properties into the PDF - options are True / False
IncludeDocProperties:=True
'Does the created PDF adhere to the Print Areas already set in the
'worksheet - options are True / False
IgnorePrintAreas:=False
'Set the output quality of the created document - options are
'xlQualityMinimum / xlQualityStandard
Quality:=xlQualityStandard
'The page to start printing. If excluded, will start from the first page
From:=1
'The page to print to. If excluded, will go to the last page
To:=2
VBA Save to PDF Example using all the options
The code below demonstrates how to use all the options within a single macro. These options can be flexed to meet your requirements.
Sub SaveAsPDFOptions()
Dim saveLocation As String
saveLocation = "C:UsersmarksDocumentsmyPDFFile.pdf"
'Example using all the options
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=saveLocation, _
OpenAfterPublish:=False, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
Quality:=xlQualityStandard, _
From:=1, To:=2
End Sub
Other fixed formats available (xlTypeXPS)
The Type property can also create XPS documents when it is set to xlTypeXPS rather than xlTypePDF. XPS is Microsoft’s fixed file format; it is similar to PDF but based on the XML language. It is rarely used in the real world but is an option if required.
Conclusion
Learning how to save Excel as PDF is a good time investment. Each of these code snippets on its own is useful. However, the code examples above can be used in other automation to create even more time-saving.
Related posts:
- Excel – Create multiple PDFs based on a list
- Loop through selected sheets with VBA
- How to loop through each item in Data Validation list with VBA
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
При работе в Microsoft Excel вы можете столкнуться с проблемой сохранения активного рабочего листа в виде файла PDF. В этой статье вы можете узнать, как сохранить активный рабочий лист в виде файла PDF с кодом VBA с помощью командной кнопки. И если вы также хотите сохранить диапазон или каждый рабочий лист в активной книге как отдельный файл PDF, эта статья также может вам помочь.
Используйте командную кнопку, чтобы сохранить активный рабочий лист как файл PDF с кодом VBA
Легко сохраняйте активный или каждый рабочий лист в виде отдельного файла PDF с Kutools for Excel
Используйте командную кнопку, чтобы сохранить активный рабочий лист как файл PDF с кодом VBA
Вы можете запустить следующий код VBA, чтобы сохранить активный рабочий лист в виде файла PDF, нажав кнопку Command. Пожалуйста, сделайте следующее.
1. Во-первых, вам необходимо создать папку с именем PDF для сохранения вашего нового преобразованного файла PDF. Здесь я создаю эту папку на моем локальном диске (C :).
2. Вставьте командную кнопку, нажав Застройщик > Вставить > Командная кнопка (элемент управления ActiveX). Смотрите скриншот:
2. Затем нарисуйте командную кнопку на листе, в котором вам нужно добавить новые строки, щелкните правой кнопкой мыши кнопку и нажмите Предложения из контекстного меню.
3. в Предложения диалоговом окне введите отображаемый текст командной кнопки в поле Подпись поле под Категории вкладку, а затем закройте диалоговое окно.
Вы можете видеть, что отображаемый текст кнопки управления изменен, как показано ниже.
4. Снова щелкните правой кнопкой мыши командную кнопку, а затем щелкните Просмотреть код из контекстного меню.
5. В дебюте Microsoft Visual Basic для приложений в окне кода замените исходный код в окне кода следующим кодом VBA.
Код VBA: кнопка управления для сохранения активного листа в формате PDF
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:PDFExport.pdf", _
OpenAfterPublish:=False
Application.ScreenUpdating = True
End Sub
Внимание: В коде CommandButton1 — это имя командной кнопки, которую вы будете использовать для сохранения активного листа в виде файла PDF. «C: PDF Export.pdf» — это путь и имя вашего сохраняемого файла PDF.
6. нажмите другой + Q клавиши одновременно, чтобы закрыть Microsoft Visual Basic для приложений окно. Затем выключите Режим проектирования под Застройщик меню.
Теперь нажмите кнопку Command, активный рабочий лист будет сохранен в виде файла PDF с именем «Экспорт» и расположен в указанном месте.
Сохраните каждый рабочий лист как отдельный PDF-файл активной книги с Kutools for Excel
Здесь рекомендую Разделить книгу полезности Kutools for Excel чтобы легко сохранить активный рабочий лист в виде файла PDF. Кроме того, с помощью этой утилиты вы также можете сохранить каждый рабочий лист в текущей книге как отдельный файл PDF.
1. В книге вам необходимо сохранить каждый лист как отдельный файл PDF, затем щелкнуть Кутулс Плюс > Workbook > Разделить книгу. Смотрите скриншот:
2. в Разделить книгу диалоговое окно, настройте следующим образом:
2.1) Проверяйте только имя активного листа в Имя рабочего листа коробка;
2.2) Выбрать PDF (* .pdf) из файла Сохранить как раскрывающийся список;
2.3) Нажмите Трещина кнопку, затем Выбор папки появится диалоговое окно, укажите папку для сохранения файла PDF;
Затем выбранный рабочий лист сразу сохраняется как файл PDF.
Заметки:
1. Вы можете отметить несколько имен рабочих листов в поле Имя рабочего листа, чтобы сохранить их как отдельный файл pdf одновременно;
2. За исключением сохранения рабочего листа в виде файлов PDF, вы можете сохранять рабочие листы в формате txt. или csv. файл как вам нужно.
Если вы хотите получить бесплатную пробную версию (30-день) этой утилиты, пожалуйста, нажмите, чтобы загрузить это, а затем перейдите к применению операции в соответствии с указанными выше шагами.
Демонстрация: сохраните выбор или каждый рабочий лист в формате PDF с помощью Kutools for Excel
Статьи по теме:
- Как автоматически вставить новую пустую строку с помощью командной кнопки в Excel?
- Как отформатировать ячейку, чтобы она выглядела как 3D-кнопка в Excel?
- Как скрыть или показать командную кнопку на основе указанного значения ячейки в Excel?
Лучшие инструменты для работы в офисе
Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%
- Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
- Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон…
- Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны…
- Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
- Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
- Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии…
- Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
- Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF…
- Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
Вкладка Office: интерфейс с вкладками в Office и упрощение работы
- Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
- Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
- Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!