Sei sulla pagina 1di 12

Export Active Sheet as PDF File

The following macro code will export the active sheet (or sheets) in PDF format.
Copy the code to a regular code module, then select the sheet(s) you want to
export, and run the macro.
See the section further down, for details on how the macro works.
NOTE: There are two additional macros below:

 Create PDF file with name from worksheet cells - automatically


overwrites existing file, if any
 Create PDF file with name from worksheet cells - check for existing file,
prompt to overwrite or choose different name

The Export As PDF Code


Copy the code to a regular code module, then select the sheet(s) you want to
export, and run the macro.

Sub PDFActiveSheet()
'www.contextures.com
'for Excel 2010 and later
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler

Set wbA = ActiveWorkbook


Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")

'get active workbook folder, if saved


strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

'replace spaces and periods in sheet name


strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")

'create default name for savng file


strFile = strName & "_" & strTime & ".pdf"
strPathFile = strPath & strFile

'use can enter name and


' select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")

'export to PDF if a folder was selected


If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If

exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub

How The Macro Works


Before you run the macro, select the sheet(s) that you want to export to the PDF
file.
When the macro starts, it sets variables for the active sheet, and the active
workbook. Those will be used to set the default file name and folder.

Set wbA = ActiveWorkbook


Set wsA = ActiveSheet

A time stamp will be added to the default name, in the format


yyyymmdd_hhmm.
In the format string shown below, a backslash is entered before the underscore,
to indicate it is a literal character. Otherwise, Excel would interpret the
underscore as the spacing character that is used in Excel number formatting.

Set wbA = ActiveWorkbook


Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")

Next, the macro gets the default path for saving the PDF file. If the active
workbook has been saved, its path is used. If the active workbook has not been
saved, Excel's default save folder is used.

strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

The name of the active sheet is cleaned up -- spaces are removed, and periods
are replaced with underscores.

'replace spaces and periods in sheet name


strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")

The file path, revised sheet name, and the ".pdf" extension are combined.

'create default name for savng file


strFile = strName & "_" & strTime & ".pdf"
strPathFile = strPath & strFile

The Save As dialog box opens, with the current folder selected, or the default
save folder. The folder is filtered, to show only the PDF files that it contains.
At the top of the Save As window, the customized title is shown, "Select Folder
and FileName to save"

myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")

The default file name is filled in, and you can overwrite it, to save the file with a
different name. You can also select another folder --just browse to a different
location.
Then, click the Save button, or click Cancel, if you change your mind.

 If you click Cancel, the value of myFile is "False", and nothing more
happens -- the macro ends.
 If you click Save, the PDF file is created.

If myFile <> "False" Then


wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False

Then, if the file was created, the macro shows a confirmation message with the
file path and name.

MsgBox "PDF file has been created: " _


& vbCrLf _
& myFile

Click the OK button to close the message box.


Macro 2 - No Prompt
The previous macro creates a default name with a time stamp, based on the
active sheet name. It prompts you to select a folder for the saved PDF file, and
you can change the default name, if you prefer something different.
In the macro below, the default name is based on the values in cells A1, A2 and
A3 on the active sheet. The PDF file is automatically saved in the current folder -
- you are not prompted to choose a folder, and cannot change the default name.

Sub PDFActiveSheetNoPrompt()
'www.contextures.com
'for Excel 2010 and later
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler

Set wbA = ActiveWorkbook


Set wsA = ActiveSheet

'get active workbook folder, if saved


strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

strName = wsA.Range("A1").Value _
& " - " & wsA.Range("A2").Value _
& " - " & wsA.Range("A3").Value

'create default name for savng file


strFile = strName & ".pdf"
strPathFile = strPath & strFile

'export to PDF in current folder


wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile

exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Macro 3 - No Prompt - File Check
In the macro below, the default name is based on the values in cells A1, A2 and
A3 on the active sheet. The PDF file is automatically saved in the current folder,
with no prompts.
However, if a file with that name already exists in the current folder, a
message asks if you want to overwrite the file. Click Yes or No in the message
box.

 Yes - the new file overwrites the old file


 No - you are prompted to choose a folder, and/or enter a different file
name.

NOTE: Be sure to copy the bFileExists Function too, below the main macro

Sub PDFActiveSheetNoPromptCheck()
'www.contextures.com
'for Excel 2010 and later
'checks for existing file
'prompt to overwrite or rename
'uses bFileExists Function, below

Dim wsA As Worksheet


Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim lOver As Long
On Error GoTo errHandler

Set wbA = ActiveWorkbook


Set wsA = ActiveSheet

'get active workbook folder, if saved


strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

strName = wsA.Range("A1").Value _
& " - " & wsA.Range("A2").Value _
& " - " & wsA.Range("A3").Value

'create default name for savng file


strFile = strName & ".pdf"
strPathFile = strPath & strFile

If bFileExists(strPathFile) Then
lOver = MsgBox("Overwrite existing file?", _
vbQuestion + vbYesNo, "File Exists")
If lOver <> vbYes Then
'user can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
strPathFile = myFile
Else
GoTo exitHandler
End If
End If
Else
'export to PDF in current folder
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
End If

exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
'=============================
Function bFileExists(rsFullPath As String) As Boolean
bFileExists = CBool(Len(Dir$(rsFullPath)) > 0)
End Function
'=============================
Sub Save_as_pdf()
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String

Set FSO = CreateObject("Scripting.FileSystemObject")


s(0) = ThisWorkbook.FullName

If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")

'//Export to PDF with new File Path


ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try
again."
End If

Set FSO = Nothing

End Sub

1
Private Sub CommandButton1_Click()
2 Application.ScreenUpdating = False
3 ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
4 Filename:="C:\PDF\Export.pdf", _
5 OpenAfterPublish:=False
Application.ScreenUpdating = True
6 End Sub
7

Sub SaveAsPDF()
Application.Screen Updating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Application.InputBox("Enter File Name")

strExcelPath = "H:\My Documents"

Application.ScreenUpdating = True
End Sub

'Save Active Sheet(s) as PDF


ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Users\marks\Documents\Saved PDF.pdf"
'Save active workbook as PDF
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Users\marks\Documents\Saved PDF.pdf"

'Save selection as PDF


Selection.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Users\marks\Documents\Saved PDF.pdf"

'Save a chart as PDF


ActiveChart.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Users\marks\Documents\Saved PDF.pdf"

'Save a range as PDF


Sheets("Sheet1").Range("A1:H20").ExportAsFixedFormat
Type:=xlTypePDF, _
Filename:="C:\Users\marks\Documents\Saved PDF.pdf"

Potrebbero piacerti anche