Excel VBA: Saving and Attaching a worksheet as pdf - excel

I have combined some code from a couple of different examples to get this to work but my solution seems klunky in that I am creating 2 pdfs. One in a temp folder, and one in the current folder. The one in the temp folder is the one getting attached to the email. I would like to just save a single pdf in the current folder and attach that pdf to the email.
This is the code that exports both pdf's:
Title = ActiveSheet.Range("B11").Value & " Submittal"
' Define PDF filename in TEMP folder
PdfFile = ActiveWorkbook.Name
i = InStrRev(PdfFile, ".xl", , vbTextCompare)
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = Title
For Each char In Split("? "" / \ < > * | :")
PdfFile = Replace(PdfFile, char, "_")
Next
PdfFile = Left(CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\" & PdfFile, 251) & ".pdf"
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & ActiveSheet.Range("B11").Value & " Submittal", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End With
For some reason, if I add ThisWorkbook.Path & "\" to the Filename of the first exported file like this: Filename:=ThisWorkbook.Path & "\" & PdfFile, so it saves in the current folder instead of the temp folder, I get a runtime error and it doesn't save even though this is the same code that exports the second pdf file successfully to the current folder.
Here is the full working code but I want to eliminate the temp pdf if possible:
Sub RightArrow2_Click()
Dim IsCreated As Boolean
Dim PdfFile As String, Title As String
Dim OutlApp As Object
Dim i As Long
Dim char As Variant
Title = ActiveSheet.Range("B11").Value & " Submittal"
' Define PDF filename in TEMP folder
PdfFile = ActiveWorkbook.Name
i = InStrRev(PdfFile, ".xl", , vbTextCompare)
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = Title
For Each char In Split("? "" / \ < > * | :")
PdfFile = Replace(PdfFile, char, "_")
Next
PdfFile = Left(CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\" & PdfFile, 251) & ".pdf"
'Debug.Print PdfFile
' Export activesheet as PDF to the temporary folder
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & ActiveSheet.Range("B11").Value & " Submittal", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End With
' Use already open Outlook if possible
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
On Error GoTo 0
' Prepare e-mail with PDF attachment
With OutlApp.CreateItem(0)
' Prepare e-mail
.Subject = Title
.To = ActiveSheet.Range("H12").Value
.CC = ""
.Body = "Please see the attached submittal for " & ActiveSheet.Range("B11").Value & "." & vbLf & vbLf _
& "Thank you," & vbLf & vbLf _
& vbLf
.Attachments.Add PdfFile
' Display email
On Error Resume Next
.Display ' or use .Send
' Return focus to Excel's window
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0
End With
' Delete the temporary PDF file
If Len(Dir(PdfFile)) Then Kill PdfFile
' Try to quit Outlook if it was not previously open
If IsCreated Then OutlApp.Quit
' Release the memory of object variable
' Note: sometimes Outlook object can't be released from the memory
Set OutlApp = Nothing
End Sub

In your description, in the line of code
Filename:=ThisWorkbook.Path & "\" & PdfFile
the PdfFile variable contains the path to the temp folder which is why you get the error.

First, remove this line:
PdfFile = Left(CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) _
& "\" & PdfFile, 251) & ".pdf"
And then this line:
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path _
& "\" & .Range("B11").Value & " Submittal", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End With
I am not sure how you're creating your filename for your PDF but it should be something like this:
If you retrieve it from a Range:
With Thisworkbook
PdfFile = .Path & Application.PathSeparator & _
.Sheets("SheetName").Range("B11") & "Submittal.pdf"
End With
If you need to do manipulations on the text like what you did:
Title = ActiveSheet.Range("B11").Value & " Submittal"
PdfFile = Title
For Each c In Split("? "" / \ < > * | :")
PdfFile = Replace(PdfFile, char, "_")
Next
PdfFile = Thisworkbook.Path & Application.PathSeparator & PdfFile & ".pdf"
Once you've created a valid filename, the below code should work:
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=PdfFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End With

Related

VBA Excel MacOs 2019 pdf export to current directory

I wrote a code for PDF export in Excel for Mac Office 2019 with a variable filename. It's working despite Mac's permission bugs with VBA saving as when using the makro for the first time Excel asks for the permission to access the concerning folder.
My question:
Can I anyhow give new users the option to choose their exporting path the first time they are using the makro or do I have to adjust the code for every new user personally?
Here's my (otherwise working) code so far:
Sub als_PDF_speichern_recorded_mac()
ChDir "/Users/Admin/Documents/Dokumente/Finanzen/2021/Rechnungen 2021/"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
"/Users/Admin/Documents/Dokumente/Finanzen/2021/Rechnungen 2021/Rechnung_" & ActiveSheet.Range("D11") & ".pdf" _
, Quality:=xlQualityMinimum, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
End Sub
EDIT
I might have a solution working universally for Mac users. It's not following my original intent that users can choose the path at first use but it's supposed to be exporting the PDF to the current path of the workbook and creating a folder if not existing already.
Please could someone with Excel for Mac (I'm using 2019) confirm:
Sub exportPDF_mac()
'export to currentpath/greatnewfolder
ChDir "/" & ActiveWorkbook.Path
MakeFolderIfNotExist (ThisWorkbook.Path & Application.PathSeparator & "greatnewfolder")
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
"/" & ActiveWorkbook.Path & "/greatnewfolder/greatfile_" & ActiveSheet.Range("D11") & ".pdf" _
, Quality:=xlQualityMinimum, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
End Sub
Function MakeFolderIfNotExist(Folderstring As String)
' Ron de Bruin, 2-March-2019
' http://www.rondebruin.nl/mac/mac010.htm
Dim ScriptToMakeFolder As String
Dim TestStr As String
Dim FolderStr As String
If Val(Application.Version) < 15 Then
ScriptToMakeFolder = "tell application " & Chr(34) & _
"Finder" & Chr(34) & Chr(13)
ScriptToMakeFolder = ScriptToMakeFolder & _
"do shell script ""mkdir -p "" & quoted form of posix path of (" & _
Chr(34) & Folderstring & Chr(34) & ")" & Chr(13)
ScriptToMakeFolder = ScriptToMakeFolder & "end tell"
On Error Resume Next
MacScript (ScriptToMakeFolder)
On Error GoTo 0
Else
FolderStr = MacScript("return POSIX path of (" & _
Chr(34) & Folderstring & Chr(34) & ")")
On Error Resume Next
TestStr = Dir(FolderStr & "*", vbDirectory)
On Error GoTo 0
If TestStr = vbNullString Then
MkDir FolderStr
End If
End If
End Function
Thanks in advance!
Thomas

how to check file type and opening/ saving files in a folder VBA

The following code loops through All files in a specified folder, formats each file, and saves it as a PDF in the same folder.
The code runs fine but there are 2 issues:
1)if there are any files in the folder that are already pdf,s it will open in and mess it up. How can I make this so it only opens the excel files in the folder and not PDF files?
2)if I run it twice it works but it just saves over files if the filename already exists. How can I make I so if when it saves it and the file name already exists it saves it as a new file like filename-b, filename-c filename-d, filename-f ect?
Sub File_Loop_Example()
Dim MyFolder As String, MyFile As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.clear
End With
MyFile = Dir(MyFolder & "\", vbReadOnly)
Do While MyFile <> ""
DoEvents
On Error GoTo 0
Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False
Application.Run "PERSONAL.XLSB!TTDA"
ChDir MyFolder
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
MyFolder & "\" & MyFile, Quality:= _
xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
0
Workbooks(MyFile).Close SaveChanges:=False
MyFile = Dir
Loop
End Sub
Try replacing of
MyFile = Dir(MyFolder & "\", vbReadOnly)
with
MyFile = Dir(MyFolder & "\" & "*.xlsx")
In this way, the code will open only .xlsx files.
Or you can let your code like it is, but filter the files to be open using the next function which retrieves the file extension:
Private Function GetExt(fileName As String) As String
GetExt = Split(fileName, ".")(UBound(Split(fileName, ".")))
End Function
The function can be called just before the workbook opening. Your loop will become something like this:
Do While MyFile <> ""
DoEvents
If GetExt(MyFile) = "xlsx" or GetExt(MyFile) = "xlsm" then
Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False
Application.Run "PERSONAL.XLSB!TTDA"
ChDir MyFolder
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
MyFolder & "\" & MyFile, Quality:= _
xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False
OpenAfterPublish:=True
Workbooks(MyFile).Close SaveChanges:=False
End if
MyFile = Dir
Loop
For the next issue, use please:
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(MyFolder & "\" & MyFile & ".pdf") Then
If fso.FileExists(MyFolder & "\" & MyFile & "_b.pdf") Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
MyFolder & "\" & MyFile & "_a", Quality:= _
xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
MyFolder & "\" & MyFile & "_b", Quality:= _
xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False
End If
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
MyFolder & "\" & MyFile, Quality:= _
xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False
End If

VBA - save file as PDF to specific location with pre-defined name

Below code works fine until generate a filename. It picks up the correct folder location, but the file name is blank.
If I choose location somewhere on my local machine, the filename appears then. Could you advise me what should I do differently, please?
Private Sub CBSaveasPDF_Click()
Dim FileAndLocation As Variant
Dim strPathLocation As String
Dim strFilename As String
Dim strPathFile As String
strPathLocation = "http://teams.xxx.intranet/sites/bipm/test/test/test/test/test/"
strFilename = Me.Range("D8") & " -" & Me.Range("D7") & " -" & Me.Range("J7") & " " & Me.Range("B3")
strPathFile = strPathLocation & strFilename
FileAndLocation = Application.GetSaveAsFilename _
(InitialFileName:=strPathLocation & strFilename, _
filefilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If FileAndLocation = "False" Then
MsgBox ("Document not saved")
Exit Sub
End If
Me.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFilename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True

For each worksheets not working to print pdf

I'm printing some PDF from my Excel thanks to a little program, which was working and is not anymore and I can't figure out why. it's telling me
error '5' argument or procedure call incorrect.
I think it's really a stupid mistake but I have the nose in it and can't find it.
N.B. The filename part is not the issue, I have the same result when I change it for a basic thing like "bob"
Sub impression_multiple_pdf()
Dim chaine As String
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
If WS.Name <> "Tampon" And WS.Name <> "data" And WS.Name <> "Tableau de
Bord" Then
WS.ExportAsFixedFormat Type:=xlTypePDF,
Filename:=ThisWorkbook.Path & "\Fiches Projet\Fiche Projet " &
clear_name(WS.Range("C3")), Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False,
OpenAfterPublish:=False
End If
Next
ThisWorkbook.Activate
MsgBox "Fiches projet enregistrées dans mes documents"
End Sub
Clear name function :
Function clear_name(txt)
Dim C
C = Array("<", ">", "?", "[", "]", ":", "*", "\", "/", "|", ".", "#", "€",
",", "§", "#")
'txt = Range("A2")
For n = 0 To UBound(C)
txt = Left(Trim(txt), 128)
txt = Replace(txt, C(n), "")
Next
clear_name = txt
End Function
Make sure clear_name(WS.Range("C3")) is not empty.
Also make sure ThisWorkbook.Path returns a value that means your workbook needs to be saved at least once. And make sure your path exists \Fiches Projet\Fiche Projet otherwise it fails.
Sub impression_multiple_pdf()
Dim chaine As String
Dim WS As Worksheet
Dim Filename As String
For Each WS In ThisWorkbook.Worksheets
If WS.Name <> "Tampon" And WS.Name <> "data" And WS.Name <> "Tableau de Bord" Then
Filename = clear_name(WS.Range("C3"))
If Filename <> "" Then
WS.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\Fiches Projet\Fiche Projet " & Filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Else
MsgBox "Filename in '" & WS.Name & "' was empty"
End If
End If
Next WS
ThisWorkbook.Activate
MsgBox "Fiches projet enregistrées dans mes documents"
End Sub
If this doesn't help use
Debug.Print ThisWorkbook.Path & "\Fiches Projet\Fiche Projet " & Filename
right after the line Filename = clear_name(WS.Range("C3")) and tell the result that is printed in the Immediate Window.
Try editing this part
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\Fiches Projet\Fiche Projet " & clear_name(ws.Range("C3")), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

how to fix my code to conver xlsx to pdf in VBA

i have this code for convering my excel file to pdf but after changing format, i have a pdf file with lots of pages(in every page just 4 coumns with 19 rows while my source file has 30 columns and rows , i want to see same as excel file but in pdf format , any body can help me! thanks in advance
Sub creatpdf()
Dim fName As String
Dim fname1 As String
With Worksheets("Output_" & Date)
fName2 = .Range("D3").Value
fName3 = "_BOM"
End With
BrowseForFolder = "X:\\output\\"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
BrowseForFolder & "\" & fName2 & fName3 & "\" & "\" & fName2 & fName3 & "\" & "BOM" & "\" & fName2 & fName3, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False,
OpenAfterPublish:=False
End Sub

Resources