VBA ExportAsFixedFormat only saving last active chart - vba

I'm trying to save a single worksheet from a workbook as a pdf using the ExportAsFixedFormat method:
Sheets("Overview").ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Mid(saveFile, 1, InStr(saveFile, ".")) & "pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
This worked for a while until i started doing some chart manipulation beforehand. The manipulation I am talking about looks like this:
ActiveSheet.ChartObjects("Diagramm 4").Activate
ActiveChart.SetSourceData Source:=Sheets("Measurements").Range( _
"C4:C29,G4:G29")
Now its not exporting the whole sheet as a pdf but rather only the chart called "Diagramm 4".
I more or less understand why it's doing this but I can't find a way to fix this.

You could try selecting any cell on that sheet like:
Range("A1").Select
before you export the page. Likely this is happening because you're making the chart active without making it inactive again. Look what happens when you normally select a chart and then try to print a worksheet - it'll just try to print the chart.

Related

Why is my Excel not being exported to PDF in Landscape?

Following Problem:
I have selected a range in excel and want to export it to a PDF. Given that it is quite wide and rather short, I want the pdf to be in landscape format. I've already tried this by setting the Page Layout --> Orientation to Landscape. But this does not work.
My code is as follows:
Sub Excel2PDF()
Dim BottomEquity As Range, BottomBond As Range, PDFArea As Range
Set SB = Worksheets("SalesBrokerage")
SB.Range("B2:N" & SB.Cells(SB.Rows.Count, 2).End(xlUp).Offset(1, 0).Row).Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\CustomerPrice.pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True, Orientation:=Landscape
End Sub
Any suggestions?
Bonus question: Once I have set the landscape orientation (hopefully with your help), is there a way to ensure that the selected range fills the pdf page BestFit?

How to save a WorkSheet from an Excel spreadsheet as a PDF

I'm trying to write (what I thought would be) a simple macro which will save a Worksheet (not the whole Workbook) from an Excel Spreadsheet as a PDF. I'm using Excel 2016 (15.24) on a MacBook Pro running Yosemite. I've seen lots of examples here and online.
I started out by recording a macro and edited it. It looked like this:
Sub SavePDF()
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
End Sub
This produced a PDF file but it contained all of the sheets from the Workbook. It seems that, for some reason, the PublishOption:=xlSheet although it works manually when recording the macro, does not work from VBA.
Ok. So I tried a different approach using ExportAsFixedFormat, modelling my approach on some of the examples I've seen here and elsewhere online and trying to keep it as simple as possible. Here's my version.
Sub SimplePDF()
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="pdfs/example.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Every time I try this I get a print error, followed by the dreaded run-time error 1004. BTW, does anyone know the definition of this error?
Can anyone suggest why this is not working? I'd be grateful for any advice.
On the strength of Sinan's advice below I changed the code to
Sub SavePDF()
ActiveSheet.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF
End Sub
I get the same run-time error 1004 but it gives me the extra information "SaveAs method of Worksheet class failed"
I tried David Zemens technique below of copying the active worksheet to a new Workbook and then using SaveAs on that new workbook.
Sub NSavePDF()
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
'Close the new workbook without saving it.
ActiveWorkbook.Close False
End Sub
However, this attempts to print the worksheet on my default printer rather than converting to PDF.
You are asking to save the entire workbook and that is what is happening. Instead, you can figure out which worksheet you want to save as PDF, and invoke SaveAs method on that.
See Worksheet.SaveAs instead of Workbook.SaveAs.
Saves changes to the chart or worksheet in a different file.
Syntax
expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AddToMru, TextCodepage, TextVisualLayout, Local)
expression: A variable that represents a Worksheet object.
Sub SaveSheetAsPDF()
ActiveWorksheet.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF
End Sub
If some reason that doesn't work (but Workbook.SaveAs does), you could simply copy the sheet to a new workbook containing only one sheet, and then do SaveAs on that workbook.
Sub SavePDF()
ActiveSheet.Copy '## This creates a new workbook containing only the copied sheet
'ActiveWorkbook should now be the new/copied worksheet:
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
'Close the new workbook without saving it.
ActiveWorkbook.Close False
End Sub

