Save the active open document as pdf file - vba

I have the below code that copy range cell values from excel and paste as picture in a new word document.
I want to save the active document as pdf file with name of file as value in cell "A2".
If you can help me in adding the same in the below code it would be a great help.
Sub Picture()
Dim objWord, objDoc As Object
ActiveWindow.View = xlNormalView
Range("A2:K25").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
objWord.Selection.Paste
objWord.Selection.TypeParagraph
End Sub

Try this,
Sub SaveAsPDF()
Dim objWord, objDoc As Object
Dim A2 As String
Dim Crng As Range
A2 = Range("A2")
Set Crng = Range("A2:K25")
Crng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
objWord.Selection.Paste
objWord.Selection.TypeParagraph
With objDoc
.ExportAsFixedFormat OutputFileName:= _
"C:\Users\Dave\Downloads\" & A2 & ".pdf", ExportFormat:=17, _
OpenAfterExport:=True, OptimizeFor:=0, Range:= _
0, From:=1, To:=1, Item:=0, _
IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _
0, DocStructureTags:=True, BitmapMissingFonts:= _
True, UseISO19005_1:=False
.Close saveChanges:=False
End With
objWord.Quit
Set objWord = Nothing
End Sub
Instead of using word to PDF use excel
Sub SaveAsPDFxlStyle()
Dim objWord, objDoc As Object
Dim A2 As String
A2 = Range("A2")
ActiveSheet.PageSetup.PrintArea = "$A$2:$K$25"
With ActiveSheet.PageSetup
.PrintGridlines = True
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\Dave\Downloads\" & A2 & ".pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=0
End Sub

Related

Export to pdf with range selection cell in one page

I can not export to PDF, in horizontal format all my range selection, Where am I doing wrong?
Sub Macro()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim rngeStart
Dim rngeEnd
Set rngeStart = wksht.UsedRange.Find(What:="####", LookIn:=xlValues, LookAt:=xlWhole)
Set rngeEnd = wksht.UsedRange.FindNext(After:=rngeStart)
Dim dataRange As Range
Set dataRange = wksht.Range(rngeStart, rngeEnd)
Dim wb As Workbook
Dim i As Long
For i = 1 To wksht.Range("A" & wksht.Rows.Count).End(xlUp).Row
wksht.Copy
With ActiveSheet
.Range(.Cells(1, 1), .Cells(1, rngeStart.Column - 1)).EntireColumn.Delete
.Rows("1:" & rngeStart.Row - 1).Delete
End With
This part for Export in PDF, only one page without all range selection:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=path & wksht.Range("A" & i).Value & ".pdf", _ Quality:=xlQualityStandard,
IncludeDocProperties:=True, IgnorePrintAreas:=False
ActiveWorkbook.Close
Next i
End Sub
is there a function "fit to onepage" export in pdf?
Did you try to adjust the activesheet format before pdf export ?
Please add this code in the begining of your sub Macro() :
'START FORMAT THE ACTIVE SHEET
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape 'xlPortrait
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Application.PrintCommunication = True
'END FORMAT THE ACTIVE SHEET

Export several word documents appended in a single pdf file

