I have created a project that combines with MS Access to create letters, using data from access and letter templates in word. I have different letter type depending on the data involved. I can run one mail merge but when i finish that, close word, and try to run a second mail merge i get an "Invalid merge field" error, that claims that all my merge fields in the document don't exist in my data source (i even does this when repeating the first merge). My code is:
Private Sub cmdFullRun_Click()
Dim msg As String
Dim Letter As String
Dim Data As String
Dim LetterType As String
Dim AccessApp As Access.Application
Dim DBPath As String
Dim DropMacro As String
LetterType = Left(lblLetterType.Caption, 3)
DropMacro = Left(LetterType, 3)
DBPath = "C:\My Documents\darryl.mdb"
Set AccessApp = New Access.Application
With AccessApp
.OpenCurrentDatabase DBPath
.DoCmd.RunMacro ("export " & DropMacro) ' exports the data to darryl.txt
End With
Letter = "c:\darryl\uni work\project\" & LetterType & "Letter.doc"
Data = "C:\my documents\darryl.txt"
msg = FireUpWord(Letter, _
Data)
If msg <> "" Then MsgBox msg
End Sub
Function FireUpWord(DocName As String, DSName As String) _
As String
Dim WordApp As Object
Err.Clear
Set WordApp = CreateObject("Word.Application"
WordApp.Visible = True
Set Merge = WordApp.Documents.Open(DocName).MailMerge
If (Err.Number <> 0) Then
FireUpWord = "Couldn't open document '" & DocName _
& "'" & Chr(10) & "Errno= " & Err.Number
Else
Merge.OpenDataSource (DSName)
WordApp.ActiveDocument.MailMerge.Execute Pause:=True
FireUpWord = ""
End If
End Function
Private Sub cmdFullRun_Click()
Dim msg As String
Dim Letter As String
Dim Data As String
Dim LetterType As String
Dim AccessApp As Access.Application
Dim DBPath As String
Dim DropMacro As String
LetterType = Left(lblLetterType.Caption, 3)
DropMacro = Left(LetterType, 3)
DBPath = "C:\My Documents\darryl.mdb"
Set AccessApp = New Access.Application
With AccessApp
.OpenCurrentDatabase DBPath
.DoCmd.RunMacro ("export " & DropMacro) ' exports the data to darryl.txt
End With
Letter = "c:\darryl\uni work\project\" & LetterType & "Letter.doc"
Data = "C:\my documents\darryl.txt"
msg = FireUpWord(Letter, _
Data)
If msg <> "" Then MsgBox msg
End Sub
Function FireUpWord(DocName As String, DSName As String) _
As String
Dim WordApp As Object
Err.Clear
Set WordApp = CreateObject("Word.Application"
WordApp.Visible = True
Set Merge = WordApp.Documents.Open(DocName).MailMerge
If (Err.Number <> 0) Then
FireUpWord = "Couldn't open document '" & DocName _
& "'" & Chr(10) & "Errno= " & Err.Number
Else
Merge.OpenDataSource (DSName)
WordApp.ActiveDocument.MailMerge.Execute Pause:=True
FireUpWord = ""
End If
End Function