PDA

View Full Version : Mail Merge with conditional textbox



thtang
02-13-2016, 10:22 AM
I am trying to do mail merge by macro. A text box will be added in specific letter when one of the field hits the condition. Below in my code, it seems that whenever there is record hitting the condition, all the letter will get the textbox. I am wondering this is because the textbox is added into the word template, causing it to show it on every page. But i just want to add it in the specific letter that hitting the condition, can anybody advice me how to do it, please?



Sub PrintMailMerge()
Dim CA As String
Dim totalMailings As Long

With ActiveDocument.MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:="C:\Users\George\Documents\testmm.xlsx", _
ConfirmConversions:=False, _
ReadOnly:=True, _
LinkToSource:=True, _
AddToRecentFiles:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;" & _
"Data Source=C:\Users\George\Documents\testmm.xlsx;Mode=Read;" & _
"Extended Properties=""HDR=YES;IMEX=1;"";", _
SQLStatement:="SELECT * FROM `'PTEST$'`", _
SubType:=wdMergeSubTypeAccess
End With

totalMailings = ActiveDocument.MailMerge.DataSource.RecordCount
'

For i = 1 To totalMailings Step 1
ActiveDocument.MailMerge.DataSource.ActiveRecord = i
CA = ActiveDocument.MailMerge.DataSource.DataFields("testNo").Value
If InStr(1, CA, "012") > 0 Then
Call addBox
End If
Next i

With ActiveDocument.MailMerge
.Destination = wdSendToPrinter
.Execute
End With

End Sub

Sub addBox()
Dim Box As Shape
Set Box = ActiveDocument.Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, Left:=50, Top:=50, Width:=100, Height:=100)
Box.TextFrame.TextRange.Text = "Test"
End Sub


Thank you for your help.