VBA Mailmerge в PDF Выход

Доброе утро. Я изменил код из этого сообщения: Автоматизация слияния почты с помощью Excel VBA

Но мне нужен только вывод в формате PDF, но как только я убираю код слова, он отказывается. Я думаю, проблема в том, что если я не сохраню его как слово, он не закроет шаблон должным образом (есть код для его закрытия). Мне приходится вручную нажимать «Не сохранять», а затем он задыхается, пытаясь повторно открыть файл для следующей строки. Любая идея, как обойти это? - Любая помощь высоко ценится. Спасибо.

Public Sub MailMergeCert()
Dim bCreatedWordInstance As Boolean
Dim objWord As Word.Application
Dim objMMMD As Word.Document

Dim FirstName As String
Dim LastName As String
Dim Training As String
Dim SeminarDate As String
Dim HoursComp As String
Dim Location As String
Dim Objectives As String
Dim Trainer As String


Dim r As Long
Dim ThisFileName As String

'Your Sheet names need to be correct in here
Set sh1 = Sheets("Periop")

lastrow = Sheets("Periop").Range("A" & Rows.Count).End(xlUp).Row
r = 2

For r = 2 To lastrow
If IsEmpty(Cells(r, 10).Value) = False Then GoTo nextrow

FirstName = sh1.Cells(r, 1).Value
LastName = sh1.Cells(r, 2).Value
Training = sh1.Cells(r, 3).Value
SeminarDate = sh1.Cells(r, 4).Value
HoursComp = sh1.Cells(r, 5).Value
Location = sh1.Cells(r, 6).Value
Objectives = sh1.Cells(r, 7).Value
Trainer = sh1.Cells(r, 8).Value

SeminarDate = Format(sh1.Cells(r, 4).Value, "d mmmm YYYY")


' Setup filenames
Const WTempName = "Certificate_Periop_2016.docx" 'Template name

' Setup directories
cDir = ActiveWorkbook.Path + "\" 'Change if required
ThisFileName = ThisWorkbook.Name

On Error Resume Next

' Create a Word Application instance
bCreatedWordInstance = False
Set objWord = GetObject(, "Word.Application")

If objWord Is Nothing Then
  Err.Clear
  Set objWord = CreateObject("Word.Application")
  bCreatedWordInstance = True
End If

If objWord Is Nothing Then
MsgBox "Could not start Word"
Err.Clear
On Error GoTo 0
Exit Sub
End If

' Let Word trap the errors
On Error GoTo 0

' Set to True if you want to see the Word Doc flash past during construction
objWord.Visible = False

'Open Word Template
Set objMMMD = objWord.Documents.Open(cDir + WTempName)
objMMMD.Activate

'Merge the data
With objMMMD
.MailMerge.OpenDataSource Name:=cDir + ThisFileName, sqlstatement:="SELECT *  FROM `Periop$`"   ' Set this as required

With objMMMD.MailMerge  'With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
  .FirstRecord = r - 1
  .LastRecord = r - 1
  .ActiveRecord = r - 1
  ' EmployeeName = .EmployeeName
End With
.Execute Pause:=False
End With
End With

' Save new file
'Path and YYMM
Dim PeriopCertPath As String
PeriopCertPath = "C:\Users\305015724\Documents\ApplicationsTraining\2016\Periop\"
Dim YYMM As String
YYMM = Format(sh1.Cells(r, 11).Value, "YYMM")

'Word document
Dim NewFileNameWd As String
NewFileNameWd = YYMM & "_" & sh1.Cells(r, 12).Value & "_" & sh1.Cells(r, 2).Value & ".docx" 'Change File Name as req'd"
objWord.ActiveDocument.SaveAs Filename:=PeriopCertPath & NewFileNameWd

'PDF
Dim NewFileNamePDF As String
NewFileNamePDF = YYMM & "_" & sh1.Cells(r, 12).Value & "_" & sh1.Cells(r, 2).Value '& ".pdf" 'Change File Name as req'd"
objWord.ActiveDocument.ExportAsFixedFormat PeriopCertPath & NewFileNamePDF, ExportFormat:=wdExportFormatPDF

' Close the Mail Merge Main Document
objMMMD.Close savechanges:=wdDoNotSaveChanges
Set objMMMD = Nothing

' Close the New Mail Merged Document
If bCreatedWordInstance Then
objWord.Quit
End If

0:
Set objWord = Nothing
Cells(r, 10).Value = Date
nextrow:

Next r
End Sub

person Christine Rieger    schedule 12.10.2016    source источник


Ответы (2)


Я записал сохранение книги в формате pdf, и это результат:

ActiveDocument.ExportAsFixedFormat OutputFileName:= _
    "C:\Users\me\Desktop\Doc1.pdf", ExportFormat:=wdExportFormatPDF, _
    OpenAfterExport:=True, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
    wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _
    IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _
    wdExportCreateNoBookmarks, DocStructureTags:=True, BitmapMissingFonts:= _
    True, UseISO19005_1:=False

Кажется, вы можете попробовать:

objWord.ActiveDocument.ExportAsFixedFormat PeriopCertPath & NewFileNamePDF,
    ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False
person n8.    schedule 12.10.2016

Генерация pdf всегда работала, и я думаю, что теперь у меня есть бит сортировки Word. Это часть кода, которая создает PDF-файл, а затем закрывает Word (и некоторые другие вещи...)

'Print Certificate
'Print required
If sh1.Cells(r, 12) = "print" Then
    'remove background image
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
    Selection.WholeStory
    Selection.Cut
    'Print Certificate
   objWord.ActiveDocument.PrintOut
    'Close the Mail Merge Main Document
    objWord.ActiveDocument.Close (wdDoNotSaveChanges)
    objMMMD.Close savechanges:=wdDoNotSaveChanges
    Set objMMMD = Nothing
Else
    'Close the Mail Merge Main Document
    objWord.ActiveDocument.Close (wdDoNotSaveChanges)
    objMMMD.Close savechanges:=wdDoNotSaveChanges
    Set objMMMD = Nothing
End If

' Create a Word Application instance
bCreatedWordInstance = False
Set objWord = GetObject(, "Word.Application")
' Close the New Mail Merged Document
If bCreatedWordInstance Then
    objWord.Quit
End If

0:
Set objWord = Nothing
person Christine Rieger    schedule 25.01.2017