Using Selection.ExportAsFixedFormat to generate PDF properly - excel

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?

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

Looping "Batch Export" Crashes - Processor or Code Error?

Why can't Excel loop through large datasets?!
I have 2 different document forms which need to be exported to PDF by the hundreds. I pulled the batch export script from the internet and modified it for my usage so it would process either of these forms depending on the checkbox selected on the "Batch PDF Printer" worksheet.
Everything runs well - for the first 10-15 workbooks accessed by the loop, and then it crashes. Every Excel document freezes (Not Responding) and the page that is currently accessed by the Macro partially opens with no visible data or cells. The "Publishing" message box may also freeze at this point. Once it reported a lack of memory error - but I have not been able to repeat this. Shouldn't Excel be deleting unused cache's so as to not overload the memory? I would suspect a bum loop if it didn't run well for a while. I've heard there is no way to script in a "cache dump" or something of that nature. Is it bad code, or am I asking too much of my processor?
Sub Convert2PDF()
'Update the checkbox linked formulas on the GUI workbook
Sheet1.Range("A2").Formula = Sheet1.Range("A2").Formula
Sheet1.Range("B2").Formula = Sheet1.Range("B2").Formula
Sheet1.Range("C2").Formula = Sheet1.Range("C2").Formula
Dim strFolder As String
Dim strXLFile As String
Dim strPDFFile As String
Dim wbk As Workbook
Dim lngPos As Long
' set folder
strFolder = ThisWorkbook.Path & "\putfileshere" & "\"
Application.ScreenUpdating = False
' Get first filename
strXLFile = Dir(strFolder & "*.xls*")
' Loop through Excel workbooks in folder
Do While strXLFile <> ""
' Open workbook
Set wbk = Workbooks.Open(Filename:=strFolder & strXLFile)
' Assemble the PDF filename
lngPos = InStrRev(strXLFile, ".")
strPDFFile = Left(strXLFile, lngPos) & "pdf"
' Export to PDF
'Do the next 8 lines crash the Macro because they recalculate for every sheet? Page1, Page2, Page3 value are the same for all workbooks processed in a batch
Dim Page1 As String
Dim Page2 As String
Dim Page3 As String
Dim Page4 As String
Page1 = ThisWorkbook.Sheets("Batch PDF Printer").Range("A2")
Page2 = ThisWorkbook.Sheets("Batch PDF Printer").Range("B2")
Page3 = ThisWorkbook.Sheets("Batch PDF Printer").Range("C2")
If ThisWorkbook.Sheets("Batch PDF Printer").Range("C2") = "" Then
wbk.Sheets(Array(Page1, Page2)).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\pdfsgohere" & "\" & wbk.Name, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
'run process for format option 2
Else:
wbk.Sheets(Array(Page1, Page2, Page3)).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\pdfsgohere" & "\" & wbk.Name, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
'Tried killing the finished document to improve function
Dim xFullName As String
xFullName = Application.ActiveWorkbook.FullName
ActiveWorkbook.Saved = True
Application.ActiveWorkbook.ChangeFileAccess xlReadOnly
Kill xFullName
Application.ActiveWorkbook.Close False
End If
' Close workbook - didn't seem to help (can't do it when the workbook is gone)
'wbk.Close SaveChanges:=False
' Get next filename
strXLFile = Dir
Loop
Application.ScreenUpdating = True
MsgBox "All Done"
Thanks for the help. I've been trying to figure this out for days now.
This ran for me on >30 files with no problem:
Sub Convert2PDF()
Dim strFolder As String, strXLFile As String
Dim strPDFFile As String
Dim wbk As Workbook
Dim lngPos As Long
Dim pages(1 To 4) As String
Dim shtBatch As Worksheet, arr
Set shtBatch = ThisWorkbook.Sheets("Batch PDF Printer")
shtBatch.Range("A2:C2").Calculate '<< assume this was the point of resetting the formulas?
pages(1) = shtBatch.Range("A2").Value
pages(2) = shtBatch.Range("B2").Value
pages(3) = shtBatch.Range("C2").Value
'what pages to print? Only need to do this once
arr = IIf(Len(pages(3)) = 0, Array(pages(1), pages(2)), _
Array(pages(1), pages(2), pages(3)))
strFolder = ThisWorkbook.Path & "\putfileshere\"
strXLFile = Dir(strFolder & "*.xls*")
Do While strXLFile <> ""
Set wbk = Workbooks.Open(Filename:=strFolder & strXLFile, ReadOnly:=True)
lngPos = InStrRev(strXLFile, ".")
strPDFFile = Left(strXLFile, lngPos) & "pdf"
wbk.Sheets(arr).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\pdfsgohere\" & strPDFFile, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
wbk.Close False
strXLFile = Dir
Loop
MsgBox "All Done"
End Sub
Even if your visible system RAM is not overloading, the internal capacity of the Excel application seems to be exceeded for a brief moment. I was able to finally view the message box "Not enough system resources to display completely" before the app went into automatic reboot. Try streamlining the workbooks being accessed by the loop. If your workbooks take a while to start up, that may be indication of heavy background processes (calculations and VBA subs). DoEvents may help the code run more smoothly by asking for more processing time so the system can sort it's demands. Ultimately,
Application.Calculation = xlManual
at the top of the loop was sufficient to reduce the computational demands on the 20 gig system (which I never expected to overload).
If you have linked images in your exports.
Exported linked images leaves behind a bit or byte in the kernel, which accumulates and eventually breaks excel.
I found this solution only 1 place on the internet and i cannot find it again, but it got me from 200s to 1000 loops of VBA Macro by removing linked images.
Nothing in the VBA code would help, i used pauses, save the workbook to clear memory, disable events etc...
I wrote an answer to my problem here: https://stackoverflow.com/a/53600884/10069870
Disregard if you have no linked images in your exports :)

