Save copies as .PDF & .xlsx - vba

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

Related

How can I save .doc or .docx as PDF with VBA overwitring?

I have a code that I use in Access to save all .docx in a folder as .pdf. The problem is: when there already exists a file .docx as .pdf, the code fails and I don't know why it doesn't save the .docx as .pdf overwriting the pdf previous. How can I do that with my actual code?
My actual code is:
Private Sub Generate_PDFs_Click()
Dim directory As String
Dim fldr As Object
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select folder with Word files to export to PDF"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
directory = .SelectedItems(1)
End With
Dim fso, newFile, Folder, files, folders
Set fso = CreateObject("Scripting.FileSystemObject")
Set Folder = fso.GetFolder(directory)
Set files = Folder.files
For Each file In files
If file.path Like "*.docx*" Then
newName = Replace(file.path, ".docx", ".pdf")
newName = Replace(newName, ".doc", ".pdf")
'Debug.Print file.Path
Documents.Open FileName:=file.path, _
ConfirmConversions:=False, _
ReadOnly:=False, _
AddToRecentFiles:=False, _
PasswordDocument:="", _
PasswordTemplate:="", _
Revert:=False, _
WritePasswordDocument:="", _
WritePasswordTemplate:="", _
Format:= _
wdOpenFormatAuto, _
XMLTransform:=""
ActiveDocument.ExportAsFixedFormat OutputFileName:=newName, _
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
ActiveDocument.Close
End If
If file.path Like "*.dwg*" Then
MsgBox "Isso ainda não foi feito"
End If
Next
End Sub
Before running save, enter the following line, so Access will not prompt you, to overwrite your file if it already exists,
Application.DisplayAlerts = False
and then after saving to turn the DisplayAlerts back on,
Application.DisplayAlerts = True

I have a macro that creates individual PDFs for a set of tabs. Is there a way to add a step and combine all the PDFs into one file?

I have a macro that creates individual PDFs for a set of tabs. Is there a way to add a step and combine all the PDFs into one file?
Sub Print_Exhibit()
Dim Numb_Exhibit As Double
Dim File_Location As String
Dim Sheet_Name As String
Dim X As Double
Dim Y As Double
Numb_Exhibit = WorksheetFunction.Max(Sheets("Control - Exhibit
Key").Range("B:B"))
File_Location = Sheets("Control - Exhibit Key").Range("K6").Value
For X = 1 To Numb_Exhibit
Y = 8 + X
Sheet_Name = Sheets("Control - Exhibit Key").Range("E" & Y).Value
Sheets(Sheet_Name).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:=File_Location
& "\" & Sheet_Name & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True,
IgnorePrintAreas _
:=False, OpenAfterPublish:=True
Next
End Sub
Thank you so much for your help!
Loop through all tabs, copy and paste into a new common tab. Export it.
Did you do a prerequisite Google search before posting here?
Save multiple sheets to .pdf
Public Sub subCreatePDF()
If Not IsPDFLibraryInstalled Then
'Better show this as a userform with a proper link:
MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041".
Exit Sub
End If
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ActiveWorkbook.Path & Application.PathSeparator & _
ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Private Function IsPDFLibraryInstalled() As Boolean
'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm)
IsPDFLibraryInstalled = _
(Dir(Environ("commonprogramfiles") & _
"\Microsoft Shared\OFFICE" & _
Format(Val(Application.Version), "00") & _
"\EXP_PDF.DLL") <> "")
End Function
OR
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
ALSO
https://danwagner.co/how-do-i-save-multiple-sheets-as-a-single-pdf/

Excel macro - Export to PDF

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

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