Filename of Data Source

S

SSwan

Hello,

I am merging from multiple files and need to output in a field, the name of
the data source file. Is this possible?

Many thanks.

SSwan
 
G

Graham Mayor

The short answer is no. This information is not available to fields.

A workaround would be to create a macro to store the datasource in a
variable then use a field to display the variable. Something along the lines
of

Dim aVar As Variable
Dim oVars As Variables
Dim iNum As Integer
Dim sSource As String
Dim oDoc As Document
Set oDoc = ActiveDocument
Set oVars = oDoc.Variables
If oDoc.MailMerge.MainDocumentType <> wdNotAMergeDocument Then
For Each aVar In oVars
If aVar.name = "varDataSource" Then iNum = aVar.Index
Next aVar
If iNum = 0 Then
'If variable does not exist - create it and set its value to 1
oVars.Add name:="varDataSource",
Value:=oDoc.MailMerge.DataSource.name
Else
oVars("varDataSource").Value = oDoc.MailMerge.DataSource.name
End If
oDoc.Fields.Update
End If

Which you would have to remember to run before merging, or you could
incorporate the code in a macro used to run the merge.
The information would be displayed in the merge document using the following
field construction.

{ IF { DocVariable varDataSource } <> "Error!*" "{ DocVariable
varDataSource }" }

which traps the error message that occurs if the macro is not run. The
information is stored with the document until the macro is run again. Note
that in Word 2007 there is a bug attributable to Update KB969604 that acrews
up docvariables. This should be fixed soon (?).

An alternative would be to use a macro to write the datasource name to a
bookmark placed in the document eg

Dim sSource As String
Dim oDoc As Document
Dim oRng As Range
Set oDoc = ActiveDocument
If oDoc.MailMerge.MainDocumentType <> wdNotAMergeDocument Then
Set oRng = ActiveDocument.Bookmarks("DataSourceName").Range
oRng = oDoc.MailMerge.DataSource.name
oDoc.Bookmarks.Add "DataSourceName", oRng
End If

would write the name to a bookmark called "DataSourceName"

http://www.gmayor.com/installing_macro.htm
--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
 
S

SSwan

Thanks Graham. I shall give that a go.

I often refer to your website when I need to tweak a mergefield!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top