VBA to copy sheets without changing the format

I have a question regarding my code that somehow changes the format (row height and column width) when I copy some sheets to another workbook - this is used as a middle step before printing to pdf. In the sheets "1", "2" and "3" the sheets are set up with a print area that only cover one A4 page, but when the code copies the selected sheets to a new temporary workbook all rows and columns have increased (increased pixels) so that the print area now covers several pages. Can anyone help?
Sub Print_to_pdf()
Application.ScreenUpdating = False
Set Output_Sheets = Sheets(Array("1", "2", "3"))
Output_Sheets.Select
Output_Sheets.Copy
ChDir "XXX"
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
"XXX\Print_to_pdf".pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
ActiveWorkbook.Close savechanges:=False
Application.ScreenUpdating = True
End Sub
I still don't understand why you tried to copy those sheets. To export the sheets you could simply use this:
Sub Print_to_pdf()
Dim Output_Sheets As Sheets
Application.ScreenUpdating = False
Set Output_Sheets = Sheets(Array("1", "2", "3"))
Output_Sheets.Select
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"c:\temp\Print_to_pdf.pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
End Sub
If there are differences between the exported PDF file and any printers then this is probably due to differences in printer drivers and the PDF export engine. The only way I see to solve this playing around until it fits on both (printer and export).

VBA Exporting PDF from Excel in 2 copies

I'm looking for a solution to export couple of sheets from Excel to one file PDF. I've recorded a macro that creates nice PDF with all interesting me sheets. BUT i need 2 copies of one of the sheets in the same PDF, but I don't know how to do it.
Here is my code.
Sub ExportPDF()
Sheets(Array("PackingList", "Administracyjny", "Nadawca", "Odbiorca", "Przewoźnik")).Select
Sheets("PackingList").Activate
ChDir "C:\Users\XXXXXX\Desktop"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\XXXXXX\Desktop\Spools_PackingList.pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:= False
End Sub
See here for copying a worksheet, it might be a good workaround to copy the entire worksheet at the start of your code, and then you can just delete it at the end with (taken from here):
Sub sbDeleteASheet()
Sheet1.Delete
'OR You can mention the Sheet name
Sheets("Sheet2").Delete
End Sub

Exporting excel sheet as PDF Run-time error '5': Invalid procedure call or argument

I have a problem exporting one Excel sheet in a workbook into a PDF file.
Sub ExportPDF()
Dim Nazwa As String
' Creating a destination folder for PDF file
If Len(Dir("c:\Faktury", vbDirectory)) = 0 Then
MkDir "c:\Faktury"
End If
'InputBox that allows user to type filename
Nazwa = InputBox("Wpisz nazwę pliku", "Nazwa pliku", Sheets("Fa VAT").Range("G3"))
If Nazwa = "" Then Exit Sub
ChDir "c:\Faktury"
'Exporting sheet "Fa VAT" to PDF
Sheets("Fa VAT").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=Nazwa, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
I get the error "Run-time error '5': Invalid procedure call or argument". After that Excel highlights the last part of the code as it is supposed to be wrong. I mean exactly this part:
Sheets("Fa VAT").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=Nazwa, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
I installed Microsoft SaveAsPDF setup and nothing changes. I changed filename to some random string rather than a referring to InputBox. I tried to activate the right sheet and then export ActiveSheet. I tried with the sheet hidden and shown. I tried to run the file on two other computers.
When I copy this macro to some completely new, blank excel spreadsheet, it works.
I work on Excel 2007, Windows 10. I tried it also on Excel 2010 and Windows 7.
Here are some of the links that I tried:
Runtime Error : 5, Invalid Procedure call or argument
http://www.mrexcel.com/forum/excel-questions/595252-visual-basic-applications-trouble-save-pdf-code.html
Make sure the worksheet isn't hidden. Excel will throw an error for .ExportasFixedFormat if the worksheet is hidden or very hidden. If yours is hidden, you can unhide it first in your code:
Sheets("Fa VAT").Visible = xlSheetVisible
At the end, you can hide it again.
Sheets("Fa VAT").Visible = xlSheetHidden
I had the same error. In my case, the filepath and name given were too long. Shorten the name or path and it should work.