Hi,
I am in the process of creating a excel based letter generation tool and with my limited knowledge of VBA I was able to work on something that creates a letter and saves the document with a file name in a specific folder. The challenge I am facing is that I am unable to create an option to create multiple letters at the sametime at a click of a button. I am unable to write a code which can create letters for all the employees in a sheet insted of just one and save each of them in a specific folder with the respective employee name as the file name.
Kindly help. Below mentioned is the code I am using:
Sub MergeMe()
Dim bCreatedWordInstance As Boolean
Dim objWord As Word.Application
Dim objMMMD As Word.Document
Dim cDir As String
Dim ThisFileName As String
Dim Lim As String
Lim = Sheets("Data").Range("C2").Value
' Setup filenames
Const WTempName = "Confirmation Letter.doc" 'This is the 07/10 Word Templates name, Change as req'd
NewFileName = Lim & "_Confirmation Letter" & ".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 = objMMMD.MailMerge.DataSource.FirstRecord
.LastRecord = objMMMD.MailMerge.DataSource.LastRecord
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
End Sub
Bookmarks