Excel macro mailmerge - export to pdf - excel

I'm working vba macro which works perfectly but I need save the documents as .pdf.
I´m searching for tips, but I don´t know how to find them. Last time I found this solution : vba mail merge save as pdf
but I don´t know apply it to my macro.
Here is my code:
Sub RunMerge()
Dim wd As Object
Dim wdocSource As Object
Dim strWorkbookName As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdocSource = wd.Documents.Open(ThisWorkbook.Path & "\" & "ArtSpecDatabase.docx")
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdocSource.MailMerge.MainDocumentType = wdFormLetters
wdocSource.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM `Sheet2$`"
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = 1
.LastRecord = 1
End With
.Execute Pause:=False
End With
Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".docx"
If Dir(PathToSave, 0) <> vbNullString Then
wd.FileDialog(FileDialogType:=msoFileDialogSaveAs).Show
Else
wd.activedocument.SaveAs2 PathToSave, wdFormatDocumentDefault
End If
wd.Visible = True
wdocSource.Close savechanges:=False
wd.activedocument.Close savechanges:=False
Set wdocSource = Nothing
Set wd = Nothing
End Sub

To export a Word document as PDF, you need to use the ExportAsFixedFormat method. For example, you can replace your SaveAs2 call with this:
wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF
Now, your call to FileDialog makes no sense, so I propose changing the entire Dir(...) If-sentence to this:
Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".pdf"
If Dir(PathToSave, 0) <> vbNullString Then
With wd.FileDialog(FileDialogType:=msoFileDialogSaveAs)
If .Show = True Then
PathToSave = .SelectedItems(1)
End If
End With
End If
wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF
EDIT: Forgot to include ".pdf" extension.

Use the below code to export excel to pdf
Sub tst1()
Dim fFilename As String
fFilename = "C:\Documents and Settings\test.xlsx"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
fFilename & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
End Sub

Related

I am trying to use VBA to Print to PDF and am receiving a 1004 runtime Error

Could someone sell me why I am getting a runtime error here?? I have almost this identical code in another project that works, and I cant figure out the issue.
Sub Create_PDF()
' Create and save .pdf
Dim pdfName As String
Dim myrange As String
myrange = Cells(Rows.Count, 6).End(xlUp).Address
Dim AccountNumber As String
AccountNumber = Right(A1, 3)
FullName = "P:\Public\Generated Letters\LTXN Export Spreadsheets\" & "AccountEnding" & AccountNumber & ".pdf"
'Sets the name and location for the new file
myrange = Cells(Rows.Count, 6).End(xlUp).Address
'sets the string end for the print area
With ActiveSheet.PageSetup
.PrintArea = "A1:" & myrange
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
'Setting the spreadsheet to print active content with columns fit to single page
If Dir(FullName) <> vbNullString Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & " - " & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
'###This is where I am getting the runtime error and the file is not saving###
End Sub
Sub openFolder()
'Open the folder that we save the PDF to
Call Shell("explorer.exe" & " " & "P:\Public\Generated Letters\LTXN Export Spreadsheets\", vbNormalFocus)
End Sub
The one difference from the other project is that AccountNumber is a number and not text, but I figured in defining it as a string it shouldnt matter???
Try this:
Option Explicit
'use Const for fixed values
Const EXPORTS As String = "P:\Public\Generated Letters\LTXN Export Spreadsheets\"
Sub Create_PDF()
Dim ws As Worksheet, myRange As Range
Dim AccountNumber As String, dt As String, FullName As String, fName As String, sep As String
Set ws = ActiveSheet
AccountNumber = Right(ws.Range("A1").Value, 3) 'not just `A1`
With ActiveSheet.PageSetup
.PrintArea = "A1:" & ws.Cells(Rows.Count, 6).End(xlUp).Address
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
dt = Format(Now, "mm.dd.yyyy hh mm")
fName = EXPORTS & "AccountEnding" & AccountNumber
If Len(Dir(fName & ".pdf")) > 0 Then sep = " - "
fName = fName & sep & dt & ".pdf"
'note there's no `xlQualityMedium` enumeration for `Quality`
ws.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Sub openFolder()
'Folder paths with spaces need to be quoted....
Call Shell("explorer.exe" & " """ & EXPORTS & """", vbNormalFocus)
End Sub

How can I save an Excel sheet as a PDF to two different locations at once?

I am trying to get this VBA macro to save the selection from an Excel sheet as a PDF but in two different locations. The reason is part of the company seems to use OneDrive as their default directory and the other uses their local drive. So when I have the export as C:\Users\xxxx\Desktop, it will do that, but it won't appear on Desktops of those who use OneDrive. So I figured I'd code it up to where it saves in both directories so no matter what they use, it's on their actual Desktop. However, when I get to the second save location, it triggers the following error: Run-Time error '1004': Application-defined or object defined error
Sub gpSaveSend()
Dim IsCreated As Boolean
Dim PdfFile As String, Title As String, signature As String
Dim PdfFile2 As String
Dim OutlApp As Object
Dim RngCopied As Range
Dim StrName As String
Dim strCheck As String
Dim strCheck2 As String
Dim StrPath As String
Dim StrPath2 As String
Dim StrFullPath As String
Dim StrFullPath2 As String
Set RngCopied = Selection
Title = Range("A1")
MyDate = Format(Date, "MM-DD-YYYY")
ActiveWorkbook.Save
With ThisWorkbook
StrPath = Environ("USERPROFILE") & "\OneDrive - xxx \" & "Desktop\"
StrName = ActiveSheet.Range("AA40")
StrName2 = ActiveSheet.Range("AA34")
StrName3 = ActiveSheet.Range("AA33")
StrName4 = ActiveSheet.Range("AA38")
PdfFile = StrPath & ActiveSheet.Range("AA40") & "\" & ActiveSheet.Range("AA34") & "\" & ActiveSheet.Range("AA33") & "\" & Year(Date) & "\" & Format(Date, "mmmm") & "\" & ActiveSheet.Range("AA38") & "\" & ActiveSheet.Range("AA33") & " - " & ActiveSheet.Range("AA38") & " - " & MyDate & ".pdf"
PdfFile2 = StrPath2 & ActiveSheet.Range("AA40") & "\" & ActiveSheet.Range("AA34") & "\" & ActiveSheet.Range("AA33") & "\" & Year(Date) & "\" & Format(Date, "mmmm") & "\" & ActiveSheet.Range("AA38") & "\" & ActiveSheet.Range("AA33") & " - " & ActiveSheet.Range("AA38") & " - " & MyDate & ".pdf"
StrFullPath = StrPath & "\" & StrName & "\" & PdfFile
StrFullPath2 = StrPath2 & "\" & StrName & "\" & PdfFile2
strCheck = StrPath & "\" & StrName
FolderCheck (strCheck)
strCheck = strCheck & "\" & StrName2
FolderCheck (strCheck)
strCheck = strCheck & "\" & StrName3
FolderCheck (strCheck)
strCheck = strCheck & "\" & Year(Date)
YearFolderCheck (strCheck)
strCheck = strCheck & "\" & Format(Date, "mmmm")
YearFolderCheck (strCheck)
strCheck = strCheck & "\" & StrName4
YearFolderCheck (strCheck)
End With
With ActiveSheet.PageSetup
.FitToPagesWide = 1
.Zoom = False
End With
Sheets("Form").Range("A1:K91").ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
With ThisWorkbook
StrPath2 = Environ("USERPROFILE") & "\Desktop\"
PdfFile2 = StrPath2 & ActiveSheet.Range("AA40") & "\" & ActiveSheet.Range("AA34") & "\" & ActiveSheet.Range("AA33") & "\" & Year(Date) & "\" & Format(Date, "mmmm") & "\" & ActiveSheet.Range("AA38") & "\" & ActiveSheet.Range("AA33") & " - " & ActiveSheet.Range("AA38") & " - " & MyDate & ".pdf"
StrFullPath2 = StrPath2 & "\" & StrName & "\" & PdfFile2
strCheck2 = StrPath2 & "\" & StrName
FolderCheck2 (strCheck2)
strCheck2 = strCheck2 & "\" & StrName2
FolderCheck2 (strCheck2)
strCheck2 = strCheck2 & "\" & StrName3
FolderCheck2 (strCheck2)
strCheck2 = strCheck2 & "\" & Year(Date)
YearFolderCheck2 (strCheck2)
strCheck2 = strCheck2 & "\" & Format(Date, "mmmm")
YearFolderCheck2 (strCheck2)
strCheck2 = strCheck2 & "\" & StrName4
YearFolderCheck2 (strCheck2)
End With
With ActiveSheet.PageSetup
.FitToPagesWide = 1
.Zoom = False
End With
Sheets("Form").Range("A1:K91").ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile2, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
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
With OutlApp.CreateItem(0)
.Display
.Subject = ActiveSheet.Range("AA38") & " Completed - " & ActiveSheet.Range("AA33") & " - " & MyDate
.CC = "xxxx#xxx.com"
.HTMLBody = "<pre><BODY style=font-size:11pt;font-family:Calibri>" & Sheets("Form").Range("AA2").Value & "**Click Here to Acknowledge**" & "</body></pre>" & _
.HTMLBody ' Adds default outlook account signature
.Attachments.Add PdfFile
On Error Resume Next
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
If IsCreated Then OutlApp.Quit
Set OutlApp = Nothing
End Sub
Function FolderCheck(strCheck As String)
Dim fso As Object
Set fso = CreateObject("scripting.filesystemobject")
If (fso.FolderExists(strCheck)) Then
Exit Function
Else
fso.createfolder (strCheck)
End If
End Function
Function FolderCheck2(strCheck2 As String)
Dim fso As Object
Set fso = CreateObject("scripting.filesystemobject")
If (fso.FolderExists(strCheck2)) Then
Exit Function
Else
fso.createfolder (strCheck2)
End If
End Function
Function YearFolderCheck(strCheck As String)
Dim fso As Object
Dim strFiller As String
Set fso = CreateObject("scripting.filesystemobject")
If (fso.FolderExists(strCheck)) Then
Exit Function
Else
fso.createfolder (strCheck)
Exit Function
End If
End Function
Function YearFolderCheck2(strCheck2 As String)
Dim fso As Object
Dim strFiller As String
Set fso = CreateObject("scripting.filesystemobject")
If (fso.FolderExists(strCheck2)) Then
Exit Function
Else
fso.createfolder (strCheck2)
Exit Function
End If
End Function
Function RangetoHTML(rng As Range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to paste the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile2, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Specifically, it gets snagged at the above "PdfFile2" export code, which the only difference is the starting path, everything else is the same. It doesn't matter which path I use, if I swap the two, only the first export works and the second one won't. I'm not sure what to do or if there is a better solution to care for the issue.
UPDATE: I updated the code in my workbook and above to pretty much create two separate instances of exporting the file to include dedicated Strings, and it seems to make it through but now triggers Run-time error '76', Path not found, which then highlights the fso.createfolder line
fso.createfolder (strCheck2)
Thank you all in advance!

Problem with pasting table from excel to word

I use a macro for over 2 years with no problems. The macro is simple - copy a table from an Excel file and paste it into a Word document. For a few days, I am struggling with a problem - after starting the macro
error 4198 is occurring.
After clicking Debug VBA highlights such part of the code:
myDoc.Paragraphs(17).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
When I click Continue, the macro is going to the end with no additional problems until the next iteration.
Here is the entire macro:
Sub Agent_info()
Dim w As MailMerge
Dim a As Integer
Dim NumberOfFiles As Integer
Dim sFileName As String
Dim xlTable As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim komorka As String
Dim my_xl As Excel.Workbook
Dim xlApp As Excel.Application
'NumberOfFiles = 3
NumberOfFiles = InputBox("Ile pism przygotować?", "Pytanie")
On Error GoTo ERR_Handler
Application.ScreenUpdating = False
Application.Visible = True
Set w = ActiveDocument.MailMerge
w.DataSource.ActiveRecord = wdFirstDataSourceRecord
Set xlApp = CreateObject("Excel.Application")
Dim xlPath As String
xlPath = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\ZAŁĄCZNIKI.xlsx"
xlApp.Visible = True
Set my_xl = xlApp.Workbooks.Open(xlPath)
Worksheets("info").Activate
Range("A1").Select
If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe"
End If
For a = 1 To NumberOfFiles
On Error Resume Next
Set xlApp = GetObject("Excel.Application")
Err.Clear
If xlApp Is Nothing Then Set xlApp = CreateObject("Excel.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Excel could not be found, aborting."
End If
On Error GoTo 0
komorka = ActiveCell.Address
Do While ActiveCell.Value <> "Suma"
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Offset(0, 1).Select
Set xlTable = Excel.Range(komorka, ActiveCell)
xlTable.Copy
Do While ActiveCell.Value <> "Zaległość"
ActiveCell.Offset(-1, 0).Select
Loop
ActiveCell.Offset(0, 1).Select
With w
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = a
.LastRecord = a
End With
.Execute Pause:=False
End With
Dim katalog As String
Dim folder As String
Dim sciezka1 As String
Dim sciezka2 As String
Dim PDF As String
Dim PDF2 As String
Dim nazwaPisma As String
Dim nazwa1 As String
Dim nazwa2 As String
katalog = w.DataSource.DataFields("NAZWA_PLIKU").Value
folder = w.DataSource.DataFields("DATA_DO_PISMA_rrrrmmdd").Value
'folder = Format(Date, "yyyy-mm-dd")
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog, vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder, vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
End If
'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
nazwaPisma = " informacja o stanie zaległości z dnia "
sciezka1 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
sciezka2 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
PDF = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
PDF2 = "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
ActiveDocument.Parent.ScreenUpdating = False
ActiveDocument.SaveAs _
FileName:=sciezka1, _
FileFormat:=wdFormatXMLDocument, _
LockComments:=False, _
Password:="", _
AddToRecentFiles:=True, _
WritePassword:="", _
ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, _
SaveFormsData:=False, _
SaveAsAOCELetter:=False
ActiveDocument.Close
On Error Resume Next
Set WordApp = GetObject(class:="Word.Application")
Err.Clear
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
End If
On Error GoTo 0
WordApp.Visible = True
WordApp.Activate
Set myDoc = WordApp.Documents.Open(sciezka1)
myDoc.Paragraphs(17).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
'If Err.Number = 4198 Then
'MsgBox "Microsoft Word could not be found, aborting."
'End If
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)
WordTable.Range.ParagraphFormat.SpaceAfter = 0
Set PasteSheet = Nothing
Documents(myDoc).SaveAs _
FileName:=sciezka2, _
FileFormat:=wdFormatXMLDocument, _
LockComments:=False, _
Password:="", _
AddToRecentFiles:=True, _
WritePassword:="", _
ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, _
SaveFormsData:=False, _
SaveAsAOCELetter:=False
ActiveDocument.ExportAsFixedFormat _
OutputFileName:=PDF2, _
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.ExportAsFixedFormat _
OutputFileName:=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
Documents(myDoc).Close
w.DataSource.ActiveRecord = wdNextRecord
Next
END_Handler:
Application.Visible = True
Application.ScreenUpdating = True
Exit Sub
ERR_Handler:
MsgBox Err.Description
Resume END_Handler:
End Sub

Export sheets to PDF through VBA and enlarge them

I already have a code that do the exporting to PDF, it exports the selected sheets but I want to make the exported selection in the sheets bigger in the PDF file, to help the printing phase later.
Here's the code that do the exporting:
Sub PDFActiveSheet()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strPath & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "Les QrCodes ont été exporter dans le fichier PDF" _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Erreur lors de l'exportation"
Resume exitHandler
End Sub
If you simply want to zoom in by a fix %, use the following command before the export line
wsA.PageSetup.Zoom = 150

Excel VBA: Saving and Attaching a worksheet as pdf

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

Resources