Private Sub command106_Click()
Dim DC2RTR As String
'First ensure that Word is running - FollowHyperlink won't launch Word
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Err <> 0 Then
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'objWord.UserControl = True
Err.Clear
End If
On Error GoTo 0
Set objWord = Nothing
AppActivate "Microsoft Word"
DC2RTR = "D:\ExampleMailmerge.docx"
Application.FollowHyperlink DC2RTR
Start = Timer
Do Until Timer > Start + 0.2
DoEvents
Loop
retval = Mailmerge_GotoRecord("2", "ID")
Debug.Print retval
End Sub
Function Mailmerge_GotoRecord(valueToFind As String, FieldName As String) As String
Dim objWord As Object 'Word.Application
Dim objDoc As Object
Dim dsMain As Object
'On Error GoTo ErrorHandler
Set objWord = GetObject(, "Word.Application")
objWord.Visible = True
Set objDoc = objWord.ActiveDocument
Set dsMain = objDoc.MailMerge.DataSource
dsMain.ActiveRecord = wdFirstRecord
If dsMain.FindRecord(FindText:=valueToFind, _
Field:=FieldName) = True Then
Mailmerge_GotoRecord = dsMain.ActiveRecord
Else
Mailmerge_GotoRecord = ""
End If
CleanExit:
Exit Function
ErrorHandler:
MsgBox Err.Description & "(code: " & Err.Number & ")"
Mailmerge_GotoRecord = ""
Resume CleanExit
End Function
'Export merge list to a text file (to avoid having to open the
'database when the document is opened later on)
DoCmd.TransferText transfertype:=acExportDelim, _
TableName:=strTable, _
FileName:=strTextFile, _
HasFieldNames:=True
'Open a new merge document based on the selected template
Set doc = appWord.Documents.Add(strTemplateNameAndPath)
'Set the merge data source to the text file just created,
'and do the merge
With doc
.MailMerge.OpenDataSource Name:=strTextFile, _
Format:=wdOpenFormatText
If Nz(InStr(strTemplateName, "Label")) > 0 Then
.MailMerge.MainDocumentType = wdMailingLabels
Else
.MailMerge.MainDocumentType = wdFormLetters
End If
.MailMerge.Destination = wdSendToNewDocument
.MailMerge.Execute
'Set another Document variable to the newly merged document,
'to ensure that the correct document is saved
Set docMerge = appWord.ActiveDocument
.Close savechanges:=wdDoNotSaveChanges
End With
docMerge.SaveAs2 strSaveNamePath
If you want to output a single document (rather than a mail-merge to multiple reccipients), I'd tend to use a Word template with CustomDocumentProperties instead of Word Mailmerge.
this is the MS reference for the MailMergeDatasource.FindRe
But you'd have to expand your code to use it, by creating object references to the Word application, then the mailmerge document before being able to call the method on that document.
here's a basic example (without much error handling) that you could use to replace your method of following hyperlink to open the Word document.
Open in new window