Mail merge print button (1 Viewer)

mounty76

Registered User.
Local time
Yesterday, 22:56
Joined
Sep 14, 2017
Messages
341
Hello!

I've seen a quite a few bits of code on here but can't seem to find what I'm after, any chance one of you good people can help me with some code?

Basically I have a form that shows a qry result, there are about 10 results normally on the qry and these are linked to a mail merge document, I want a button on the form that when clicked runs some code to:

1. open the mail merge document without prompting for the link
2. runs the mail merge
3. Prints out the mail merge with the current displayed record
4. closes the word document

If someone can help me out with some code for that I'd be very grateful

Many Thanks
 

theDBguy

I’m here to help
Staff member
Local time
Yesterday, 22:56
Joined
Oct 29, 2018
Messages
21,454
Hi. Have you tried Albert's Simple Mail Merge? (I'll have to search for a link.) Just curious...
 

Gasman

Enthusiastic Amateur
Local time
Today, 06:56
Joined
Sep 21, 2011
Messages
14,231
Have you looked at the Similar threads at the bottom of the page?
 

mounty76

Registered User.
Local time
Yesterday, 22:56
Joined
Sep 14, 2017
Messages
341
Thanks guys, not seen Alberts Simple Mail Merge, the threads at the bottom of this page don't seem to offer what I'm after. My DB is called d:\test and the word document is called d:\contracts\contract.docx

They seem complicated and with errors
 

Gasman

Enthusiastic Amateur
Local time
Today, 06:56
Joined
Sep 21, 2011
Messages
14,231
Look at this thread then.

 

mounty76

Registered User.
Local time
Yesterday, 22:56
Joined
Sep 14, 2017
Messages
341
I have a mail merge document already that is 9 pages long and all linked to the access query. All I want to do is have a button in access that opens the word document, automatically selects yes when prompted for data from the DB, prints the current record, then closes word. Also my form that I have opens up and filters the query results based on the record ID but when I open the word document it still shows all the records from the original query that is linked to the form?
 

bastanu

AWF VIP
Local time
Yesterday, 22:56
Joined
Apr 13, 2010
Messages
1,402
Can you have a look at this code, I have adapted it from a longer version I have that does some more things (save as pdf, email as attachment,]etc.). You need to read through the comments and adapt it to fit your setup. Basically create a query that only contains the current record from your form ("SELECT * FROM YourFormRecordSource WHERE [RecordID] = FORMS! frmYourForm!RecordID;") which will get exported as a text file into the front-end folder and that file will be used as the mail-merge source (much safer than using an Access query).
Code:
Private Sub cmdPrintCurrentRecord_Click()
Dim ReadOnlyMode As Boolean, strDocument As String

strDocument = Me.txtPathToYourWordDocument 'uses a text box on your form to get the full name of the Word mail-merge template or use a dlookup to get it from a settings table
If Dir(strDocument) = "" Then
    MsgBox strDocument & " not found!", vbInformation, "Document not found!"
    Exit Sub
End If
response = MsgBox("Do you wish to generate a Read-Only Mail Merge document using " & Chr(13) & _
        strDocument & Chr(13) & Chr(13) & _       
        Chr(13) & Chr(13) & "Select YES for Read-Only" & _
        Chr(13) & "Select NO for Read-Write" & _
        Chr(13) & "Select CANCEL to halt.", vbYesNoCancel + vbQuestion, "Generate a Mail Merge Document")

If response = vbCancel Then Exit Sub

If response = vbYes Then
    ReadOnlyMode = True
Else
    ReadOnlyMode = False
End If
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Dim iFileCount As Integer
Dim strMailMergeFolder as string

strMailMergeFolder = CurrentProject.path
vcKillMailMerge
If Right(strMailMergeFolder, 1) <> "\" Then strMailMergeFolder = strMailMergeFolder & "\"
iFileCount = 1
On Error GoTo Error_Kill
Kill_File:
If Len(Dir(strMailMergeFolder & "DB_MailMerge" & iFileCount & ".txt")) > 0 Then Kill strMailMergeFolder & "DB_MailMerge" & iFileCount & ".txt"
GoTo relink

Error_Kill:
iFileCount = iFileCount + 1
GoTo Kill_File

relink:
     DoCmd.TransferText acExportDelim, , "qryYourQueryForCurrentID", strMailMergeFolder & "DB_MailMerge" & iFileCount & ".txt", True
     RelinkDocMailMergeText strMailMergeFolder & "DB_MailMerge" & iFileCount & ".txt", strDocument, ReadOnlyMode
    

'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

End Sub

Sub RelinkDocMailMergeText(strMailMergeFileName As String, strDoc As String, boReadOnlyMode As Boolean)
Dim WordApp As Object
Dim retcode
Dim strFileName
Dim sPathNotmalTemplate
'On Error Resume Next


strFileName = strDoc

If Dir(strFileName) = "" Then
    MsgBox strFileName & " was not found!  Is it hidden?", vbExclamation, "Document not in this folder!"
    Exit Sub
End If


Set WordApp = CreateObject("Word.Application")
        
With WordApp

          .Application.Visible = True
          On Error GoTo telluser
          .StatusBar = "Preparing to add a new Mail-Merge document in Word format.  Please wait..."
          
          .Documents.Open strFileName, ReadOnly:=boReadOnlyMode, AddToRecentFiles:=False, Revert:=True

    .ActiveDocument.MailMerge.OpenDataSource Name:= _
        strMailMergeFileName, ConfirmConversions:=False, ReadOnly:= _
        boReadOnlyMode, LinkToSource:=True, Revert:=True, AddToRecentFiles:=False
    .NormalTemplate.Saved = True
    .ActiveDocument.MailMerge.ViewMailMergeFieldCodes = False
    .ActiveDocument.MailMerge.DataSource.ActiveRecord = -4 'first record
    .ActiveDocument.MailMerge.Destination = 0    'new record
    .ActiveDocument.MailMerge.Execute
    .Documents(1).Printout 'print merged doc
    .Documents(1).Close 0 'wdDoNotSaveChanges  close merged doc
    .ActiveDocument.Close 0 'close mail-merge template
End With
Set WordApp = Nothing
Exit Sub

telluser:
Set WordApp = Nothing
MsgBox "An error occurred while attempting to open a Mail-Merge document:" & Chr(13) & strFileName, vbExclamation, "Add New Mail-Merge Document"
End Sub




Public Sub vcKillMailMerge()
    Dim strFileName As String
    Dim iFolderCount As Integer
    Dim strFolders() As String
    Dim i As Integer
    Dim strFolder As String, strFilePattern As String
    
    On Error Resume Next
    
    strFolder = CurrentProject.path
    strFilePattern = "*DB_MailMerge*"
     'Collect child folders
    strFileName = Dir$(strFolder & "\", vbDirectory)
    Do Until strFileName = ""
        If (GetAttr(strFolder & "\" & strFileName) And vbDirectory) = vbDirectory Then
            If Left$(strFileName, 1) <> "." Then
                ReDim Preserve strFolders(iFolderCount)
                strFolders(iFolderCount) = strFolder & "\" & strFileName
                iFolderCount = iFolderCount + 1
            End If
        End If
        strFileName = Dir$()
    Loop
     'process files in current folder
    strFileName = Dir$(strFolder & "\" & strFilePattern)
    Do Until strFileName = ""
        '*******************************************
        Kill strFolder & "\" & strFileName
         '*******************************************
        strFileName = Dir$()
    Loop
End Sub

Cheers,
Vlad
 

Users who are viewing this thread

Top Bottom