动态创建合并域(访问Word)

时间:2015-03-11 14:23:03

标签: vba ms-word

无论如何我可以使用VBA从数组值设置Word文档中的字段文本吗?

Do While .Execute
        Selection.MoveDown Unit:=wdLine, count:=1
        Selection.Paragraphs.Indent

        For I = 0 To mergeFields.GetUpperBound(0)
            Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
            Selection.TypeText Text:="MERGEFIELD M_1"
            Selection.MoveRight Unit:=wdCharacter, count:=2
            Selection.TypeParagraph
        Next 

在" MERGEFIELD M_1"的位置,我想从名为" mergeFields"的数组中填充该文本,该数组具有类似命名的字符串。原因是因为该数组是在一个单独的函数中动态设置的,所以我可能需要创建5个新字段或最多20个新字段。

所以我的想法如下:

            Selection.TypeText Text:= mergeField(I)
            Selection.MoveRight Unit:=wdCharacter, count:=2
            Selection.TypeParagraph

这样的事情可能吗?

1 个答案:

答案 0 :(得分:0)

没关系,经过多次调整后我能够让它工作。这是其他任何人的最终代码:

Do While .Execute
            Selection.MoveDown Unit:=wdLine, count:=1
            Selection.Paragraphs.Indent

            For Each fieldName In mergeFields
                If fieldName <> "" Then
                    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
                    Selection.TypeText Text:=mergeFields(I)
                    Selection.MoveRight Unit:=wdCharacter, count:=2
                    Selection.TypeParagraph
                    I = I + 1
                    End If
            Next
        Loop