I have an embedded MS-Word document in an Excel Worksheet which name is SalaryPaycheck.
The MS-word document contains several linked fields to Worksheet cells.
I have update the linked cells, several times and perform updating above fields.
Then I need perform exporting the embedded MS-Word document each time the fields have updated, as PDF.
So I need all exported files are appending in a single pdf file.
I using below code:
Sub PrintIt()
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim i as Integer
ActiveSheet.OLEObjects("SalaryPaycheck").Activate
Set objWord = GetObject(, "Word.Application")
objWord.Visible = False
Set objDoc = objWord.ActiveDocument
objWord.Application.DisplayAlerts = wdAlertsNone
objWord.Application.ScreenUpdating = False
For i = 1 to 10
Range("Key").value = i
objDoc.Fields.Update
objDoc.ExportAsFixedFormat _
outputfileName:=ThisWorkbook.path & "\Results\" & "rep" & i & ".pdf" _
, exportformat:=wdExportFormatPDF _
, openafterexport:=False _
, optimizefor:=wdExportOptimizeForPrint _
, Range:=wdExportAllDocument _
, Item:=wdExportDocumentContent _
, includedocprops:=False _
, keepirm:=True _
, createbookmarks:=wdExportCreateNoBookmarks _
, docstructuretags:=True _
, bitmapmissingfonts:=True _
, useiso19005_1:=False
Next i
objWord.Quit
Set objDoc = Nothing
Set objWord = Nothing
End Sub 'Print it
How can using objDoc.SaveAs2 or objDoc.ExportAsFixedFormat (shown above) same as objDoc.PrintOut' whith 'Append:=True argument?
Or How can using .PrintOut with 'Append:=True' argument in this case (PDF) which working quietly (using OutputFileName:=path & filename and PrintToFile:=True)
As said in the other question, just append the documents in word
Sub PrintIt()
Dim objWord As Word.Application
Dim objDocTotal As Word.Document
Dim objDoc As Word.Document
Dim i As Integer
Dim strOutfile As String
Dim rg As Word.Range
ActiveSheet.OLEObjects("SalaryPaycheck").Activate
Set objWord = GetObject(, "Word.Application")
objWord.Visible = True
Set objDoc = objWord.ActiveDocument
Set objDocTotal = Documents.Add
objWord.Application.DisplayAlerts = wdAlertsNone
objWord.Application.ScreenUpdating = True
For i = 1 To 10
Range("Key").Value = i
With objDoc
.Fields.Update
.Content.Copy
End With
Set rg = objDocTotal.Content
With rg
.Collapse Direction:=wdCollapseEnd
If i > 1 Then .InsertBreak wdPageBreak
.PasteAndFormat wdFormatOriginalFormatting
End With
Next i
strOutfile = "<Path>\Salary.pdf"
objDocTotal.ExportAsFixedFormat outputfileName:= _
strOutfile, exportformat:=wdExportFormatPDF, _
openafterexport:=False, optimizefor:=wdExportOptimizeForPrint, Range:= _
wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent
objDocTotal.Close False
objWord.Quit
Set objDoc = Nothing
Set objWord = Nothing
End Sub

How to set fixed margins on Excel VBA code (PDF is printing in 2 pages instead of 1)

I have an Excel file which has a button "Generate PDF" that runs a macro to print a certain sheet (lets call it "QUOTE") into a PDF. This sheet is shown to be well limited in margins and in my computer the created PDF has the perfect structure: everything is well included in 1 page. However, in some other computers, when the PDF is created, everything does not fit into 1 page and a 2nd page is created with a bit of content. Here is the code (including the attempts to fix this problem by limiting the margins):
Sub Excel_Export_Proposal()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim wsCOTIZACION As Worksheet
Dim Proposalname As String
Dim iVis As XlSheetVisibility
Dim xlName As Excel.Name
Dim FolderPath As String
Dim myRange As String
Set wsQUOTE = ThisWorkbook.Sheets("QUOTE")
FolderPath = ActiveWorkbook.Path & "\"
Proposalname = "Quote for " & CStr(Range("B2").Value)
wsQUOTE.PageSetup.PrintArea = myRange
With wsQUOTE.PageSetup
.FitToPagesTall = 1
.FitToPagesWide = False
.Zoom = False
.LeftMargin = Application.InchesToPoints(0.7)
.RightMargin = Application.InchesToPoints(0.4)
.BottomMargin = Application.InchesToPoints(0.75)
.TopMargin = Application.InchesToPoints(0.75)
End With
'Proposal
Application.ScreenUpdating = False
wb.Unprotect
With wsQUOTE
iVis = .Visible
.Visible = xlSheetVisible
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ActiveWorkbook.Path & "\" & Proposalname & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=True
.Visible = iVis
wsQUOTE.Activate
End With
wb.Protect
Application.ScreenUpdating = True
End Sub
Can somebody help me fixing this problem? I would like that the sheet would we printed perfectly regardless of the computer or software in which is generated...
In order to have the procedure Excel_Export_Proposal including the PrintingArea in one page always the following adjustments should be applied:
Set the printing area correctly:
This line sets the printing area: wsQUOTE.PageSetup.PrintArea = myRange
However no value is assigned to the variable myRange before this line, therefore the PrintArea is set to "" which is equivalent to setting it to the entire UsedRange of the wsQUOTE sheet.
To ensure that the entire PrintArea is printed in one page the FitToPagesTall and FitToPagesWide must be set to 1
Replace .FitToPagesWide = False with .FitToPagesWide = 1
And remove .Zoom = False as it has not effect after setting FitToPagesTall and FitToPagesWide to 1
To ensure that the ExportAsFixedFormat method uses the print areas as defined in the target excel file set the IgnorePrintAreas parameter to False.
Replace this line IgnorePrintAreas:=True, _ with this line IgnorePrintAreas:=False, _
Below is the revised procedure:
Sub Excel_Export_Proposal_Revised()
Dim wb As Workbook, wsQuote As Worksheet
Dim myRange As String, Proposalname As String, FolderPath As String
Dim iVis As XlSheetVisibility
Set wb = ThisWorkbook
Set wsQuote = wb.Sheets("QUOTE")
FolderPath = wb.Path & "\"
Proposalname = "Quote for " & wsQuote.Range("B2").Value2
'Update myRange with the address of the range to be printed
myRange = "$B$2:$O$58" 'Change as required
Application.ScreenUpdating = False
With wsQuote.PageSetup
.PrintArea = myRange
.FitToPagesTall = 1
.FitToPagesWide = 1 'Set FitToPagesWide to 1
.LeftMargin = Application.InchesToPoints(0.7)
.RightMargin = Application.InchesToPoints(0.4)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
End With
'Proposal
wb.Unprotect
With wsQuote
iVis = .Visible
.Visible = xlSheetVisible
.Activate
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=FolderPath & Proposalname & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
.Visible = iVis
End With
wb.Protect
Application.ScreenUpdating = True
End Sub
See following pages for additional information on the resources used:
Worksheet.ExportAsFixedFormat Method (Excel)
PageSetup Object (Excel)

