【发布时间】:2015-04-19 13:11:00
【问题描述】:
我在 Excel 中创建了一个宏,我可以在其中将 Excel 中的数据通过邮件合并到 Word 信函模板中,并将各个文件保存在文件夹中。
我在 Excel 中有员工数据,我可以使用该数据生成任何员工信函,并可以根据员工姓名保存单个员工信函。
我已自动运行邮件合并并根据员工姓名保存单个文件。每次它为一个人运行文件时,它都会将状态显示为 Letter Already Generate,这样它就不会重复任何员工记录。
问题是所有合并文件中的输出与第一行相同。示例:如果我的 Excel 有 5 个员工详细信息,我可以在每个员工姓名上保存 5 个单独的合并文件,但是如果是第 2 行中的第一个员工,则合并数据。
我的行有以下数据:
A 行:有 S.No.
B 行:具有 Empl 名称
C 行:有处理日期
D 行:有地址
E 行:名字
F 行:业务名称
G行:显示状态(如果生成了字母,则在运行宏后显示“Letter Generated Already”,如果输入新记录,则显示空白。
此外,我如何将输出(合并文件)也保存为 PDF 文件而不是 DOC 文件,以便合并的文件有两种格式,一种是 DOC 格式,另一种是 PDF 格式?
Sub MergeMe()
Dim bCreatedWordInstance As Boolean
Dim objWord As Word.Application
Dim objMMMD As Word.Document
Dim EmployeeName As String
Dim cDir As String
Dim r As Long
Dim ThisFileName As String
lastrow = Sheets("Data").Range("A" & Rows.Count).End(xlUp).Row
r = 2
For r = 2 To lastrow
If Cells(r, 7).Value = "Letter Generated Already" Then GoTo nextrow
EmployeeName = Sheets("Data").Cells(r, 2).Value
' Setup filenames
Const WTempName = "letter.docx" 'This is the 07/10 Word Templates name, Change as req'd
Dim NewFileName As String
NewFileName = "Offer Letter - " & EmployeeName & ".docx" 'This is the New 07/10 Word Documents File Name, Change as req'd"
' Setup directories
cDir = ActiveWorkbook.path + "\" 'Change if appropriate
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 `Data$`" ' Set this as required
With objMMMD.MailMerge 'With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
End With
' Save new file
objWord.ActiveDocument.SaveAs cDir + NewFileName
' 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, 7).Value = "Letter Generated Already"
nextrow:
Next r
End Sub
【问题讨论】: