我想构建合并域来决定来自两个不同合并域的数据。
例如,«field_1»
应包含:
IF «field_1» > "" "«field_1»" "«field_2»"
我尝试了以下方式:
Sub createField()
Dim mergeString As String
mergeString = "IF{MERGEFIELD field_1}>"""" ""{MERGEFIELD field_1}""""{MERGEFIELD field_2}"""
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
Selection.TypeText Text:=mergeString
End Sub
还有insertFormula:
Sub createField()
Dim mergeString As String
mergeString = "IF{MERGEFIELD field_1}>"""" ""{MERGEFIELD field_1}""""{MERGEFIELD field_2}"""
Selection.InsertFormula Formula:= mergeString
End Sub
但这只是一团糟。
答案 0 :(得分:2)
不幸的是,这段代码只是将文本作为常规字符串而不是Mergefields插入。如果手动在Word中插入字段,则可以使用Ctrl + F9键插入大括号,以标记内容是字段而不是常规文本。
要将您想要的字段直接插入Word,您需要手动构建字段(使用Ctrl + F9并键入字段名称),或者您可以使用该选项插入带有占位符文本的If语句然后用所需的字段替换占位符。您需要按照相同的过程在VBA中创建Field。
Sub createField() Dim showState As Boolean showState = ActiveWindow.View.ShowFieldCodes
Dim ifField As MailMergeField
Set ifField = ActiveDocument.MailMerge.Fields.AddIf(Range:=Selection.Range, MergeField:= _
"Name", Comparison:=wdMergeIfNotEqual, CompareTo:="", TrueText:="FieldIfTrue", _
FalseText:="FieldIfFalse")
ifField.Select
ActiveWindow.View.ShowFieldCodes = True
With Selection.Find
.ClearFormatting
.Text = "FieldIfTrue"
.Replacement.Text = ""
.Forward = True
.Format = False
.Execute
End With
ActiveDocument.Fields.Add Range:=Selection.Range, Type:=wdFieldMergeField, Text:="""Name"""
With Selection.Find
.Text = "FieldIfFalse"
.Replacement.Text = ""
.Forward = True
.Format = False
.Execute
End With
ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, Name:="OtherName"
Selection.Fields.Update
ActiveWindow.View.ShowFieldCodes = showState
End Sub