Public Sub Save_Sheet_As_PDF_With_Picture_Footer_On_Last_Page()
Dim pictureFile As String
Dim PDFoutputFile As String
Dim currentView As XlWindowView
Dim rowsPerPage As Long
Dim lastDataRow As Long
Dim lastPageLastRow As Long
Dim picShape As Shape
Dim footerCell As Range
pictureFile = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\My picture.png" 'CHANGE FILE NAME OF PICTURE
PDFoutputFile = ThisWorkbook.Path & "\Sheet with last page footer.pdf" 'CHANGE PDF FILE NAME & PATH
Application.ScreenUpdating = False
With ActiveWindow
currentView = .View
.View = xlPageBreakPreview
End With
With ActiveSheet
.ResetAllPageBreaks
If .HPageBreaks.Count > 0 Then
'Get the number of rows per page by reading the row number of the first page break
rowsPerPage = .HPageBreaks(1).Location.Row - 1
Else
'No page breaks, so assume 50 rows per page
rowsPerPage = 50
End If
'Get the row number of the last data row
lastDataRow = .UsedRange.Rows.Count + .UsedRange.Rows(1).Row - 1
'Get the row number of the last row on the last page
lastPageLastRow = (.HPageBreaks.Count + 1) * rowsPerPage
'Add the picture at (0,0) so that its Height (and Width) can be read
Set picShape = .Shapes.AddPicture(pictureFile, False, True, 0, 0, -1, -1)
'Get the cell immediately below the last row on the last page. The Top of this cell is the bottom of the last row on the last page
Set footerCell = .Cells(lastPageLastRow + 1, 1)
'Would the picture overlay the data?
If footerCell.Top - 1 - picShape.Height < .Cells(lastDataRow + 1, 1).Top Then
'Yes, so add a new page break and get the cell immediately below the last row on the new page. The Top of this cell is the bottom of the last row on the last page
.HPageBreaks.Add Before:=.Cells(lastPageLastRow + 1, 1).EntireRow
Set footerCell = .Cells(lastPageLastRow + rowsPerPage + 1, 1)
End If
'Reposition picture at bottom of last page. picShape.Left stays 0, so picture is on far left of page
picShape.Top = footerCell.Top - 1 - picShape.Height
End With
'Save sheet as the PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFoutputFile, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=True, OpenAfterPublish:=True
picShape.Delete
ActiveWindow.View = currentView
Application.ScreenUpdating = False
End Sub