Word MailMerge后如何保留域代码(例如文件页脚中的{FILENAME})

时间:2014-05-08 15:28:29

标签: ms-word automation word-vba mailmerge fieldcodes

我在源文档的页脚中插入了一个字段{FILENAME}。

当我使用此源文档和数据文件生成MailMerge时,生成的文档不显示字段代码 - 它已被代表当前文档文件名的硬编码文本替换 - “Document1”。这是代码,表明我没有做任何特别奇特的事情:

Call vActiveDocument.MailMerge.OpenDataSource(vDataSourcePath)
vActiveDocument.MailMerge.SuppressBlankLines = True

vActiveDocument.MailMerge.Destination = 0 'Send to new Document

Call vActiveDocument.MailMerge.execute(True)
Call vActiveDocument.Close(False)
Set vActiveDocument = vApplication.activedocument

我错过了什么吗?我期待代码字段仍然是代码字段,即使在mailmerge操作之后。有一种方法可以告诉Word'计算MERGEFIELD字段,但不计算其他表单字段'。

目前我正在使用笨重的搜索和替换,但这真的很难看。丑丑丑陋丑陋。甚至有资格成为黑客。

'//get current filename
fileName = vActiveDocument.Name

'//check if we need to replace foooter
If ( replaceFileNameInFooter) then

    '//Replacing current document filename with a computed field
    '//set view to footer
    vApplication.ActiveWindow.ActivePane.View.SeekView = 10

    '//Assing footer
    Set footer = vApplication.Selection.Range

    '//search for current filename -> example: FormLetters1
    footer.Find.Text = filename

    '//replace with a filename field -> Type 29
    While footer.Find.Execute()
        Call vApplication.Selection.Fields.Add(footer, 29)  
    Wend

    '//set main document mode
    vApplication.ActiveWindow.ActivePane.View.SeekView = 0

End if

1 个答案:

答案 0 :(得分:0)

据我所知,使用现场语言进行此操作的唯一方法是另一种黑客攻击,而且可能更难管理。

将您想要的字段代码(例如{FILENAME \ p}放在另一个文档中,为其添加书签,例如使用“bm_filename_p”,然后使用

{ INCLUDETEXT "the full path+name of the document" bm_filename_p }

在邮件合并主文档中。

合并后,所有INCLUDETEXT字段都会保留,但您可能需要保存文件,然后更新页脚中的字段以获得所需的结果。此时,如果您想“修复”字段结果,您可以按照常规方式执行此操作(根据结果替换字段代码),但如果您不这样做,则始终需要包含的文件指定的位置。

虽然它适用于FILENAME,它甚至可以在邮件合并主文档的主体中使用{SEQ abc}等字段,但它不起作用,例如在{SEQ abc \ c}中页脚。

您可以使搜索和替换任务更容易的一种方法是插入带有标识符的{PAGE}字段,例如

{ PAGE \#field_filename }

这些字段在合并后也会保留,查找/替换它们可能会稍微容易一些(例如,查找{PAGE}字段并将“PAGE #field_”替换为“”,或者其他一些字段。