excel vba not exporting pagesetup to pdf correctly - vba

I have code which formats a worksheet to the desired setup and layout (one page wide and tall in landscape). When I run the code (part of a long macro) it formats the pagesetup correctly.
If I manually export and save it as a pdf, then it uses the correct page setup, producing a one page PDF that is in landscape. However, the same export done by VBA produces a PDF that is severalpages long and in portrait.
i can't figure out why it's doing this. i've tried various solutions such as selecting the worksheet before exporting it, but all to no avail.
Any help is appreciated.
Code looks like this:
Sub SaveAsPDF()
Sheets(ReportWsName).ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
[SaveFolderPath] & "\" & ReportWsName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
End Sub
UPDATE:
Code used to format the pagesetup (since it's rather long I am only adding the relevant section of that sub)
Private Sub CreateNewReport(ProvisionCode As String, TimeFrom As Date, TimeTo As Date)
... other code here...
'Format report to create the desired layout
With Worksheets(ReportWsName)
'Delete unnecessary data and format the rest
.Range("A:B,D:D,F:G,J:M,O:O,Q:S").Delete Shift:=xlToLeft
.Range("A:F").EntireColumn.AutoFit
.Range("C:C, E:F").ColumnWidth = 30
With .Range("G:G")
.ColumnWidth = 100
.WrapText = True
End With
'Insert standard formating header form Reporting template
.Rows("1:2").Insert
wsReportTemplate.Range("1:3").Copy .Range("A1")
.Range("A2") = "Notes Report for " & ProvisionCode & " (" & TimeFrom & " - " & TimeTo & ")"
'Insert standard formating footer form Reporting template
wsReportTemplate.Range("A6:G7").Copy .Range("A" & .UsedRange.Rows.Count + 2)
'Ensure all data is hard coded
.UsedRange.Value = .UsedRange.Value
'Format Print Area to one Page
With ActiveSheet.PageSetup
.PrintArea = Worksheets(ReportWsName).UsedRange
.Orientation = xlLandscape
.FitToPagesWide = 1
End With
End With
End Sub

I have found what seems to be the solution:
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.Orientation = xlLandscape
.Zoom = False
'.PrintArea = Worksheets(ReportWsName).UsedRange
.FitToPagesWide = 1
'.FitToPagesTall = 1
End With
Application.PrintCommunication = True
I needed to add the Application.PrintCommunication part to the equation. For whatever reason Excel would overwrite the settings I was putting if I ran the code without it.

I think the problem is that you need to add the .Zoom = False to your page setup code:
'Format Print Area to one Page
With ActiveSheet.PageSetup
.PrintArea = Worksheets(ReportWsName).UsedRange
.Orientation = xlLandscape
.FitToPagesWide = 1
.Zoom = False 'I have added this line
End With
From what I have tried this should solve it for you.
Let me know how it goes!
EDIT: Maybe you need:
'Format Print Area to one Page
With ActiveSheet.PageSetup
.PrintArea = Worksheets(ReportWsName).UsedRange
.Orientation = xlLandscape
.FitToPagesWide = 1
.FitToPagesTall = 1
.Zoom = False 'I have added this line
End With
EDIT2: What if you changed:
.PrintArea = Worksheets(ReportWsName).UsedRange
To
.PrintArea = Worksheets(ReportWsName).UsedRange.Address

Yes!!!, I have had the same problem: I was not able to export a sheet with the page Setup settings already applied on it.
Before trying the Application.PrintCommunication I tested Wait and Sleep commands without success. Finally I skipped this issue by using CopyPicture method, adding a chart page and then exporting it to pdf, but resolution in my pdf it was not fine and I was not able to play with margins.
So just add Application.PrintCommunication=false before your code , on pagesetup settings like CaptainABC says and most important: close with Application.PrintCommunication=true after the code.
Thank you for this useful post.

Related

Vba: Print an Excel sheet to multiple pdf pages

I'll try to keep this short. I'm working on a Excel project and I have to print at the end a single sheet, the problem is the printed PDF is too small, so I've looked up for it in different forums and I found out that I had to turn .FitToPagesTall = 0 In order that the excel worksheet don't get fit to one pdf page. The problem I'm struggling with now is that even if the pdf pages are bigger than before, It still small and It's making it hard to read. My idea is to print each 30 rows (for example) in a pdf page (Page1 --> Range("A1:E30"), Page2 --> Range("A31:E60").. etc, you got the idea)
Any ideas how I can do that please ?
Thanks in advance !
Update #1: Here's a screen shot of only a slice of my data range
Even if I set the .PrintArea to A:D, it still give the same result. To rephrase my request: I'm looking for a way to print different ranges in multiple pages.
thanks everyone for giving me a part out of ur time.
try to adapt the Orientation and fit the data horizontally, something like this :
With ActiveSheet.PageSetup
.PrintTitleRows = "$1:$1" 'to repeat your header on each page
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape ' or xlPortrait
.Zoom = False
.FitToPagesWide = 1 'fit to wide only
.FitToPagesTall = 0
End With
EDIT: auto-selection code added
My understanding of the question: how to print multiple selections from the same worksheet into PDF containing multiple pages (each selection = new page)
Multiple selection (ctlr) & Print Selection
Range("A1:E30, A31:E60") _
.PrintOut Copies:=1, Collate:=True 'your ranges in the quotes
'prompts user to choose destination where to save to
It is equal to manually selecting multiple ranges (holding ctrl) and selecting print selection when printing.
Edit - Code added
If you like the above idea, you might like the following code?
It constructs a string, such as: "A1:D30,A31:D60,A61:D90", which specifies ranges to be selected. Assumptions is that data is in columns A-D and last row can be found in column A. You can specify how many rows to print in my_step.
Sub select_and_print()
Dim s_rn, s_range As String
Dim i, my_step As Integer
Dim selections_count As Single
my_step = 30 'how many rows to include on 1 page
'to prevent extra page in some cases:
selections_count = WorksheetFunction.RoundUp((Cells(Rows.Count, 1).End(xlUp).Row / my_step), 0)
'String, which specifies selections in ws, between columns A - D
For i = my_step To selections_count * my_step Step my_step:
s_rn = "A" & (i - my_step + 1) & ":D" & i
If i = my_step Then
s_range = s_rn
Else
s_range = s_range + "," + s_rn
End If
Next i
'selection & print
Range(s_range).PrintOut Copies:=1, Collate:=True
End Sub
Building off #JC Guidicelli's answer, the important things I was missing was .FitToPagesTall = False. I don't know why Excel requires False and not 0, but that seems to be the way it is.
Sheets(Array("Sheet 1", "Sheet 2", "Sheet 3")).Select
With ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
End With
and in my export command, I needed IgnorePrintAreas:=True.
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=<file path>, Quality:=xlQualityStandard, IgnorePrintAreas:=True
This gives me a PDF with all the data from Sheets 1, 2, and 3, and if data from those sheets is more than a page, it splits it over multiple pages without zooming it in.

Save worksheet with graphs as PDF

I am trying to save my worksheet as a pdf file with the use of vba. The worksheet is wider than an A4 page and contains a few shapes (side to side). I want the worksheet to fit on one A4 page, so it should be rescaled as seen on screen. I am using the following code:
Sub Print_PDF()
Dim sFilename As String
Worksheets.Add.Name = "Helpsheet"
sFilename = "G:\anything\test.pdf"
ThisWorkbook.Worksheets("Newsletter").Range("A2:D81").CopyPicture xlScreen, xlBitmap
ThisWorkbook.Sheets("Helpsheet").Activate
ThisWorkbook.Sheets("Helpsheet").Paste
ActiveSheet.PageSetup.PrintArea = ThisWorkbook.Sheets("Helpsheet").Range("A1:O86")
With ActiveSheet.PageSetup
.Orientation = xlPortrait
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
ThisWorkbook.Sheets("Helpsheet").ExportAsFixedFormat Type:=xlTypePDF, Filename:=sFilename, quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
Application.DisplayAlerts = False
ThisWorkbook.Sheets("Helpsheet").Delete
Application.DisplayAlerts = True
End Sub
The code actually saves a PDF file in the expected location. However, the PDF file is 4 pages instead of the expected 1 page. So it seems that the printarea is not defined correctly. What am I doing wrong?
Have you tried adjusting your PageSetup parameters as per this example?
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.Orientation = xlLandscape
.Zoom = False
'.PrintArea = Worksheets(ReportWsName).UsedRange
.FitToPagesWide = 1
'.FitToPagesTall = 1
End With
Application.PrintCommunication = True
Think explicitly setting .Zoom to false is important.
Source:
excel vba not exporting pagesetup to pdf correctly
Assuming the activesheet is also the sheet("Helpsheet")
The print area need the address of the print range.
ActiveSheet.PageSetup.PrintArea = ThisWorkbook.Sheets("Helpsheet").Range("A1:O86").Address

Run time error 424 in excel macros

I am new to excel macros, I am working on creating a macro which needs to format the cells and also to generate the bar code for column A. Created a function Code128() to convert the string in to bar code as given in the blog and it works fine.
I am using them in the macros I am creating like below
With ActiveSheet.PageSetup
.PrintTitleRows = "$1:$1"
.PrintGridlines = True
.Orientation = xlLandscape
.PaperSize = xlPaperA4
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
End With
Columns("A").ColumnWidth = 10
For Each Target In Range("A1", Range("A" & Rows.Count).End(xlUp))
If Target.Value <> vbNullString Then
Target.Value = PERSONAL.XLSB!Code128(Target.Value)
Target.Resize(, 12).WrapText = True
Target.Font = "Code 128"
End If
Next
Next
But when I run the macro on the excel I am getting the run time error like
You should be able to use Application.Run to evaluate a function that exists in another workbook. The format of that is:
Target.Value = Application.Run("PERSONAL.XLSB!Module2.Code128", Target.Value)
Or more generally:
= Application.Run(workbookname$ & "!" & modulename & "." & functionname, args())
Barring that, you could Add a reference to Personal.xlb in your Book1.

Excel - Hiding last picture in row of invoice

I have built an Invoice worksheet that has a top portion (A1:K19) that will remain static; this is the top portion of the invoice. Below Row 19 starts the individual item lines that will be populated with what items are ordered.
I have created a macro for the user that will automatically format the invoice into a 1 page PDF and autohide the unused line item rows; however I have pictures in each line item line.
When I run my macro it hides all the pictures expect the last one. How can I hide the last image box that just sticks out and doesn't hide with row. If I individually hide that row alone it hides, but with a group it does not.
Below is the current VBA script I have written.
Sub Save_Quote_As_PDF()
Application.ScreenUpdating = False
For i = 20 To 59
If ActiveSheet.Cells(i, 3) = "" Then
ActiveSheet.Cells(i, 3).EntireRow.Hidden = True
End If
Next i
Dim PdfFilename As Variant
PdfFilename = Application.GetSaveAsFilename( _
InitialFileName:=ActiveWorkbook.Path & "\" & ActiveSheet.Range("N2").Value, _
FileFilter:="PDF, *.pdf", _
Title:="Save As PDF")
If PdfFilename <> False Then
With ActiveSheet.PageSetup
.Orientation = xlPortrait
.PrintArea = "$A$1:$K$78"
.PrintTitleRows = ActiveSheet.Rows(19).Address
.Zoom = False
.FitToPagesTall = 1
.FitToPagesWide = 1
End With
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=PdfFilename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End If
For i = 20 To 59
If ActiveSheet.Cells(i, 3) = "" Then
ActiveSheet.Cells(i, 3).EntireRow.Hidden = False
End If
Next i
Application.ScreenUpdating = True
End Sub
Here is a screenshot of the pdf section that shows the pic object showing
Screenshot of Image Not Hiding in PDF results
I recreated your code above with my own sample data. The issue seems to be when the images don't have "move and size with cells" (in their properties).
If you have code elsewhere, that's inserting those images then you'll need to do this,
Sub Move_Size()
Dim i As Long
For i = 1 To ActiveSheet.Shapes.Count
On Error Resume Next
With ActiveSheet.Shapes.Item(i)
.Placement = xlMoveAndSize
.PrintObject = True
End With
Next i
On Error Goto 0
End Sub
Taken from here

All columns of excelsheet are not fitted in same page of pdf; while converting using Excel VBA

Am trying to convert microsoft excel file with large number of columns (70+) into pdf using a Excel VBA code.
In active workbook, am trying to save 'Sheet1' to PDF format at required path. I have the following code.
Sub GetSaveAsFilename()
Dim fileName As String
fileName = Application.GetSaveAsFilename(InitialFileName:="", _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Path and FileName to save")
If fileName <> "False" Then
With ActiveWorkbook
.Worksheets("Sheet1").ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
fileName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
End If
End Sub
When am running the VBA code and saving the pdf file, I see that; the whole excelsheet is not fitted in same page. It's displaying some content in next page.
(Only few columns appear in first page, remaining appear on next page and so on..).
I checked with How to publish a wide worksheet in PDF format?.
But, setting page layout to landscape and converting excel file manually to PDF; also displays some columns in next pages.
There are many Free Excel to PDF Converters available online, which give me same results.
Is there any function available in VBA, through which I can fit all the columns in a single page of PDF?
The problem is with the Page Setup settings, I have done some minor changes to your code and added a procedure to perform the page setup settings, when launching the procedure you can select the paper size, however be aware the minimum zoom allowed is 10% (see PageSetup Members (Excel)). Therefore, if even at 10% the Print Area does not fit in one page I suggest to chose a larger paper size (i.e. A3) to generate an one page PDF, then when printing the Pdf select fit to page. The procedure also gives you the change to play with the margins, when generating PDF's I set all margins at 0, but you can changed as it fits your goals.
Sub Wsh_LargePrintArea_To_Pdf()
Dim WshTrg As Worksheet
Dim sFileName As String
sFileName = Application.GetSaveAsFilename( _
InitialFileName:="", _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Path and FileName to save")
If sFileName <> "False" Then
Rem Set Worksheet Target
Set WshTrg = ActiveWorkbook.Worksheets("Sheet1")
Rem Procedure Update Worksheet Target Page Setup
'To Adjust the Page Setup Zoom select the Paper Size as per your requirements
'Call Wsh_Print_Setting_OnePage(WshTrg, xlPaperLetter)
'Call Wsh_Print_Setting_OnePage(WshTrg, xlPaperA4)
'To Adjust the Page Setup Zoom select the Paper Size as per your requirements
'If the Print Still don't fit in one page then use a the largest Paper Size (xlPaperA3)
'When printing the Pdf you can still selet to fix to the physical paper size of the printer.
'Call Wsh_Print_Setting_OnePage(WshTrg, xlPaperA3)
'This is the largest paper i can see in my laptop is 86.36 cm x 111.76 cm
Call Wsh_Print_Setting_OnePage(WshTrg, xlPaperEsheet)
Rem Export Wsh to Pdf
WshTrg.ExportAsFixedFormat _
Type:=xlTypePDF, _
fileName:=sFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
End Sub
Sub Wsh_Print_Setting_OnePage(WshTrg As Worksheet, ePaperSize As XlPaperSize)
On Error Resume Next
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.LeftMargin = Application.InchesToPoints(0)
.RightMargin = Application.InchesToPoints(0)
.TopMargin = Application.InchesToPoints(0)
.BottomMargin = Application.InchesToPoints(0)
.HeaderMargin = Application.InchesToPoints(0)
.FooterMargin = Application.InchesToPoints(0)
'.Orientation = xlLandscape
.Orientation = xlPortrait
.PaperSize = ePaperSize
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Application.PrintCommunication = True
End Sub
First select the range you want to print and set it as PrintArea. And then run this code, this work for me with an 79 columns sheet
Sub saveAsPDF()
Dim MyPath
Dim MyFolder
With Sheet1.PageSetup
'.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.BottomMargin = 0
.TopMargin = 0
.RightMargin = 0
.LeftMargin = 0
End With
MyPath = ThisWorkbook.Path
MyFolder = Application.GetSaveAsFilename(MyPath, "PDF Files (*.pdf),*.pdf")
If MyFolder = False Then Exit Sub
Sheet1.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=MyFolder, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
add this to your code, it will force everything to print on one sheet wide, but still let it print over multiple sheets tall
With Worksheets("Sheet1").PageSetup
.FitToPagesWide = 1
.FitToPagesTall = False
End With
also set your margins to "Narrow"
The problem is that you need to Select the UsedRange and then use Selection.ExportAsFixedFormat
Sub GetSaveAsFilename()
Dim fileName As String
fileName = Application.GetSaveAsFilename(InitialFileName:="", _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Path and FileName to save")
If fileName <> "False" Then
'Selecting the Used Range in the Sheet
ActiveWorkbook.Worksheets("Sheet1").UsedRange.Select
'Saving the Selection - Here is where the problem was
Selection.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
End Sub
EDIT:
The problem was the PageSetupbecasue each page size has a maximum pixel limit as you were heading towards in your comment.
The Page Size is set to Oversize A0 which should more than cater for your 100x1500 UsedRange. Here you change the page size with the FitToPages... = 1 to check that your Range is within the print lines.
The FitToPagesWide and FitToPagesTall is to fit everything onto one page.
Sub GetSaveAsFilename()
Dim fileName As String
fileName = Application.GetSaveAsFilename(InitialFileName:="", _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Path and FileName to save")
If fileName <> "False" Then
'Suspending Communicaiton with Printer to Edit PageSetup via Scripting
Application.PrintCommunication = False
'Setting Page Setup
With ActiveSheet.PageSetup
.FitToPagesWide = 1
.FitToPagesTall = 1
' Setting Page Size to 92x92 inch Should cater for your data
.PaperSize = 159
End With
'Enabling Communicaiton with Printer
Application.PrintCommunication = True
'Selecting the Used Range in the Sheet
ActiveWorkbook.Worksheets("Sheet1").UsedRange.Select
'Saving the Selection - Here is where the problem was
Selection.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=True, OpenAfterPublish:=True
End If
End Sub
Note that the Page will appear Blank, you will need to Zoom in alot to view the data