Save as PDF hidden and protected by password EXCEL sheet

I was using this code to save as PDF a hidden worksheet and it was working perfectly:
Sub Cite()
Dim wb As Excel.Workbook
Dim Proposalname As String
Dim iVis As XlSheetVisibility
Dim xlName As Excel.Name
Dim FolderPath As String
Set wb = ActiveWorkbook
FolderPath = ActiveWorkbook.Path & "\"
Proposalname = "Cite for " & CStr(Range("B2").Value)
'Proposal
Application.ScreenUpdating = False
With Worksheets(2)
iVis = .Visible
.Visible = xlSheetVisible
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ActiveWorkbook.Path & "\" & Proposalname & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=True
.Visible = iVis
Worksheets(2).Activate
End With
Application.ScreenUpdating = True
End Sub
However, now I protected this hidden sheet with a password so people can't unhide it. After doing this, I am not able to generate the PDF like it was working before. I tried to use the command "Unprotect password" and also did not work, it keeps saying that something is wrong with the line ".Visible = xlSheetVisible". Can somebody help me solving this problem please?
You must unprotect the workbook as well as the worksheet in order to change the visible property of a worksheet
EDIT:
wb.unprotect "Your password here"
With Worksheets(2)
iVis = .Visible
.Visible = xlSheetVisible
more code here
End With
wb.protect "Your password here"
Application.ScreenUpdating = True

Copying Multiple Versions of the same Excel Page into one PDF

