I am looking for some help to solve a save to PDF problem. I have a sheet with some information that prints on 2 pages. The information displayed on this sheet is controlled by a drop down option to select 1 of several hundred options. I have a print to PDF function working fine for a single view of the information displayed so I select 1 option using the drop down and click the save to PDF button which all works great.
I need to add a 2nd function that will loop through all of the options available in the drop down box and add all of this into a single PDF to be saved. I can handle all of the standard code in the loop but how do I build up the PDF file inside the loop. I know how to build an array of sheets to export to a single PDF but this kind of 'in loop' function is something I am struggling to find an answer to.
Can anyone help please? If you need any more info, please just ask.
Thanks
In the Solution, 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
You can append data in Help sheet then export pdf.
Ref: https://stackoverflow.com/questions/
Related
I am currently working on a VBA code that does the following:
1.Copies a ticker from one sheet to another (same workbook)
The sheet where the ticker is copied to should be refreshed and populated by bloomberg
That sheet is exported as a PDF
Do the same process while there are no more tickers in the first sheet.
I am having issues, because the code that I created does not seem to work properly with the Bloomberg. The iteration works well, so does the export to PDF part. However, while the loop is going, there is not enough time for Bloomberg to refresh the sheet I want to export. I end up with three sheets out of four with N/As instead of the correct data.
Here is what I have so far
Public Sub RefreshStaticLinks()
Call Worksheets("M").UsedRange.Select
Call Application.Run("RefreshCurrentSelection")
Call Application.OnTime(Now + TimeValue("00:01:00"), "M_PDF")
End Sub
Sub Mosaic_PDF()
Dim File_Path As String
Dim File_Name As String
Dim ReportTic As String
Dim Rng As Range, cl As Range
Set Rng = Worksheets("Set_up").Range("A2:A300")
With Worksheets("Mosaic")
For Each cl In Rng
If cl <> "" Then
Sheets("Mosaic").Range("G3") = cl
With Worksheets("Mosaic")
Call Application.Run("RefreshStaticLinks")
End With
File_Path = "N:\DATA\EQTY\EQFUND\SI\Projects\Standard Reporting\PDF Reports\Mosaic Fundamental Positioning\"
File_Name = "Fundamental Positioning Summary "
ReportTic = Format(ActiveWorkbook.Sheets("Mosaic").Range("G3").Text)
'Exports to pdf
With ActiveWorkbook
With Sheets(Array("Mosaic")).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=File_Path & File_Name & ReportTic & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End With
End With
End If
Next cl
End With
End Sub
I created a VBA macro to export specific sheets of a workbook to a PDF. Simple enough. The problem that I am experiencing is that my code only selects part of Sheet4, so in my PDF part of the sheet is missing.
Sheet4 contains data in range A1:W80. However, when running the code below only the range A1:W75 is selected for printing. I have confirmed my PrintArea contains the entire page. Everything even looks great when printing.
I have searched endlessly for a solution, with no success. Could this be a page-layout setting issue? How can I ensure I am selecting the entire sheet, instead of only part of it, when exporting to PDF?
Here is my code:
Sub SaveReportPDF()
Dim filepath As String
filepath = "ABC"
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")).Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=filepath, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
As good practise, you can set your used range of each sheet as the print area, and fit it to the page, using the following sub:
Sub ScaleForPrinting()
Dim sh As Worksheet
' Stop PrintCommunication for speed
Application.PrintCommunication = False
' Cycle through each sheet
For Each sh In ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4"))
' Set print area to used range of sheet
sh.PageSetup.PrintArea = sh.UsedRange
' Remove zoom, scale sheet to fit 1 page
With sh.PageSetup
.CenterHorizontally = True
.CenterVertically = True
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Next sh
' Enable PrintCommunication to apply settings
Application.PrintCommunication = True
End Sub
Then you will want to use the ActiveSheet object after selecting, rather than the Selection object. This is perhaps counter-intuitive, but you want to print the sheets not what you've selected in the sheets.
So:
ScaleForPrinting
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=filepath, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
' Deselect sheets to avoid nasty multiple sheet accidental editing!
ThisWorkbook.Sheets("Sheet1").Select
I've been trying to get an easy printout (in PDF using a single button) of one sheet with only active range and one chart located in another sheet. I've got everything working, except after I print, both sheets are grouped together and I can't edit my chart.
I'm trying to make this foolproof and easy for coworkers during real time operations. Right now I can right-click and select 'Ungroup sheets' to fix it, but I hate to have to do that each time (or explain that it needs to be done).
I tried to select a sheet, a different sheet, only one sheet etc. I can't figure out how to get VBA to ungroup the sheets at the end. Any ideas?
Sub CustomPrint()
'if statement to ask for file path
If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
& Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then
If FixedFilePathName = "" Then
'Open the GetSaveAsFilename dialog to enter a file name for the PDF file.
FileFormatstr = "PDF Files (*.pdf), *.pdf"
fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _
Title:="Create PDF")
'If you cancel this dialog, exit the function.
If fname = False Then Exit Sub
Else
fname = FixedFilePathName
End If
'Dynamic reference to RT drilling data
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Dim sht As Worksheet
Set sht = Worksheets("rt drilling data")
Set StartCell = Range("A1")
'Refresh UsedRange
Worksheets("rt drilling data").UsedRange
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Select Range
sht.Range("A1:K" & LastRow).Select
Sheets("Chart Update").Activate
ActiveSheet.ChartObjects(1).Select
ThisWorkbook.Sheets(Array("chart update", "RT drilling data")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=fname, IgnorePrintAreas:=False
'If the export is successful, return the file name.
If Dir(fname) <> "" Then RDB_Create_PDF = fname
End If
If OverwriteIfFileExist = False Then
If Dir(fname) <> "" Then Exit Sub
End If
On Error GoTo 0
Worksheets("ws model updates").Select
End Sub
If Dir(fname) <> "" Then Exit Sub will bypass Worksheets("ws model updates").Select
If OverwriteIfFileExist = False Then
If Dir(fname) <> "" Then
Worksheets("ws model updates").Select
Exit Sub
End If
End If
I have some code that creates a number of sheets (by copying an existing master sheet), based on an array and then applies an auto filter.
Here is the code I am using to apply the autofilter, as you can see it is configured to apply on the sheet being activated and any cell change.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = False
ActiveSheet.AutoFilterMode = False
Range("A19").AutoFilter
Range("A19").AutoFilter Field:=1, Criteria1:=Range("F17").Value
End Sub
Private Sub Worksheet_Activate()
Application.ScreenUpdating = False
ActiveSheet.AutoFilterMode = False
Range("A19").AutoFilter
Range("A19").AutoFilter Field:=1, Criteria1:=Range("F17").Value
End Sub
My issue is that I then run some further code to save the sheets to a PDF, at which point the sheets have not been activated of changed (so hence the filter not applied)
Below is my save worksheet code:
'Code to Save PDF
Dim wks As Worksheet
Dim WksCell As Range
' Look at each cell within the range and obtain worksheet names
For Each WksCell In ActiveSheet.Range("A2:A" & iHighest).Cells
' Attempt to reference the worksheet using this name
Set wks = Excel.Worksheets(WksCell.Value)
Set rng = wks.Range("A2:F20")
pdfName = wks.Name
ChDir ActiveWorkbook.Path & "\"
fileSaveName = wks.Name
wks.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
fileSaveName _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Next
End Sub
Is there a way to force an update/activation for each of these sheets to trigger the autofilter before the export?
NB. If I click on each sheet manually before the export, it is fine.
You can add an iteration of the .Sheets collection and call the .Activate() method to execute the Worksheet_Activate() event (simulates the clicking on each tab)
Ie.
Dim sh as Worksheet
For Each sh in sheets
sh.Activate()
Next
I am trying to extract a selection of worksheets from a workbook; worksheets whose names contain the string: "STRINGY", and export those worksheets as one single pdf. The code below creates a blank pdf.
Sub Test()
Application.CutCopyMode = False
For Each sht In ActiveWorkbook.Worksheets
If InStr(1, sht.Name, "STRINGY") > 0 Then
Sheets(sht.Name).Select Replace:=False
End If
Next sht
Selection.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\File.pdf"
Any help would be greatly appreciated.
You were along the right lines, but didn't use the Selection correctly. The following should do what you need:
Option Explicit
Sub Test()
Dim arrSheets() As String
Dim sht As Worksheet
Dim i As Integer
i = 0
For Each sht In ActiveWorkbook.Worksheets
If InStr(1, sht.Name, "STRINGY") > 0 Then
ReDim Preserve arrSheets(i)
arrSheets(i) = sht.Name
i = i + 1
End If
Next sht
ThisWorkbook.Sheets(arrSheets).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\File.pdf", _
OpenAfterPublish:=True
End Sub
Basically, you need to add the sheets whose name contain your search string in an array and select them all at the same time. Then use that selection as the basis for the export to PDF.
I added the OpenAfterPublish export option so that the file opens in your PDF reader after export; it's not a requirement.
The above code has been successfully tested with Excel 2010, but can't be certain it'll work in Excel 2007 or previous. Notice that an error will occur if the PDF add-in is not currently installed. If that's the case, you can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041.