Export excel to pdf layout changes - excel

So i have searched for hours now and did not find a solution.
I am trying to export sheets that have a print area to PDF but the PDF layout is different than what i see when i check the print preview.
i am using excel 2010.
Does anyone know why this happens.
code i use to export
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False

Finally found a solution. apparently its something with the settings.
In Excel, go to File > Options > Advanced. Under General section,
uncheck ‘Scale content for A4 or 8.5 x 11” paper size’ and click OK.

Instead of exporting the document, why dont you print the sheet and set the printer to PDF printer something like.
Sub PrintTest() ' This will print multiple sheets based on a certain criteria
Dim sh As Worksheet
Dim arr() As String
Dim i As Long: i = 0
For Each sh In ThisWorkbook.Worksheets
If Mid(sh.Name, 1, 4) = "Test" Then ' Change the conditional statement
sh.PageSetup.Orientation = xlLandscape
ReDim Preserve arr(i)
arr(i) = sh.Name
i = i + 1
End If
Next sh
Dim printSheets As Variant
printSheets = arr
Worksheets(printSheets).PrintOut Preview:=False, ActivePrinter:="Adobe PDF", PrintToFile:=True, PrToFileName:=PSFileName
End Sub

Related

VBA to print the same area from multiple worksheets as separate PDF files

Going through the stack overflow and other sources on the internet, I found a couple of VBA codes to print multiple active worksheets to separate PDF files.
I would like to use the same printing area in each sheet and save the PDFs as separate files. While trying to (re)create the code, I have now reached the following state and am stuck. More specifically, it seems that the last four lines before "Next" are erroneous (makred in red in Excel VBA Console and causing syntax error), but I am unable to pinpoint what that is so. Can someone here help me out. Thanks in advance.
Sub SetPrintAreas2()
Dim sPrintArea As String
Dim wks As Worksheet
sPrintArea = "C8:E25"
For Each wks In ActiveWindow.SelectedSheets
wks.PageSetup.PrintArea = sPrintArea
wks.PageSetup.Orientation = xlLandscape
wks.PageSetup.PaperSize = xlPaperA4
wks.PageSetup.CenterHorizontally = True
wks.PageSetup.CenterVertically = True
wks.PageSetup.FitToPagesWide = 1
wks.PageSetup.FitToPagesTall = 1
wks.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Application.ActiveWorkbook.Path & “\” & wks.Name, _
Quality:=xlQualityStandard, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
Set wks = Nothing
End Sub
Thanks to all of you helped make a completely unworkable code full functional. This is how the final working code looks:
Sub SetPrintSameAreasOfActiveSheetsAsPDFs()
Dim sPrintArea As String
Dim wks As Worksheet
sPrintArea = "C8:E25"
For Each wks In ActiveWindow.SelectedSheets
wks.PageSetup.PrintArea = sPrintArea
wks.PageSetup.Orientation = xlLandscape
wks.PageSetup.PaperSize = xlPaperA4
wks.PageSetup.CenterHorizontally = True
wks.PageSetup.CenterVertically = True
wks.PageSetup.FitToPagesWide = 1
wks.PageSetup.FitToPagesTall = 1
wks.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Application.ActiveWorkbook.Path & Application.PathSeparator & wks.Name, _
Quality:=xlQualityStandard, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
Set wks = Nothing
End Sub
It prints the Cells between C8:E25 for all selected worksheets in an Excel workbook as PDFs to the same directory. The PDFs take up the name of the worksheet. To use it, after inserting it as a VBA module in the excel sheet, go to the developer tab, Click on Macros, select SetPrintSameAreasOfActiveSheetsAsPDFs() and press "Run".
Change this text to below. your “\” is wrong character.
“\”
to
"\"
or
Application.PathSeparator

Fixed save as filename in PDF does not work anymore Office 2016

