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
Related
Can you help me with this problem
I was making a macro to save the file as pdf in excel for a certain range of objects but face a runtime error
I got an error stating:
Runtime error 1004:
"Document Not Saved or maybe open or an error occurred while saving."
below is the code of it:
Sub AntigenReportSlip()
Sheets("AntigenReportSlip").Select
Dim filename As String
Dim ChDir As String
filename = Range("E9")
ChDir = "D:\New Lab Report\AntigenReports\"
Sheets("AntigenReportSlip").Range("$A$1:$U$33").ExportAsFixedFormat Type:=xlTypePDF,
filename:= _
ChDir & filename & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False,
openAfterPublish:=True
End Sub
As far as I know, Excel's Range class does not have a ExportAsFixedFormat method. However, Workbook class does.
This should help you
Sub AntigenReportSlip()
' Make sure this folder already exists
Dim OutputFolder As String
OutputFolder = "D:\New Lab Report\AntigenReports\"
' Get filename from E9 cell
Dim filename As String
filename = Sheets("AntigenReportSlip").Range("E9").value
' Compute full filename.
' Note: You should always store fullpath on a variable before using it.
Dim fullFilename As String
fullFilename = OutputFolder & filename
' Select cells range you would like to export
Sheets("AntigenReportSlip").Range("$A$1:$U$33").Select
' Export selected range to PDF e present it
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, filename:=fullFilename, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, openAfterPublish:=True
End Sub
For further detailon ExportAsFixedFormat method, check https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.exportasfixedformat
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
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 :)
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!
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.