Saving a PDF automatically to a predetermined folder - vba

I am writing a macro that automates a daily report that I send out each day. One of my last items is to write a script that saves the formatted excel sheet as a PDF (through a print to pdf option), and save it in a specific folder. I have the following written, however, it still prompts the user as to where to save it.
What would be a better way, or a way in general, to have it save automatically to a folder somewhere on my desktop?
Sub printToPDF()
Worksheets("general_report").PageSetup.CenterVertically = False
ActiveWindow.SelectedSheets.PrintOut Copies:=1, ActivePrinter:="Foxit Reader PDF Printer"
End Sub

This should do the work,
Sub printToPDF()
Dim FilePath As String
Dim FileName As String
FilePath = "C:\Users\userName\Desktop\" 'Change as per your username
ActiveSheet.Copy 'Copy a worksheet to a new workbook
'It saves .PDF file at your Descrop with the name of the worksheet
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FilePath & ActiveSheet.Name, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'Closing a newly created workbook without saving it
Application.DisplayAlerts = False
ActiveWorkbook.Close
End Sub

Related

Excel VBA to go to a folder and save all Excel Docs as seperare PDF files

ive been working on some code for a while but cannot seem to get it to work.. think im nowhere near if im honest..
I want to program a button into an excel doc to go to a folder i.e. D:\Work\
which has lots of excel spreadsheets in, and save everyone one as a separate PDF doc?
thanks in advance
The code below Loop through all files and then save all worksheets with in a workbook as PDF. I have commented the code to help you understand it.
Option Explicit
Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String
Dim wbktoExport As Workbook
Dim strSourceExcelLocation As String
strSourceExcelLocation = "D:\Work\XLS\"
'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.xls*")
Do While Len(strWorkbook) > 0
'Open the workbook
wbktoExport = Workbooks.Open(strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport)
'Get next workbook
strWorkbook = Dir
'Close Excel workbook without making changes
wbktoExport.Close False
Loop
End Sub
Sub Export_Excel_as_PDF(ByRef wbk As Workbook)
Dim strTargetPDFLocation As String
strTargetPDFLocation = "D:\Work\PDF\"
'Select all worksheets in the opened workbook
wbk.Sheets.Select
'Activate first worksheet
wbk.Sheets(1).Activate
'Export as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
strTargetPDFLocation & wbk.Name & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
End Sub

Is it possible to make save button (not save as button) to save document in specific path?

I want to make save button for my validation program in VBA excel.
A save button will save the file in a spesicic path and rename automaticallyby the status of document (Clean or Error).
If the document has been save when the document still error, the file will be named error.xlsm
But, when i fix the error of document. The document will be named clean.xlsm.
It’s annoying me to delete the first file (error.xlsm) manually.
Is it possible to make save button save (not save as button) to save document in specific path without using save as?
Here is my code:
Private Sub CommandButton2_Click()
ActiveWorkbook.SaveAs Filename:="D:\" & Sheets("C").Range("G23").Text & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
ReadOnlyRecommended:=False, CreateBackup:=False
ActiveWorkbook.Close
End Sub
*note: Sheets("C").Range("G23").Text contains status of document (clean or error with if formula)
Give this a try...
Private Sub CommandButton2_Click()
Dim fName As String
Application.DisplayAlerts = False
fName = ActiveWorkbook.Sheets("C").Range("G23").Value
ActiveWorkbook.SaveAs FileName:="D:\" & fName & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
ReadOnlyRecommended:=False, CreateBackup:=False
ActiveWorkbook.Close
On Error Resume Next
Select Case fName
Case "Error"
Kill "D:\Clean.xlsm"
Case "Clean"
Kill "D:\Error.xlsm"
End Select
End Sub

How to save a WorkSheet from an Excel spreadsheet as a PDF