Creating multiple PDF combined into one file from excel

I am currently using the below to create individual pdf files (each time a new value is put into C4, a new pdf with different data is generated). Is there a way that all of these pdf can be saved into one file?
Thank you in advance for your help
Q
Sub moveselection()
Dim i As Integer
For i = 1 To 108
Range("C4").Value = Sheets("Sheet1").Range("A4").Offset(i, 0).Value
ThisFile = Range("C4").Value
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="T:\Maths\QM" & _
ActiveSheet.Range("C4").Value & ".pdf", _
From:=1, _
To:=1, _
OpenAfterPublish:=False
Next i
End Sub
Rather than saving as pdf each time why not Create a new workbook before you enter the loop and then copy the active sheet to this new workbook then after the loop ends you can export the entire workbook to pdf?

Run-time error '1004': Application-defined or object-defined error

I read through a few of the existing VBA questions with this error but I find that the error message is general and there are many, many ways to get it.
My VBA code is below and I am trying to find out why all of a sudden it is not working when it used to. The lines which Excel highlights are between the 2 * which I do not actually have in the code :)
Sub publishPDF()
'
' PublishToPDF Macro
' Macro recorded 01/07/2016 by Pczarnota
' Export to PDF
SaveFolder = "S:\DataOps\InvValidatedFeed\"
DocName = Range("D1").Value
*ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=SaveFolder & DocName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False*
MsgBox ("Another one down!")
End Sub
This must have something to do with the filename in D1, the reliance on the ActiveSheet property to define the parent worksheet of D1 or an illegal filename.
Sub publishPDF()
' PublishToPDF Macro
' Macro recorded 01/07/2016 by Pczarnota
' Export to PDF
Dim saveFolder As String, docName As String
saveFolder = "S:\DataOps\InvValidatedFeed\" '<~~ access to the share or network drive?
docName = Worksheets("Sheet1").Range("D1").Value '<~~define the worksheet holding the filename!
If CBool(InStr(1, docName, Chr(46))) Then 'check for a period (full stop)
'remove it; the save type will add the appropriate one
docName = Left(docName, InStr(1, docName, Chr(46)) - 1)
End If
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=saveFolder & docName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
MsgBox ("Another one down!")
End Sub
This works for me but I did not duplicate the network share and used abc.xls in Sheet1!D1.

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).

Resources