I recently updated to office 2016 and now my macro that i am using to select a range in excel, and then convert this range to PDF and automatically send an email, does not fully work.
Before when i used this macro, the filename was automatically filled in the SaveAs dialog box, but now it is empty. I do not understand why.
Does anyone else has a problem like this or know how to fix it?
Here is my code:
Function Skicka_projektunderlag_PDF(Myvar As Object, FixedFilePathName As String, _
OverwriteIfFileExist As Boolean, OpenPDFAfterPublish As Boolean) As String
Dim FileFormatstr As String
Dim Fname As Variant
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws = Sheets("Partner_information")
Set ws1 = Sheets("Kundinformation")
Set ws2 = Sheets("Kalkyl")
If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
& Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then
If FixedFilePathName = "" Then
FileFormatstr = "PDF Files (*.pdf), *.pdf"
Fname = Application.GetSaveAsFilename(ws.Range("B1").Value & " - Projektunderlag " & ws2.Range("BF104").Value & " " & ws1.Range("B3").Value _
, FileFilter:=FileFormatstr, Title:="Create PDF")
If Fname = False Then Exit Function
Else
Fname = FixedFilePathName
End If
If OverwriteIfFileExist = False Then
If Dir(Fname) <> "" Then Exit Function
End If
On Error Resume Next
Myvar.ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=Fname, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=OpenPDFAfterPublish
On Error GoTo 0
If Dir(Fname) <> "" Then Skicka_projektunderlag_PDF = Fname
End If
End Function
Best regards
AgatonSaxx
The following answer isn't refined but I have also been struggling with this problem in Word 2016 VBA to generate a default file name when Save As is selected in Word 2016
and wanted to share what I've found thus far as it is working with some success.
I was able to get the code semi-working again by adding an event handler.
Application.DocumentBeforeSave Event
example here https://msdn.microsoft.com/en-us/library/office/ff838299.aspx
tied to Using Events with Application Object
example here https://msdn.microsoft.com/en-us/library/office/ff821218.aspx
I moved my actual code to within the class module
Cancel=true
had to be added to the end of the code or the Save As dialog box would open twice.
This "solution" has some drawbacks that it only works once per document. So, if for some reason, you want to use SaveAs on the same document more than once, the name won't default. It also seems a bit clunky/limited for my taste but it is a start.
This "solution" is Word based but you should be able to do/ find something similar for Excel.
Hope this helps put you on the path to success. Apologies for not being a perfect answer. Just wanted to share lessons learned as maybe it will cut down on your time to a solution!

Using Selection.ExportAsFixedFormat to generate PDF properly

I want to export to pdf all the sheets on the workbook except the first one. To do that I used Selection.ExportAsFixedFormat instead of ActiveWorkbook.ExportAsFixedFormat.
The problem using Selection.ExportAsFixedFormat, is that for each sheet, the only part of it that will appear ond the correspondent pdf page is a manual selection instead of all the printing area as it should be (if I select only one cell it will be the only one that appears on the pdf). Using ActiveWorkbook.ExportAsFixedFormat the pdf is generated as intended.
Sub PDF()
Dim SaveAsStr As String
Dim strName As String
Dim i As Long
ReDim ArraySh(2 To Sheets.Count)
For i = 2 To Sheets.Count
ArraySh(i) = Sheets(i).Name
Next
...
'ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, fileName:=SaveAsStr & ".pdf", OpenAfterPublish:=True, IgnorePrintAreas:=False
Sheets(ArraySh).Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, fileName:=SaveAsStr & ".pdf", OpenAfterPublish:=True, IgnorePrintAreas:=False
End Sub
How can I use the Selection method, to generate the PDF properly?

How to save a sheet array to PDF with a specific sheet order

