Sheets("Key Indicators").ExportAsFixedFormat Type:=xlTypePDF,
Filename:=ArchivePath, Quality:=xlQualityStandard,
IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Currently this is what I have.
I understand how to ExportAsFixedFormat PDF but what I need to know how to do is to access the Create PDF function under Acrobat (As show in the picture below) using VBA. If I do ExportAsFixedFormat the links get flattened. Acrobat "Create PDF" would allow me to convert an Excel to PDF with hyperlinks included.
How would I do that?
I am using Excel 2016 and Adobe Pro DC
These are my adobe references
Sub PDF()
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\PCNAME\Documents\Book1.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Please try the above codes
Acrobat Reference should work
Here is the guide from Adobe
Once added, you may use the following code
Tip: It may lead you to correct coding -I'm not quite sure since I coded it "blindly" because I don't have Acrobat in my PC-. Debug step by step to see what's doing.
Sub ExportWithAcrobat()
Dim AcroApp As Acrobat.CAcroApp 'I'm not quite sure it's needed since we are creating the doc directly
Dim AcrobatDoc As Acrobat.CAcroPDDoc
Dim numPages As Long
Dim WorkSheetToPDF As Worksheet
Const SaveFilePath = "C:\temp\MergedFile.pdf"
Set AcroApp = CreateObject("AcroExch.App") 'I'm not quite sure it's needed since we are creating the doc directly
Set AcrobatDoc = CreateObject("AcroExch.PDDoc")
'it's going to be 0 at first since we just created
numPages = AcrobatDoc.GetNumPages
For Each WorkSheetToPDF In ActiveWorkbook.Worksheets
If AcrobatDoc.InsertPages(numPages - 1, WorkSheetToPDF, 0, AcrobatDoc.GetNumPages(), True) = False Then 'you should be available to work with the code to see how to insert the sheets that you want in the created object ' 1. If Part1Document.InsertPages(numPages - 1, "ExcelSheet?", 0, AcrobatDoc.GetNumPages(), True) = False
MsgBox "Cannot insert pages" & numPages
Else ' 1. If Part1Document.InsertPages(numPages - 1, "ExcelSheet?", 0, AcrobatDoc.GetNumPages(), True) = False
numPages = numPages + 1
End If ' 1. If Part1Document.InsertPages(numPages - 1, "ExcelSheet?", 0, AcrobatDoc.GetNumPages(), True) = False
Next WorkSheetToPDF
If AcrobatDoc.Save(PDSaveFull, SaveFilePath) = False Then ' 2. If Part1Document.Save(PDSaveFull, "C:\temp\MergedFile.pdf") = False
MsgBox "Cannot save the modified document"
End If ' 2. If Part1Document.Save(PDSaveFull, "C:\temp\MergedFile.pdf") = False
End Sub
Following pages may provide better assistance: Link1, Link2
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:="N:\JKDJKDJ", _
Quality:=xlQualityStandard, IncludeDocProperties:=True,
IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
You can publish any Excel Range as a PDF using ExportAsFixedFormat. There is no need to set a refernce to Acrobat.
' Usage:
' PublishRangePDF(Thisworkbook, fileName) : Will Publish the entire Workbook
' PublishRangePDF(AvtiveSheet, fileName) : Will Publish all selected worksheets
' PublishRangePDF(Range("A1:H100"), fileName) : Will Publish Range("A1:H100")
Sub PublishRangePDF(RangeObject As Object, fileName As String, Optional OpenAfterPublish As Boolean = False)
On Error Resume Next
RangeObject.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileName, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=OpenAfterPublish
On Error GoTo 0
End Sub
Related
For generating a report, I have create pdf with bellow approach.
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
fileName:=ThisWorkbook.path & "\rep.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
In the ActiveSheet, there were specified Print Area, Witch contains a Table, so table's column filtered value have change programmatically, and need:
I want new face of the print area that reforms by changing filtering criteria; get appends at the end of initial pdf file quietly, without creating a new pdf file, in a new page section.
How can I do that?
I have installed ADOBE Acrobat Professional on my system and able to add appropriate references in VBA references.
You just need the "Acrobat" library.
One simple solution is to use the native ExportAsFixedFormat method to save each section as a separate PDF file first, e.g. "C:\temp\Part1.pdf" and "C:\temp\Part2.pdf"
Then use the InsertPages method in the Acrobat API as per example below:
Sub MergePDF()
Dim AcroApp As Acrobat.CAcroApp
Dim Part1Document As Acrobat.CAcroPDDoc
Dim Part2Document As Acrobat.CAcroPDDoc
Dim numPages As Integer
Set AcroApp = CreateObject("AcroExch.App")
Set Part1Document = CreateObject("AcroExch.PDDoc")
Set Part2Document = CreateObject("AcroExch.PDDoc")
Part1Document.Open ("C:\temp\Part1.pdf")
Part2Document.Open ("C:\temp\Part2.pdf")
' Insert the pages of Part2 after the end of Part1
numPages = Part1Document.GetNumPages()
If Part1Document.InsertPages(numPages - 1, Part2Document,
0, Part2Document.GetNumPages(), True) = False Then
MsgBox "Cannot insert pages"
End If
If Part1Document.Save(PDSaveFull, "C:\temp\MergedFile.pdf") = False Then
MsgBox "Cannot save the modified document"
End If
Part1Document.Close
Part2Document.Close
AcroApp.Exit
Set AcroApp = Nothing
Set Part1Document = Nothing
Set Part2Document = Nothing
MsgBox "Done"
End Sub
Reference: http://www.khk.net/wordpress/2009/03/04/adobe-acrobat-and-vba-an-introduction/
Adobe Developer Guide: http://www.adobe.com/devnet/acrobat/pdfs/iac_developer_guide.pdf
Adobe API Reference:
http://www.adobe.com/devnet/acrobat/pdfs/iac_api_reference.pdf
In the Solution, I provide there is no need of Acrobat Pro.
We suppose that we have a table which named: Table2.
We have also a help sheet(to store filtered tables) which is Hiden and named: Help.
Option Explicit
Sub print_to_pdf()
Dim sh As Long
Dim rg As Range
Dim Rng As Range
Dim rw As Range
Application.ScreenUpdating = False
For Each rw In Range("Table2[#All]").Rows
If rw.EntireRow.Hidden = False Then
If Rng Is Nothing Then Set Rng = rw
Set Rng = Union(rw, Rng)
End If
Next
Rng.Copy
With Sheets("help")
.Visible = True
sh = .Cells(Rows.Count, "A").End(xlUp).Row + 2
Set rg = Range("a3" & ":" & "a" & sh - 2)
.Activate
.Cells(sh, "A").Select
ActiveSheet.Paste
ActiveSheet.PageSetup.PrintArea = rg
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\rep.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
.Visible = False
End With
Application.ScreenUpdating = True
MsgBox "Your PDF Has been Created with Success!!", vbInformation
End Sub
Helllo everyone. I have created a macro to export some templates I've built in excel. The range of the templates are A1:T79. I set up the code below to take that range and turn it into a PDF document (which works fine).
The problem is that the pdf document it creates has a huge margin of space on the right hand side. I want the the columns (A through T) to FULLY populate the page width end to end (doesn't matter about how many pages that adjusts to in length).
I've tried a number of things and looked at some related links on this website but none have worked (which is why i'm asking again as opposed to responding to an old post over a year old!). Any help would be greatly appreciated. Code is below. Let me know if I've not explained anything properly and I will respond below. Thanks! :)
Sub PDF_Gen()
'Set Page Area. My attempt at trying to fix the page width which doesn't work
With ActiveSheet.PageSetup
.PrintArea = ActiveSheet.Range("A1:T79")
.Orientation = xlPortrait
.FitToPagesWide = 1
.Zoom = False
End With
'Convert to PDF and save document in C drive
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\template1.pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
This has fixed itself now bizarrely. I've just set the Page Break Preview range and it has worked this time, so i'm not going to ask any questions and just accept it! This is the code i'm going with
Sub PDF_Gen()
Dim Title As String
'Set Page Break Preview area
ActiveWindow.View = xlPageBreakPreview
ActiveSheet.PageSetup.PrintArea = "$A$1:$T$79"
'Convert to PDF and save in C drive
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\template1.pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
I am encountering a problem when I am attempting to print an Excel worksheet. I have a sub that calls two other subs, see below:
Sub AutoGen_NOW()
Application.Calculation = xlCalculationAutomatic
autoGen_refresh
autoGen_invoiceStageGen
End Sub
The subs called are
1. autoGen_refresh
2. autoGen_invoiceStageGen
The first sub called refreshes a workbook connection, while the second sub prints a worksheet that references the connection. My problem is, even though the printing sub occurs after the refresh sub, the printing sub prints the worksheet as it appeared before the refresh, not with the new data. When i look at the worksheet manually, after the print, it contains the new data.
Any help on this is much appreciated. I have added the two subs below:
Sub autoGen_refresh()
Dim LastAnnual As WorkbookConnection
Dim LastMonthly As WorkbookConnection
Dim oledbCn As OLEDBConnection
Set LastAnnual = ThisWorkbook.Connections("Staging_AnnualLastEntry")
Set LastMonthly = ThisWorkbook.Connections("Staging_MonthlyLastEntry")
'Refresh Annual Connection if Annual is selected - Refresh Monthly Connection if Monthly is selected
If MonthForm.OptionButton16.Value = True Then
LastAnnual.Refresh
Else
LastMonthly.Refresh
MonthlyTemp
MonthlyHide
End If
End Sub
Sub autoGen_invoiceStageGen()
Dim FolderPath As String
Dim sourceSheet As Worksheet 'This is the Worksheet where the data connection is
Dim i As Long
'Dim template worksheets
Dim annualRateWS As Worksheet
Dim annualPSFWS As Worksheet
Dim annualFlatWS As Worksheet
Dim monthlyRateWS As Worksheet
'Set template Worksheets
Set annualRateWS = Worksheets("00_ComRate_Template")
Set annualPSFWS = Worksheets("00_PSF_Template")
Set annualFlatWS = Worksheets("00_FlatAmount_Template")
Set monthlyRateWS = Worksheets("00_MONTHLYTEMPLATE")
'Set sourceSheet to Annual or Monthly table based on user input
Select Case MonthForm.OptionButton16.Value
Case "True"
Set sourceSheet = ThisWorkbook.Worksheets("Annual_InvoiceGen")
Case "False"
Set sourceSheet = ThisWorkbook.Worksheets("Monthly_InvoiceGen")
End Select
'Set path of directory all invoices are saved too
FolderPath = ("P:\Regis Profiles\00_MerchantDB\XX_TempDump\")
'Code used to stop screen flashing during macro operation -- This is set back to true after loop
Application.ScreenUpdating = False
'ANNUAL COMMISSION RATE - PDF GENERATION
If MonthForm.OptionButton16.Value = "True" And MonthForm.OptionButton7.Value = "True" Then
annualRateWS.Visible = True
annualRateWS.Activate
ThisWorkbook.Connections("Staging_AnnualLastEntry").Refresh
annualRateWS.Calculate
Workbook_BeforePrint (False)
'Application.Wait (Now + TimeValue("0:00:03"))
For i = 32 To 43 'This Code Hides All Calculation Years that are out of range*****
ActiveSheet.Rows(i).Hidden = (ActiveSheet.Cells(i, 5).Value = 0)
Next i
annualRateWS.Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & ThisWorkbook.Worksheets("REF_InvoiceGen").Range("$B$2").Value & Format(Now(), "yyyymmddhhmmss"), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
annualRateWS.Visible = False
End If
'ANNUAL COMMISSION PSF - PDF GENERATION
If MonthForm.OptionButton16.Value = True And MonthForm.OptionButton8.Value = "True" Then
annualPSFWS.Visible = True
annualPSFWS.Activate
ThisWorkbook.Connections("Staging_AnnualLastEntry").Refresh
annualPSFWS.Calculate
'Application.Wait (Now + TimeValue("0:00:03"))
annualPSFWS.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & ThisWorkbook.Worksheets("REF_InvoiceGen").Range("$B$2").Value & Format(Now(), "yyyymmddhhmmss"), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
annualPSFWS.Visible = False
End If
'ANNUAL FLAT AMOUNT = PDF GENERATION
If MonthForm.OptionButton16.Value = True And MonthForm.OptionButton9.Value = "True" Then
annualFlatWS.Visible = True
annualFlatWS.Activate
ThisWorkbook.Connections("Staging_AnnualLastEntry").Refresh
annualFlatWS.Calculate
'Application.Wait (Now + TimeValue("0:00:03"))
annualFlatWS.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & ThisWorkbook.Worksheets("REF_InvoiceGen").Range("$B$2").Value & Format(Now(), "yyyymmddhhmmss"), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
annualFlatWS.Visible = False
End If
'MONTHLY COMMISSION RATE - PDF GENERATION
If MonthForm.OptionButton16.Value = "False" And MonthForm.OptionButton7.Value = "True" Then
monthlyRateWS.Visible = True
monthlyRateWS.Activate
monthlyRateWS.Calculate
MonthlyTemp
MonthlyHide
'Application.Wait (Now + TimeValue("0:00:03"))
monthlyRateWS.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & ThisWorkbook.Worksheets("REF_InvoiceGen").Range("$B$2").Value & Format(Now(), "yyyymmddhhmmss"), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
monthlyRateWS.Visible = False
End If
sourceSheet.Visible = False
'Code used to set screen updating BACK TO True
Application.ScreenUpdating = True
End Sub
Tim Williams solved the problem. Background refresh was enabled on the connections. After disabling this, everything worked properly.
The below code generates a PDF file from a dynamic array of sheets. The second code sets the print area and print titles on the individual sheets of interest. Some of the sheets have multiple, discontinuous regions set to print.
Worksheets(sSheetsArray).Select
sFilename = "L:\[FilePath]" & Format(Now, "DD-MMM-YY-HH-MM") & "2.pdf"
Debug.Print sFilename
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=sFilename, _
Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
Sub to set print areas etc.
Sub SetWorksheetPrintArea(ws As Worksheet, sPrintAreas As String, sTitleRange As String, bLandscape As Boolean)
With ws.PageSetup
.PrintArea = sPrintAreas
.PrintTitleRows = sTitleRange
If bLandscape Then .Orientation = xlLandscape Else .Orientation = xlPortrait
.Zoom = False
.FitToPagesWide = 1
End With
End Sub
This works, however, I need to have one sheet produce pages side by side in the PDF. This should be similar to the way it would be presented on paper if set to booklet printing. Does anyone know how this could be done without re-arranging the layout of the sheet?
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