I have a very simple mail merge that is connected to an SQL server database
The mail merge has two fields on it, one is
{MERGEFIELD Dealer_Name}
the other is the following IF field
{IF {MERGEFIELD Dealer_Name}="Joe" "1" "0"}
However the IF field does not execute. The Dealer_Name merge field does execute and displays each dealer name or each page but the IF field just displays as Dealer_Name}=
Also is it possible to write a VBA function or procedure and then add it to the word mail merge document as a field or merge button or something else.
For example let say I have the following VBA procedure
Public Sub PrintSomeText
Selection.TypeText("Hello World")
End Sub
Could I add this to the mail merge document as a macro or something so that it prints out "Hello World" on each page in the locate that it was placed onto the document?
I was able to get the IF field code working, not sure how, it just started working.
Also I found that you can use VBA code in Word mail merge documents by using the DOCVARIABLE or REF field codes.
For anyone else who has this problem:
Add a document variable like this:
{DOCVARIABLE MyVariable}
or a bookmark reference like this:
{REF MyBookmarkReference}
Then in VBA (Alt+F11) do the following:
In Project (Project name), e.g. Project(MailMergeDemo) Under "Microsoft Word Objects" Double click "ThisDocument"
and enter the following code
Dim WithEvents app As Application
Private Sub Document_Close()
Set app = Nothing
End Sub
Private Sub Document_Open()
Set app = Application
End Sub
Choose the app object from the drop down and then choose the app_MailMergeBeforeRecordMerge event and enter the following code:
Private Sub app_MailMergeBeforeRecordMerge(ByVal Doc As Document, Cancel As Boolean)
Doc.Variables("MyVariable").Value = Doc.MailMerge.DataSource.DataFields(SomeFieldName).Value
Doc.Bookmarks("MyBookmarkReference").Range.Text = "this is a test"
Doc.Fields.Update
End Sub
You will need to close and reopen the document to hook the application object.
Please refer to http://support.microsoft.com/kb/285333 for more information.