I am trying to reference a PIVOT table filter to use as the Save As name for generating a PDF. I cannot seem to find any combination of PIVOT table object reference to do this.
Sub Deferred_Rent_To_PDF()
Dim strWorksheet As String
Dim strPivotTable As String
Dim pdfFilename As Variant
Dim strDocName As String
Dim ptDeferredRent As pivotTable
strWorksheet = "Deferred"
strPivotTable = "DeferredRent"
Set ptDeferredRent = Worksheets(strWorksheet).PivotTables(strPivotTable)
'strDocName = ptDeferredRent. <----- THIS IS WHERE I NEED HELP
pdfFilename = Application.GetSaveAsFilename(InitialFileName:=strDocName, _
FileFilter:="PDF, *.pdf", Title:="Save As PDF")
If pdfFilename <> False Then
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=pdfFilename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End If
End Sub
Try something like this:
You are looking for field_name.CurrentPage but only if field_name.Orientation = xlPageField (i.e. filter field and not row or data or column field or hidden)
Sub Deferred_Rent_To_PDF()
Dim strWorksheet As String
Dim strPivotTable As String
Dim pdfFilename As Variant
Dim strDocName As String
Dim ptDeferredRent As PivotTable
strWorksheet = "Pivot (2)" '"Deferred"
strPivotTable = "PivotTable7" '"DeferredRent"
ThisWorkbook.Sheets(strWorksheet).Activate
Set ptDeferredRent = Worksheets(strWorksheet).PivotTables(strPivotTable)
'strDocName = ptDeferredRent. <----- THIS IS WHERE I NEED HELP
strDocName = Get_Pivot_filter_field(ptDeferredRent)
If strDocName <> "not found" Then
Debug.Print strDocName
pdfFilename = Application.GetSaveAsFilename(InitialFileName:=strDocName, _
FileFilter:="PDF, *.pdf", Title:="Save As PDF")
If pdfFilename <> False Then
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=pdfFilename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End If
End If
End Sub
Function Get_Pivot_filter_field(pvt As PivotTable)
'On Error Resume Next
Debug.Print pvt.Name
Pivot_Table_Name = pvt.Name
Debug.Print pvt.PivotFields.Count
Get_Pivot_filter_field = "not found"
For Each field_name In pvt.VisibleFields 'pvt.PivotFields
If pivot_field_active(Pivot_Table_Name, field_name) Then
With field_name
Debug.Print field_name & " " & .Orientation
If .Orientation = xlPageField Then 'xlDataField (4)' 'xlColumnField (2)' 'xlHidden (0)' 'xlPageField (3)' 'xlRowField (1)'
Debug.Print field_name & " " & .Orientation & .CurrentPage
Get_Pivot_filter_field = .CurrentPage
Else
Debug.Print field_name & " not filter field"
End If
End With
Else
Debug.Print field_name & " not active"
End If
Next
End Function
Function pivot_field_active(ByVal Pivot_Table_Name As String, ByVal strName As String) As Boolean
Dim strTemp As String
On Error Resume Next
With ActiveSheet.PivotTables(Pivot_Table_Name).PivotFields(strName)
If .NumberFormat = "$#,##0" Then
'Do nothing no error
End If
If .CurrentPage Then
Err.Clear
End If
End With
If Err = 0 Then pivot_field_active = True Else pivot_field_active = False
End Function
What I do here is loop through all pvt.VisibleFields where pvt is the pivot table you pass into the function pvt.VisibleFields(pvt)
If .Orientation = xlPageField then it is a filter field and if it is then return the .CurrentPage as the result of the function Get_Pivot_filter_field otherwise return "not found"
Then use this .CurrentPage as your PDF name.
Full example here: https://drive.google.com/file/d/1HkeJVgKeFeCuj2ItRn2s90ozy41zlCVL/view?usp=sharing
Related
Could someone sell me why I am getting a runtime error here?? I have almost this identical code in another project that works, and I cant figure out the issue.
Sub Create_PDF()
' Create and save .pdf
Dim pdfName As String
Dim myrange As String
myrange = Cells(Rows.Count, 6).End(xlUp).Address
Dim AccountNumber As String
AccountNumber = Right(A1, 3)
FullName = "P:\Public\Generated Letters\LTXN Export Spreadsheets\" & "AccountEnding" & AccountNumber & ".pdf"
'Sets the name and location for the new file
myrange = Cells(Rows.Count, 6).End(xlUp).Address
'sets the string end for the print area
With ActiveSheet.PageSetup
.PrintArea = "A1:" & myrange
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
'Setting the spreadsheet to print active content with columns fit to single page
If Dir(FullName) <> vbNullString Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & " - " & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
'###This is where I am getting the runtime error and the file is not saving###
End Sub
Sub openFolder()
'Open the folder that we save the PDF to
Call Shell("explorer.exe" & " " & "P:\Public\Generated Letters\LTXN Export Spreadsheets\", vbNormalFocus)
End Sub
The one difference from the other project is that AccountNumber is a number and not text, but I figured in defining it as a string it shouldnt matter???
Try this:
Option Explicit
'use Const for fixed values
Const EXPORTS As String = "P:\Public\Generated Letters\LTXN Export Spreadsheets\"
Sub Create_PDF()
Dim ws As Worksheet, myRange As Range
Dim AccountNumber As String, dt As String, FullName As String, fName As String, sep As String
Set ws = ActiveSheet
AccountNumber = Right(ws.Range("A1").Value, 3) 'not just `A1`
With ActiveSheet.PageSetup
.PrintArea = "A1:" & ws.Cells(Rows.Count, 6).End(xlUp).Address
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
dt = Format(Now, "mm.dd.yyyy hh mm")
fName = EXPORTS & "AccountEnding" & AccountNumber
If Len(Dir(fName & ".pdf")) > 0 Then sep = " - "
fName = fName & sep & dt & ".pdf"
'note there's no `xlQualityMedium` enumeration for `Quality`
ws.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Sub openFolder()
'Folder paths with spaces need to be quoted....
Call Shell("explorer.exe" & " """ & EXPORTS & """", vbNormalFocus)
End Sub
I have large spreadsheet that I'm looping through and printing each page to a pdf report.
I'm trying to print them A3 Landscape, however the actual export size is far larger than an A3 page.
Any suggestions I what I'm doing wrong?
Here is my current code:
Sub printChartsA3()
Application.ScreenUpdating = False
Dim sPrintArea As String
Dim wks As Worksheet
Const path As String = "E:\A3 Charts\"
sPrintArea = "A1:BM69"
For Each wks In Worksheets
Application.PrintCommunication = False
wks.PageSetup.PaperSize = xlPaperA3
wks.PageSetup.Orientation = xlLandscape
wks.PageSetup.LeftMargin = Application.InchesToPoints(0.25)
wks.PageSetup.RightMargin = Application.InchesToPoints(0.25)
wks.PageSetup.PrintArea = sPrintArea
wks.PageSetup.Zoom = False
wks.PageSetup.FitToPagesWide = 1
'wks.PageSetup.FitToPagesTall = 1 'not sure if this one is needed?
Application.PrintCommunication = True
wks.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=path & wks.Name & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
Set wks = Nothing
Application.ScreenUpdating = True
End Sub
I am trying to do page setup on multiple sheets with same range. However, one of the sheets "Dashboard" has different page set up range. It is going to be "D24:K73" How can I accomplish that with the code below? I have tried modifying it but my skills do not produce wanted results.
Sub Octsaveaspdf()
Dim ws As Worksheet
Dim FileName As String
Dim FilePath As String
For Each ws In Sheets
If ws.Visible Then ws.Select (False)
Next
FilePath = Range("Instructions!B16").Value
FileName = Range("Dashboard!Q26").Text
Range("$p24:$w73").Select
Application.PrintCommunication = False
With ActiveSheet.PageSetup
LeftMargin = Application.CentimetersToPoints(0.1)
.RightMargin = Application.CentimetersToPoints(0.1)
.FitToPagesWide = 1
End With
Application.PrintCommunication = True
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, FileName:=FilePath & "Compare " & FileName & ".pdf" _
, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
I truly appreciate all the help :) Thank you!
Move your export into a separate procedure and call it multiple times with different ranges to export.
The code below will work through each visible sheet and export different ranges depending on the sheet name.
Each export will be given the same name, so you'll need to do something about that to stop problems with file name conflicts.
Private FilePath As String
Private FileName As String
Public Sub OctSaveAsPDF()
Dim ws As Worksheet
FilePath = ThisWorkbook.Worksheets("Instructions").Range("B16")
FileName = ThisWorkbook.Worksheets("Dashboard").Range("Q26")
For Each ws In ThisWorkbook.Worksheets
If ws.Visible Then
Select Case ws.Name
Case "Dashboard"
PerformExport ws.Range("D24:K73")
Case "Sheet1", "Sheet2"
PerformExport ws.Range("A1:Z10")
Case Else
PerformExport ws.Range("P24:W73")
End Select
End If
Next ws
End Sub
Public Sub PerformExport(xpRng As Range)
With xpRng
With .Parent.PageSetup 'The parent of the range is the worksheet.
.LeftMargin = Application.CentimetersToPoints(0.1)
.RightMargin = Application.CentimetersToPoints(0.1)
.FitToPagesWide = 1
End With
.ExportAsFixedFormat _
Type:=xlTypePDF _
, FileName:=FilePath & "Compare " & FileName & ".pdf" _
, Quality:=xlQualityStandard _
, IncludeDocProperties:=True _
, IgnorePrintAreas:=False _
, OpenAfterPublish:=True
End With
End Sub
I have cobbled together a VBA script that loops through a list of data, changing the value of a single cell on a summary page. That cell drives a number of formulas. After each iteration, the cell range of interest is saved off as a PDF.
I am looking to avoid having to manually hit enter every time the 'save as' dialog box is generated on each loop. Once I deploy this script, I could be looking at 1k+ iterations.
Sub AlterID()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
Set ws = Worksheets("Summary Data")
For Each c In Worksheets("Data").Range("A2:A11").Cells
Worksheets("Summary Data").Range("B1").Value = c.Value
strFile = ws.Range("D3").Value
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
ws.Range("D3:H9").Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
Next
End Sub
Sub AlterID()
Dim ws As Worksheet, c As Range
Dim strFile As String
Set ws = Worksheets("Summary Data")
For Each c In Worksheets("Data").Range("A2:A11").Cells
ws.Range("B1").Value = c.Value
strFile = ThisWorkbook.Path & "\" & ws.Range("D3").Value
ws.Range("D3:H9").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
End Sub
Have you tried turning off application alerts?
Application.DisplayAlerts = False 'before your code
Application.DisplayAlerts = True 'after your code
Edit 1
Here is a sub I use to save a file to a PDF
Sub SaveAsPDF()
Dim myValue As Variant
Dim mySheets As Variant
mySheets = Array("Report")
For Each sh In mySheets
Sheets(sh).PageSetup.Orientation = xlLandscape
Next
uid = InputBox("Enter your UID")
uid = StrConv(uid, vbProperCase)
Application.PrintCommunication = False
With Sheets("Report").PageSetup
.FitToPagesWide = 1
.FitToPagesTall = False
End With
Application.PrintCommunication = True
Dim fName As String
fName = "HMB SOX report for week ending " & ActiveSheet.Range("H4").Text
Call selectPage("Report")
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
"C:\Users\" & uid & "\Desktop\" & fName, :=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, Publish:=False
End With
End Sub
So this is my code that´s is supposed to loop through the pivot's SUPPLIER FILTER based on a list located in the same worksheet. After every loop it has to upload the file to the intranet in a .pdf format.
Sub Upload()
Dim pt As PivotTable
Dim pi As PivotItem
Dim pf As PivotField
Dim lLoop As Long
Set pt = Sheets("To Supplier").PivotTables("PivotTable1")
Set pf = pt.PivotFields("[Query].[SUPPLIER].[SUPPLIER]")
Sheets("To Supplier").Select
For Each pi In pf.PivotItems
On Error Resume Next
pf.CurrentPage = pi.Value
On Error GoTo 0
If pf.CurrentPage = pi.Value Then
If lLoop = 0 Then
With Sheets("To Supplier").PageSetup
.CenterFooter = pi.Value
.LeftHeader = pt.Name
.LeftFooter = Now
End With
End If
Range("L2").Select
ActiveCell.FormulaR1C1 = _
"=INDEX(RC[-6]:R[59]C[-5],MATCH(R[1]C[-10],RC[-6]:R[59]C[-6],0),2)"
Sheets("To Supplier").ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"http://collaborationx.com/portalone/sourcing/Supplier%20documents/" & Cell("L2").Value _
& "/Evaluations/" & Cell("L2").Value & "%20Credits.pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
lLoop = lLoop + 1
End If
Next pi
End Sub
However, It keeps throwing me off... now the prob is that it says the function is not defined, before the problem was with the references...
Cell("L2") is not defined. You probably wanted Range("L2") but since you selected that range before you could use ActiveCell. Example, HTH.
Option Explicit
Sub test()
Range("L2").Select
ActiveCell.FormulaR1C1 = "=INDEX(RC[-6]:R[59]C[-5],MATCH(R[1]C[-10],RC[-6]:R[59]C[-6],0),2)"
Dim exportFileName As String
exportFileName = "http://collaborationx.com/portalone/sourcing/Supplier%20documents/{0}/Evaluations/{0}%20Credits.pdf"
exportFileName = Replace(exportFileName, "{0}", ActiveCell.Value)
Sheets("To Supplier").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=exportFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub