Excel macro - Export to PDF - vba

I have a work book that has many macros to export various worksheets as pdfs in the same location the workbook is saved.
My issue is, if the workbook is saved in a folder on the desktop, then the PDFs are generated just fine.
When the workbook is saved on a network location, the pdfs don't generate. below is a sample of the macro:
Sub PDF_CStmtP()
Application.ScreenUpdating = False
ThisWorkbook.Sheets(Array("C Stmt - P")).Select
pdfname = fileSaveName
ChDir ActiveWorkbook.Path & "\"
fileSaveName = "Closing Statement (Purchase)"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
fileSaveName _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
ActiveWorkbook.Sheets("Main Menu").Activate
MsgBox "File Saved " & " " & fileSaveName
End Sub

Your issue is the ChDir command, see here for an explanation: https://www.techonthenet.com/excel/formulas/chdir.php
The important part of this is "The CHDIR statement lets you change the current directory on the current drive. If you need to change drives, try using the CHDRIVE statement first."
When you are trying to save to a network drive you are changing the drive letter from C:\ to whatever the network drive is mapped to, in my case it was U:\ .
The simple fix to your code is to move the Path from ChDir to just being in the filename, so your code should look like:
Sub PDF_CStmtP()
Application.ScreenUpdating = False
ThisWorkbook.Sheets(Array("C Stmt - P")).Select
pdfname = fileSaveName
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & "Closing Statement (Purchase)"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
ActiveWorkbook.Sheets("Main Menu").Activate
MsgBox "File Saved " & " " & fileSaveName
End Sub
There are a few other edits you could make to clean it up, but this will solve the issue at hand.
**Based on the comment about the message box, you could change the code to this:
Sub PDF_CStmtP()
Application.ScreenUpdating = False
ThisWorkbook.Sheets(Array("C Stmt - P")).Select
pdfname = "Closing Statement (Purchase)"
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & pdfname
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
ActiveWorkbook.Sheets("Main Menu").Activate
MsgBox "File Saved " & " " & pdfname
End Sub

Related

Excel pdf export

I'm new in Excel macros. I try to make a "save as pdf" button. I wrote a code like this:
Sub save_as_pdf()
'
' save_as_pdf Macro
' Saves sheet as PDF
'
Dim Path As String
Dim filename As String
Path = "/Users/Adrian/Desktop/"
filename = ThisWorkbook.Sheets("Controller").Range("B20")
PathAndFilename = Path & filename & ".pdf"
MsgBox "Saved file as: " & PathAndFilename
Sheets("View").Select
Application.DisplayAlerts = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
PathAndFilename, Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Application.DisplayAlerts = True
End Sub
I need the Range("B20") because I keep there a filename based on some in-excel logic.
The MsgBox produces a valid path and filename.
Yet, when I run this I get a "Error while printing" and a "Runtime error 1004" highlighting ActiveSheet.ExportAsFixedFormat ...
Set a print area in the sheet to export.
Also verify path as I expected \ and a drive letter e.g. C:\
The following works for me
Option Explicit
Sub save_as_pdf()
Dim Path As String
Dim filename As String
Dim PathAndFileName As String
Path = "C:\Users\User\Desktop\" ' "C:\Users\Adrian\Desktop\"
filename = ThisWorkbook.Sheets("Controller").Range("B20")
PathAndFileName = Path & filename & ".pdf"
MsgBox "Saved file as: " & PathAndFileName
Sheets("View").Select
Application.DisplayAlerts = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
PathAndFileName, Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Application.DisplayAlerts = True
End Sub

Save copies as .PDF & .xlsx

I'm trying to save copies of the workbook but don't know how to set the file type when saving, this code makes the files but they're corrupt and cannot be opened.
Sub Saves1()
'Store Answers
Dim SavePdfAnswer As String
Dim SaveXlsxAnswer As String
SavePdfAnswer = VBA_CS.Range("C2")
SaveXlsxAnswer = VBA_CS.Range("C3")
'Store File Path And Names
PdfFilePath = VBA_CS.Range("M2") & "\" & ActiveSheet.Range("F9") & ".pdf" 'File path for pdf file
ExcelFilePath = VBA_CS.Range("M2") & "\" & ActiveSheet.Range("F9") & ".xlsx" 'File path for excel xlsx file
'Save as pdf
If SavePdfAnswer = "Yes" Then
ActiveWorkbook.SaveCopyAs PdfFilePath
End If
'Save as excel xlsx
If SaveXlsxAnswer = "Yes" Then
ActiveWorkbook.SaveCopyAs ExcelFilePath
End If
End Sub
for pdf:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="path\pdf_from_excel.pdf" _
, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=True, OpenAfterPublish:=True
for xlsx:
ActiveWorkbook.SaveAs Filename:= _
"path\excel_file_name.xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Hope this works whats needed
A quick example:
Sub SaveFile()
Dim tmpPth As String
On Error GoTo errorhandle
tmpPth = FilePath & FileName
ThisWorkbook.Sheets("Sheetname").ExportAsFixedFormat Type:=xlTypePDF, FileName:=tmpPth & ".pdf", Quality:=xlQualityStandard, openAfterPublish:=False
ActiveWorkbook.SaveCopyAs tmpPth & ".xlsm"
Exit Sub
errorhandle:
MsgBox ("Something went wrong")
End Sub
if You want to know how system do this you can register macros.
Ms Word generated this code :
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
"C:\Users\Administrator\Desktop\fileName.pdf", ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _
IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _
wdExportCreateNoBookmarks, DocStructureTags:=True, BitmapMissingFonts:= _
True, UseISO19005_1:=False

VBA “Save to PDF” saves even on cancels

I have a problem with a macro. I would like to avoid that the macro saves the PDF file even if I press on Cancel in the Save dialog box. What did I miss?
Here's the code:
Set ws = Foglio5
'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(Foglio5.Cells(14, 2) & "_" & (Foglio5.Cells(14, 4) & "_" & (Foglio5.Cells(15, 10))), "", ""), ".", "_") _
& "_" _
& Format(Foglio5.Cells(17, 5), "yyyymmdd\") _
& ".pdf"
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.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF Creato! Si trova nella cartella di questo file."
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Errore nella creazione del PDF"
Resume exitHandler
End Sub
I tried changing:
If myFile <> "False" Then
into:
If myFile Then
Now it is not working anymore and it says that it is impossible to save the PDF.
myFile <> "False"
should be
myFile <> False
ref

Saving a Range of data as a PDF with a button in excel

I have code that will bring up a save dialog box when a button in my excel sheet is clicked:
Sub SavePDF()
Dim X
X = Application.GetSaveAsFilename(InitialFileName:=Range("F8") & "_" & Range("F6"), _
FileFilter:="PDF files, *.pdf", _
Title:="Save PDF File")
If TypeName(X) = "Boolean" Then
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=X, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
End Sub
...what I need is to add something to this that will only save a certain range of data when the button is clicked. My range is: B2 to J44. At the moment when I click the save button is it saving the whole sheet which I do not want.
Thanks in advance.
Try the following.
Option Explicit
Sub CreatePDF()
Dim wSheet As Worksheet
Dim vFile As Variant
Dim sFile As String
Set wSheet = ActiveSheet
sFile = Replace(Replace(wSheet.Name, " ", ""), ".", "_") _
& "_" _
& Format(Now(), "yyyymmdd\_hhmm") _
& ".pdf"
sFile = ThisWorkbook.Path & "\" & sFile
vFile = Application.GetSaveAsFilename _
(InitialFileName:=sFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If vFile <> "False" Then
wSheet.Range("B2:J44").ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
End If
End Sub
See Examples here
File is save as SheetName_TodaysDate_HoursMinutes
if you would like to add seconds just add ss next to _hhmmss

Check is destination directory exist then proceed if not then create it and proceed afterwards

I have a button on one of the worksheets that lets user to continue with his task to save his/her template as a separate workbook in the folder.
Here is my code
Private Sub ContinueButton_Click()
Application.ScreenUpdating = 0
Sheets(cmbSheet.Value).Visible = True
Application.Goto Sheets(cmbSheet.Value).[a22], True
Application.ScreenUpdating = 1
Unload Me
End Sub
Now what I need is to check if that folder exist, in case if the folder does not exist my user should be able to create it.
My code to create this folder is here below, but how to connect this 2 functions together I simply have no idea, since I am fairly new to VBA
Sub CreateDirectory()
Dim sep As String
sep = Application.PathSeparator
'sets the workbook's path as the current directory
ChDir ThisWorkbook.Path
MsgBox "The current directory is:" & vbCrLf & CurDir
'makes new folder in current directory
MkDir CurDir & sep & Settings.Range("C45").Value
MsgBox "The archive directory named " & Settings.Range("C45").Value & " has been created. The path to your directory " & Settings.Range("C45").Value & " is below. " & vbCrLf & CurDir & sep & Settings.Range("C45").Value
End Sub
I am going to modularize your code a little bit:
First get the directory path here
Function getDirectoryPath()
getDirectoryPath = ThisWorkbook.Path & Application.PathSeparator & Settings.Range("C45").Value
End Function
You can create the directory using this function
Sub createDirectory(directoryPath)
MkDir directoryPath
End Sub
You can check if a directory exists or not using Dir function
Dir(directoryPath, vbDirectory) 'empty string means directoryPath doesn't exist
The final function on button click:
Private Sub ContinueButton_Click()
Application.ScreenUpdating = 0
Sheets(cmbSheet.Value).Visible = True
directoryPath = getDirectoryPath
'Creating the directory only if it doesn't exist
If Dir(directoryPath, vbDirectory) = "" Then
createDirectory directoryPath
End If
Application.Goto Sheets(cmbSheet.Value).[a22], True
Application.ScreenUpdating = 1
Unload Me
End Sub
I created a macro that will save as pdf certain tabs of my excel in a relative (variable)folder.
It will use the contract reference to create a subfolder, such subfolder label is exactly the contract reference. If subfolder already exists it just creates the files in it, else (subfolder does not exist) then it creates the folder and save the files in it.
Sub Gera_PDF_MG_Nao_Produtor_Sem_Ajuste()
Gera_PDF_MG_Nao_Produtor_Sem_Ajuste Macro
Dim MyFolder As String
Dim LaudoName As String
Dim NF1Name As String
MyFolder = ThisWorkbook.path & "\" & Sheets("Laudo").Range("C9")
LaudoName = Sheets("Laudo").Range("K27")
NF1Name = Sheets("MG sem crédito e sem ajuste").Range("Q3")
Sheets("Laudo").Select
Columns("D:P").Select
Selection.EntireColumn.Hidden = True
If Dir(MyFolder, vbDirectory) <> "" Then
Sheets("Laudo").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & LaudoName & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Sheets("MG sem crédito e sem ajuste").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & NF1Name & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Else
MkDir MyFolder
Sheets("Laudo").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & LaudoName & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Sheets("MG sem crédito e sem ajuste").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & NF1Name & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
End If
Sheets("Laudo").Select
Columns("C:Q").Select
Selection.EntireColumn.Hidden = False
Range("A1").Select
'
End Sub
If Dir(Fldrpath, vbDirectory) = "" Then
MkDir Fldrpath
End If
Fldrpath refer to the Folderpath if Folder not found MkDir creates the folder