I have a Workbook with multiple sheets which I want to select and convert to a single PDF file.
I have written the following code which works fine and creates the file:
Sub Print_Project_Report_To_PDF
Dim FilePathandName As String
MyDate = Format(DateSerial(Year(Now), Month(Now) - 1, 1), "mmmm yyyy")
MyPath = ThisWorkbook.Path & "\"
MyFile = "Project Progress Report - " & MyDate & ".pdf"
FilePathandName = MyPath & MyFile
ThisWorkbook.Sheets(Array("PR_COVER_PAGE", "PR_SUMMARY", _
"PR_PROJECT_DETAILS", "PR_INTERNAL RESOURCES", "PR_TIME", _
"PR_REVENUE_FORECAST_SUMMARY", "PR_ORIGINAL_REVENUE_FORECAST", _
"PR_ACTUAL_REVENUE_FORECAST", "PR_COSTS", "PR_ISSUES", "MONTHLY FINANCIAL REPORT", _
"PG-SC_COVER_LETTER", "PG-SC_CLAIM_SUMMARY", "PG-SC_TRADE", "PG-SC_HYDRAULICS", _
"PG-SC_MECHANICAL", "PG-SC_MEDICAL_GASES", "PG-SC_ELECTRICAL", "PG-SC_VARIATION", _
"PG-SC_MONTHLY_CASHFLOW", "PG-MH_COVER_LETTER", "PG-MH_CLAIM_SUMMARY", _
"PG-MH_TRADE", "PG-MH_HYDRAULICS", "PG-MH_MECHANICAL", "PG-MH_MEDICAL_GASES", _
"PG-MH_ELECTRICAL", "PG-MH_VARIATION", "PG-MH_MONTHLY_CASHFLOW", "CLIENT_COVER", _
"CLIENT_SUMMARY", "CLIENT_ISSUES")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FilePathandName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
ThisWorkbook.Sheets("Dashboard").Select
End Sub
The problem is that the PDF file is not created with the sheets in order which I have specified in the array. They are in the order which they appear in the Workbook (Left to right). It correctly only includes the sheets I want but not in the order i want.
I dont want to change the order of the sheets in the Workbook either because it is setup in a specific, progressive way.
Can anyone help me with code which will allow me to be specific with the order of the sheets when the document is published?
Any help would be greatly appreciated.
I agree with #SiddharthRout in first idea/comment below the question. However, in quite similar situation when I print complicated PowerPoint presentation I use
PDFCreator application
At the first step I run that software and set 'stop printing' option. Than you could send to that software (in the way you print worksheet) each worksheet separately which would be separate document stacked in the list in the right order at the beginning. Using special feature you can match them into one document then and print it. It's very useful and quite reliable solution.
Here is some sample VBA code how copy the current workbook into a temp file and reorder a list of sheets. Use such a routine before printing:
Sub CopyAndReorder()
Dim wbCopy As Workbook
ThisWorkbook.SaveCopyAs "C:\TEMP\XXXX.XLS"
Set wbCopy = Workbooks.Open("C:\TEMP\XXXX.XLS")
ReorderSheets wbCopy
End Sub
Sub ReorderSheets(wb As Workbook)
Dim shNames As Variant, shName As Variant, sh As Worksheet
shNames = Array("Table3", "Table2", "Table1")
For Each shName In shNames
Set sh = wb.Sheets(shName)
sh.Move After:=wb.Sheets(wb.Sheets.Count)
Next
End Sub
(You have to adapt this code snippet to your needs, of course, use a better temp file name, delete the new file afterwards, provide the list of sheets from outside, etc, but I think you get the idea).

Only allow saving to PDF in Excel 2007/2010

Is there any way to force excel to always print a file in PDF format? For some reason the standard code I found (on this site and others) doesn't seem to work.
Here's the code I'm using:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
cFileName, Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
I've got a simple Input box to capture the file name, and I'd like to prevent them from doing anything else. Ideally, I'd like to put this code into my BeforeSave event and my BeforePrint event so that the only thing they can do is print to PDF. Is this possible?
A long time ago I used the opensource PDFPrinter in combination with Excel. Here is some of the code I wrote that seems to do what you want. Maybe you can use this as a start for your own solution?
'Print the saved file as a pdf in the same directory
KTCurrentFilePath = ActiveWorkbook.Path 'Store current FilePath
'Define Variables for PDF printjob
Dim pdfjob As Object
Dim KTPDFName As String
Dim KTPDFPath As String
Dim KTPCurrentPrinter As String
'Set Variable Values
KTPDFName = Range("MyPDFName").Value & ".pdf"
KTPDFPath = ActiveWorkbook.Path & Application.PathSeparator
KTPCurrentPrinter = Application.ActivePrinter
'Check if worksheet is empty and exit if so
If IsEmpty(ActiveSheet.UsedRange) Then Exit Sub
'Start PDF Engine
Set pdfjob = CreateObject("PDFCreator.clsPDFCreator")
On Error GoTo 0
With pdfjob
If .cStart("/NoProcessingAtStartup") = False Then
MsgBox "Can't initialize PDFCreator.", vbCritical + _
vbOKOnly, "PrtPDFCreator"
Application.ActivePrinter = KTPCurrentPrinter
Exit Sub
End If
.cOption("UseAutosave") = 1
.cOption("UseAutosaveDirectory") = 1
.cOption("AutosaveDirectory") = KTPDFPath
.cOption("AutosaveFilename") = KTPDFName
.cOption("AutosaveFormat") = 0 ' 0 = PDF
.cClearCache
End With
'Print the document to PDF
ActiveSheet.PrintOut copies:=1, ActivePrinter:="PDFCreator"
'Wait until the print job has entered the print queue
Do Until pdfjob.cCountOfPrintjobs = 1
DoEvents
Loop
pdfjob.cPrinterStop = False
'Wait until PDF creator is finished then release the objects
Do Until pdfjob.cCountOfPrintjobs = 0
DoEvents
Loop
pdfjob.cClose
Set pdfjob = Nothing
'Reset Printer to default
Application.ActivePrinter = KTPCurrentPrinter
End Sub
Regards,
Robert Ilbrink
Are you getting an error like this or running the code?
"Automation error: The object invoked has disconnected from its clients" error message in Excel 2000
If yes then have a look at the link below
http://support.microsoft.com/kb/813120
Use the code below in worksheet
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Macro1
End Sub
Add the following code in a new module
Sub Macro1()
cfilename = "C:\Users\SONY\Desktop\Book1.pdf" 'you can use the input box method to get the desired file name and location
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
cfilename, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
End Sub

Resources