Option Explicit
Const REP As String = "Archives publipostage"
Sub GenérerPDF()
Dim nomDir$, nomfic$, pathSource$, iSection&, nbFichiers%
Dim docMerge As Document, docRec As Document, rngSection As Range
Dim oMerge As MailMerge, oFileDialog As Office.FileDialog
nomDir = ThisDocument.Path & "\" & REP
ChDir ThisDocument.Path
On Error Resume Next ' Erreur si le répertoire existe déjà
MkDir REP
On Error GoTo 0
Set oFileDialog = Application.FileDialog(MsoFileDialogType.msoFileDialogFilePicker)
With oFileDialog
.AllowMultiSelect = -1: .ButtonName = "Ouvrir"
.Title = "Choix du fichier source": .Filters.Add "Source publipostage", "*.xlsx": .FilterIndex = 2
If (.Show > 0) Then
End If
If (.SelectedItems.Count > 0) Then
pathSource = .SelectedItems(1)
Else
GoTo FinSub
End If
End With
Set oMerge = ActiveDocument.MailMerge
oMerge.MainDocumentType = wdFormLetters
With ActiveDocument.MailMerge
.Destination = 0: .SuppressBlankLines = -1
.DataSource.FirstRecord = 1: .DataSource.LastRecord = -16: .Execute Pause:=False
End With
Set docMerge = ActiveDocument
nbFichiers = docMerge.Sections.Count - 1
For iSection = 1 To nbFichiers 'On ignore le dernière section
Set rngSection = docMerge.Sections(iSection).Range
With rngSection
nomfic = .Words(8).Text & .Words(9).Text & ".pdf"
Set docRec = Documents.Add: docRec.Range.InsertBefore .Text
End With
docRec.SaveAs2 FileName:=nomDir & "\" & nomfic, FileFormat:=wdFormatPDF: docRec.Close False
Next iSection
docMerge.Close False: MsgBox nbFichiers & " fichiers générés"
FinSub:
ThisDocument.Close False 'Il ne faut surtout pas enregistrer le fichier
End Sub