I have written an Excel > Word Mail merge where the word document is the mail merge template.
At the moment the location of the excel file (data source) has to be hard coded.
I want to be able to move the files about the network, as long as they are in the same folder as each other, so it recognizes the data source is still the excel file.
I currently have this piece of code which i thought would work. When the word document is opened at any point, it will re-create the data source by looking to the current directory of the file and looking for the file name PM MailMerge.xlsm.
Then when it has been created, a message box should show the new mailmerge datasource.
This works, but then when i move both files into any other folder, it fails and says cannot find datasource.
Code:
Private Sub Document_Open()
Dim strBook As String
Dim strBookName As String
Dim strDataSource As String
strBookName = "\PM MailMerge.xlsm"
strBook = ActiveDocument.Path & strBookName
strDataSource = ActiveDocument.MailMerge.DataSource.Name
ActiveDocument.MailMerge.OpenDataSource Name:= _
strBook, _
ConfirmConversions:=False, _
ReadOnly:=False, _
LinkToSource:=True, _
AddToRecentFiles:=False, _
PasswordDocument:="", _
PasswordTemplate:="", _
WritePasswordDocument:="", _
WritePasswordTemplate:="", _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=strBook;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=37;Jet OLEDB:D", _
SQLStatement:="SELECT * FROM `Merge$`", _
SQLStatement1:="", SubType:= _
wdMergeSubTypeAccess
MsgBox "Current Datasource - " + strDataSource
End Sub
It fails because Word tries to connect to the existing data source before it executes Document_Open. However, precisely what happens and what you see depend on at least the following:
- whether the data source information stored in the document is still valid (i.e., is the original .xlsm still there, and e.g. is the correct Sheet name still in it)
- whether you are opening the Word document manually or via OLE Automation
- whether the SQLSecurityCheck registry setting described here is in its default state (i.e. absent or set to 1), or set to 0
- in the case of OLE Automation, whether the Word Applicaiotn object's DisplayAlerts property is set to wdAlertsAll or wdAlertsNone
Roughly speaking...
If the data source Word tries to find still exists, in all cases except one, Word will make the connection as long as the user responds Yes to any security prompt they see. The exception is that if SQLSecurityCheck is absent or set to 1 (i.e. is the default), the document is opened via OLE Automation, and DisplayAlerts is set to wdAlertsNone, no dialog is displayed and the data source is not opened.
If the data source Word tries to find does not exist (e.g. has been moved), in all cases except one the user will see an error dialog. If their response to that dialog is to identify a valid data source, the document will have a new data source. Again, the exception is when SQLSecurityCheck is the defaul value, the document is opened via OLE, and DisplayAlerts is set to wdAlertsNone. In that case, no dialog is displayed and the data source is not opened.
A problem for developers is that if the SQLSecurityCheck value has been changed to 0 (typically to spare users having to answer the security check question all the time) they cannot avoid a user dialog popping up when the data source does not exist.
However, as long as the user is able to see and respond to any dialog boxes that Word displays when connecting to the data source, the user will either end up (a) with an open document with a data source attached, or (b) an open document with no data source attached (or arguably, some other mess, e.g. the user tries to end the Word process or some such). If either of those two things happen, the Document_Open code should then be run and Word should end up connecting to the data source you want. (Although it is possible that in some cases, trying to connect to an existing data source such as a text file when Word is already connected to it using a different method may result in an error.)
Incidentally,
- for an OLE DB connection to an Excel workbook, you should be able to omit all the parameters in your OpenDataSOurce call except Name and SQLStatement.
- AFAICS at the moment your code will always report the name of the existing data source if Word has not already removed it by the time Document_Open executes. You'd need to move the assignment to strDataSource below the OpenDataSource call to show the new name. But perhaps I've missed the point there!
I had the same problem. I solved it with: 1. the MainDocumentType = wdNotAMergeDocument (must be set to normal document, otherwise word is always questioning on open). 2. after starting a vba function read the current document-path and run the attached function:
enter code here
Function Start_MMerge(xdoc As Document, SBD_Name As String) As Integer
On Error GoTo Start_MMergeError
Dim vFile As String
vFile = Dir(SBD_Name) 'prüft, ob es die Datei SBD_Name überhaupt gibt
If Len(vFile) <> 0 Then
xdoc.MailMerge.MainDocumentType = wdFormLetters
xdoc.MailMerge.OpenDataSource Name:= _
SBD_Name, _
ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
Format:=wdOpenFormatAuto, Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=" & SBD_Name _
& ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";
Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=35;Jet OLEDB:Da" _
, SQLStatement:="SELECT * FROM `Adressen$` WHERE [E-Mail senden]='nein'", SQLStatement1:="",
SubType:=wdMergeSubTypeAccess
xdoc.MailMerge.MainDocumentType = wdFormLetters
With xdoc.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Start_MMerge = -1
Else
Start_MMerge = 0
End If
Start_MMergeExit:
xdoc.MailMerge.MainDocumentType = wdNotAMergeDocument
Exit Function
Start_MMergeError:
Start_MMerge = 0
Resume Start_MMergeExit
End Function
enter code here
来源:https://stackoverflow.com/questions/19769787/microsoft-word-mail-merge-data-source-auto-location