Exporting for a mail merged document to multiple .docx, .pdf files
Chia sẻ code macro: xuất nhiều file từ mail merge trong word.
<first> (don’t copy this)
Option Explicit
‘// Path to stored files
Const FOLDER_SAVED As String = “D:\ ”
‘// Select file database
Const SOURCE_FILE_PATH As String = “D:\Data.xlsx”
Sub TestRun()
Dim MainDoc As Document, TargetDoc As Document
Dim dbPath As String
Dim recordNumber As Long, totalRecord As Long
Dim Batdau, Ketthuc, giatri1, giatri2, i
Set MainDoc = ActiveDocument
With MainDoc.MailMerge
‘// Input value first
Batdau = “Nhap gia tri bat dau:”
giatri1 = InputBox(Batdau, Default)
‘// Inpurt value end
Ketthuc = “Nhap gia tri ket thuc:”
giatri2 = InputBox(Ketthuc, Default)
‘// if you want to specify your data, insert a WHERE clause in the SQL statement
‘// Sheet is database, it is Name of sheet on excel file
.OpenDataSource Name:=SOURCE_FILE_PATH, sqlstatement:=”SELECT * FROM [Sheet1$]”
‘// totalRecord = .DataSource.RecordCount
totalRecord = giatri2
i = giatri1
For recordNumber = i To totalRecord
With .DataSource
.ActiveRecord = recordNumber
.FirstRecord = recordNumber
.LastRecord = recordNumber
End With
.Destination = wdSendToNewDocument
.Execute False
Set TargetDoc = ActiveDocument
‘// Site_Name is field, you want to input name for files to created
TargetDoc.SaveAs2 FOLDER_SAVED & .DataSource.DataFields(“Site_Name”).Value & “.docx”, wdFormatDocumentDefault
‘// TargetDoc.ExportAsFixedFormat FOLDER_SAVED & .DataSource.DataFields(“Site_Name”).Value & “.pdf”, exportformat:=wdExportFormatPDF
‘// TargetDoc.Close False
TargetDoc.Close True
Set TargetDoc = Nothing
Next recordNumber
End With
Set MainDoc = Nothing
End Sub
<end>(don’t copy this)
Lưu ý: 1 số trường hợp copy về không chạy, các bạn vui lòng chỉnh lại dấu nháy ‘ và “. Do đưa lên web 2 dấu này nó bị thay đổi.
để chính xác hơn Mình gửi các bạn link download. Click
Sau khi download các bạn import trong macro
Bình luận