2

我想构建在来自两个不同合并字段的数据之间做出决定的合并字段。例如«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

但这只是一团糟。

4

1 回答 1

2

不幸的是,此代码只会将文本作为常规字符串而不是作为合并字段插入。如果您在 Word 中手动插入字段,您可以使用 Ctrl+F9 键插入大括号以标记内容是字段而不是常规文本。

要将您想要的字段直接插入 Word,您需要手动构建字段(使用 Ctrl+F9 并键入字段名称),或者您可以使用选项插入带有占位符文本的 If 语句,然后替换占位符带有必填字段。您需要按照相同的过程在 VBA 中创建字段。

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

结束子

于 2015-07-02T15:34:14.427 回答