I'm trying to write (what I thought would be) a simple macro which will save a Worksheet (not the whole Workbook) from an Excel Spreadsheet as a PDF. I'm using Excel 2016 (15.24) on a MacBook Pro running Yosemite. I've seen lots of examples here and online.
I started out by recording a macro and edited it. It looked like this:
Sub SavePDF()
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
End Sub
This produced a PDF file but it contained all of the sheets from the Workbook. It seems that, for some reason, the PublishOption:=xlSheet although it works manually when recording the macro, does not work from VBA.
Ok. So I tried a different approach using ExportAsFixedFormat, modelling my approach on some of the examples I've seen here and elsewhere online and trying to keep it as simple as possible. Here's my version.
Sub SimplePDF()
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="pdfs/example.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Every time I try this I get a print error, followed by the dreaded run-time error 1004. BTW, does anyone know the definition of this error?
Can anyone suggest why this is not working? I'd be grateful for any advice.
On the strength of Sinan's advice below I changed the code to
Sub SavePDF()
ActiveSheet.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF
End Sub
I get the same run-time error 1004 but it gives me the extra information "SaveAs method of Worksheet class failed"
I tried David Zemens technique below of copying the active worksheet to a new Workbook and then using SaveAs on that new workbook.
Sub NSavePDF()
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
'Close the new workbook without saving it.
ActiveWorkbook.Close False
End Sub
However, this attempts to print the worksheet on my default printer rather than converting to PDF.
You are asking to save the entire workbook and that is what is happening. Instead, you can figure out which worksheet you want to save as PDF, and invoke SaveAs method on that.
See Worksheet.SaveAs instead of Workbook.SaveAs.
Saves changes to the chart or worksheet in a different file.
Syntax
expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AddToMru, TextCodepage, TextVisualLayout, Local)
expression: A variable that represents a Worksheet object.
Sub SaveSheetAsPDF()
ActiveWorksheet.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF
End Sub
If some reason that doesn't work (but Workbook.SaveAs does), you could simply copy the sheet to a new workbook containing only one sheet, and then do SaveAs on that workbook.
Sub SavePDF()
ActiveSheet.Copy '## This creates a new workbook containing only the copied sheet
'ActiveWorkbook should now be the new/copied worksheet:
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
'Close the new workbook without saving it.
ActiveWorkbook.Close False
End Sub

VBA Exporting PDF from Excel in 2 copies

I'm looking for a solution to export couple of sheets from Excel to one file PDF. I've recorded a macro that creates nice PDF with all interesting me sheets. BUT i need 2 copies of one of the sheets in the same PDF, but I don't know how to do it.
Here is my code.
Sub ExportPDF()
Sheets(Array("PackingList", "Administracyjny", "Nadawca", "Odbiorca", "Przewoźnik")).Select
Sheets("PackingList").Activate
ChDir "C:\Users\XXXXXX\Desktop"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\XXXXXX\Desktop\Spools_PackingList.pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:= False
End Sub
See here for copying a worksheet, it might be a good workaround to copy the entire worksheet at the start of your code, and then you can just delete it at the end with (taken from here):
Sub sbDeleteASheet()
Sheet1.Delete
'OR You can mention the Sheet name
Sheets("Sheet2").Delete
End Sub

How to save the excel file with vba coding without opening it?

I have added a button in excel sheet and added following codes in vba window of that button. Now when I click this button i.e. when I run the codes it saves the excel sheet in pdf form whose name it takes from cell no H8 and saves it at M:\formats. Moreover it also saves the same excel sheet in .xlsx format at M:\formats\excels. But here the problem is when I run the codes it closes the excel sheet in which I have added the codes and opens the file which is saved by the codes. For example I made abc.xlsm excel sheet and added the codes in vb window, now xyz is written in cell no h8 in abc.xlsm excel sheet, now when I will run the codes it closes abc.xlsm and all codes are shown in xyz.xlsx excel sheet. I want it should only save the file in xlsx format it requisite location. It should not close the base file (which is abc.xlsx in the above example) and should not open the saved file (which is xyz.xlsx in the above example). Moreover I want that the saved file (xyz.xlsx in the above example) should not contain any vba coding. In another words it should be just like the backup copy for the base file (which is abc.xlsx in the above example). Kindly help me in to modify these codes to them as I want. I will be highly obliged to you. Thanks
Sub ExportAPDF_and_SaveAsXLSX()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
strBasePath = "M:\formats\excels\"
strFileName = Range("H8")
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName,
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Here is the code, with just two small changes. Both new sets of lines have the comment "New" in front of them.
Also just tidied up the error handling routine a little bit.
The way it works is this:
Store the filename of the current workbook in the variable 'strMasterWorkbookFilename'
The PDF file is created by 'exporting' the worksheet.
The Excel worksheet is then saved as an XLSX. This effectively 'closes' the original workbook.
3.1 The Button ("Button 8") is removed from the new XLSX worksheet and the workbook is saved again.
The code then re-opens the original workbook ('strMasterWorkbookFilename') and closes the current workbook.
Notes - Saving as the XLSX will remove the Macro code from the saved file. The Macro will remain in the main 'master' file.
Sub ExportAPDF_and_SaveAsXLSX()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
' NEW
Dim strMasterWorkbookFilename As String
strMasterWorkbookFilename = ThisWorkbook.FullName
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbook
wsThisWorkSheet.Shapes("Button 8").Delete
ActiveWorkbook.Save
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
' NEW
Workbooks.Open strMasterWorkbookFilename
Workbooks(strFileName).Close SaveChanges:=False
exitHandler:
Exit Sub
errHandler:
MsgBox "Error Saving file. The error is " & vbCrLf & Chr(34) & Err.Description & Chr(34)
Resume exitHandler
End Sub
Thanks for posting this as a new question. If I'd carried on modifying the original code in the first question, it would not have been useful for anyone else reading your original post.