I have a one page excel file that changes based on a drop down selection. I need to be able to export each data set into one PDF. So, I am looking for a macro that would loop through each selection in the drop down menu and have each of those data sets save into a multi page PDF file.
My thought would be to create the loop and have each version saved as a temporary worksheet. Then I could use
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
to save all the sheets as one PDF but then I would need to delete all the temp files.
Thanks,
Chris
I suggest exporting them all individually to PDF into a temp directory, stitching them together using Adobe's COM automation library (assuming you have Pro), then deleting the temp folder.
Public Sub JoinPDF_Folder(ByVal strFolderPath As String, ByVal strOutputFileName As String)
On Error GoTo ErrHandler:
Dim AcroExchPDDoc As Object, _
AcroExchInsertPDDoc As Object
Dim strFileName As String
Dim iNumberOfPagesToInsert As Integer, _
iLastPage As Integer
Set AcroExchPDDoc = CreateObject("AcroExch.PDDoc")
Dim strFirstPDF As String
' Get the first pdf file in the directory
strFileName = Dir(strFolderPath + "*.pdf", vbNormal)
strFirstPDF = strFileName
' Open the first file in the directory
If Not (AcroExchPDDoc.Open(strFolderPath & strFileName)) Then
Err.Raise 55555, "JoinPDF_Folder", "Could not open PDF for joining"
End If
' Get the name of the next file in the directory [if any]
If strFileName <> "" Then
strFileName = Dir
' Start the loop.
Do While strFileName <> ""
' Get the total pages less one for the last page num [zero based]
iLastPage = AcroExchPDDoc.GetNumPages - 1
Set AcroExchInsertPDDoc = CreateObject("AcroExch.PDDoc")
' Open the file to insert
If Not (AcroExchInsertPDDoc.Open(strFolderPath & strFileName)) Then
Err.Raise 55555, "JoinPDF_Folder", "Could not open PDF for joining"
End If
' Get the number of pages to insert
iNumberOfPagesToInsert = AcroExchInsertPDDoc.GetNumPages
' Insert the pages
AcroExchPDDoc.InsertPages iLastPage, AcroExchInsertPDDoc, 0, iNumberOfPagesToInsert, True
' Close the document
AcroExchInsertPDDoc.Close
' Delete the document
Kill strFolderPath & strFileName
' Get the name of the next file in the directory
strFileName = Dir
Loop
' Save the entire document as the strOutputFileName using SaveFull [0x0001 = &H1]
If Not (AcroExchPDDoc.Save(PDSaveFull, strOutputFileName)) Then
Err.Raise 55556, "JoinPDF_Folder", "Could not save joined PDF"
End If
End If
' Close the PDDoc
AcroExchPDDoc.Close
Kill strFolderPath & strFirstPDF
CallStack.Pop
Exit Sub
ErrHandler:
GlobalErrHandler
End Sub
Here was my solution:
Sub LoopThroughDD()
'Created by Chrismas007
Dim DDLCount As Long
Dim TotalDDL As Long
Dim CurrentStr As String
TotalDDL = Sheets("Report").DropDowns("Drop Down 10").ListCount
'Loops through DropDown stores
For DDLCount = 1 To TotalDDL
Sheets("Report").DropDowns("Drop Down 10").Value = DDLCount
CurrentStr = "Report" & DDLCount
'Creates a copy of each store and pastes them in a new worksheet
Sheets.Add(After:=Sheets(Worksheets.Count)).Name = "Report" & DDLCount
Sheets("Report").Columns("D:V").Copy
Sheets(CurrentStr).Columns("A:S").Insert Shift:=xlToRight
Sheets(CurrentStr).Range("A1:S98").Select
Selection.Copy
Sheets(CurrentStr).Range("A1:S98").Select
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Sheets(CurrentStr).PageSetup.PrintArea = "$A$1:$S$98"
'Sets worksheet to one page
With Sheets(CurrentStr).PageSetup
.LeftMargin = Application.InchesToPoints(0.5)
.RightMargin = Application.InchesToPoints(0.5)
.TopMargin = Application.InchesToPoints(0.5)
.BottomMargin = Application.InchesToPoints(0.5)
.HeaderMargin = Application.InchesToPoints(0)
.FooterMargin = Application.InchesToPoints(0)
.FitToPagesWide = 1
.FitToPagesTall = 1
.Zoom = False
.CenterHorizontally = True
.CenterVertically = True
End With
Next DDLCount
'Because only visable worksheets will be captured on PDF dump, need to hide temporarily
Sheets("Report").Visible = False
Dim TheOS As String
Dim dd As DropDown
'Going to name the file as the rep name so grabbing that info here
Set dd = Sheets("Report").DropDowns("Drop Down 2")
TheOS = Application.OperatingSystem
'Select all visible worksheets and export to PDF
Dim ws As Worksheet
For Each ws In Sheets
If ws.Visible Then ws.Select (False)
Next
If InStr(1, TheOS, "Windows") > 0 Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & dd.List(dd.ListIndex), Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & ":" & dd.List(dd.ListIndex), Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
End If
'Unhide our original worksheet
Sheets("Report").Visible = True
TotalDDL = Sheets("Report").DropDowns("Drop Down 10").ListCount
'Delete all temp worksheets
For DDLCount = 1 To TotalDDL
CurrentStr = "Report" & DDLCount
Application.DisplayAlerts = False
Sheets(CurrentStr).Delete
Application.DisplayAlerts = True
Next DDLCount
DDLCount = Empty
End Sub