Skip to content

Instantly share code, notes, and snippets.

@ticapix
Last active March 10, 2019 11:04
Show Gist options
  • Save ticapix/4acd413d45a8c719d67f2c633b8ab9ce to your computer and use it in GitHub Desktop.
Save ticapix/4acd413d45a8c719d67f2c633b8ab9ce to your computer and use it in GitHub Desktop.
VBA code to export Excel spreadsheet to pdf file in local folder
## check if file already exists
Function FileExists(ByVal FileToTest As String) As Boolean
FileExists = (Dir(FileToTest) <> "")
End Function
## delete file if already generated
Sub DeleteFile(ByVal FileToDelete As String)
If FileExists(FileToDelete) Then 'See above
' First remove readonly attribute, if set
SetAttr FileToDelete, vbNormal
' Then delete the file
Kill FileToDelete
End If
End Sub
## export shreapsheet as pdf
Sub ExportPdf()
Dim folder As String
Dim filename As String
Dim filepath As String
folder = Application.ActiveWorkbook.Path # folder of the currently open sreapsheet
filename = "invoice " & ActiveSheet.Name & ".pdf"
filepath = folder & "\" & filename # create path string with folder and filename
DeleteFile (filepath)
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
filepath _
, Quality:=xlQualityMinimum, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, From:=1, To:=1, OpenAfterPublish:=True
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment