使用数据库字段名称作为文件名从邮件合并保存Word文件

时间:2013-05-02 22:20:20

标签: vba ms-word word-vba mailmerge

我希望能够将活动文件保存在Word 2010 MailMerge中,其文件名从数据库字段“First_Name”派生,并从数据库字段“Last_Name”派生到子文件夹中,该子文件夹是硬编码的子文件夹。

我收到"requested member of the collection does not exist"的错误。

我知道当您尝试访问不存在的对象时会发生此错误。数据库字段是First_Name,我也尝试过First Name,以防代码搜索名字的地址字段,该字段已与First_Name的数据库字段配对。 这是我尝试过的:

Sub SavingIndividuallyByCustomerName()

Dim firstname As String
Dim lastname As String

firstname = ActiveDocument.FormFields("First_Name").Result
lastname = ActiveDocument.FormFields("Last_Name").Result

    With ActiveDocument.MailMerge
    .Destination = wdSendToNewDocument
    .SuppressBlankLines = True
    With .DataSource
        .FirstRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
        .LastRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
    End With
    .Execute Pause:=False
End With
ChangeFileOpenDirectory "C:\folder\subfolder\subsubfolder\"


 ActiveDocument.SaveAs2 FileName:= _
        "C:\folder\subfolder\subsubfolder\" & firstname & lastname & ".docx"
End Sub

当我用

硬编码名称时
firstname = "John"
lastname = "Doe"

我没有其他错误,保存了活动文件。

我也试图使用但没有成功:

Dim firstname As Field
Dim lastname As Field

1 个答案:

答案 0 :(得分:0)

而不是

firstname = ActiveDocument.FormFields("First_Name").Result

lastname = ActiveDocument.FormFields("Last_Name").Result

你需要

firstname = ActiveDocument.MailMerge.DataSource.DataFields("First_Name").Value

lastname = ActiveDocument.MailMerge.DataSource.DataFields("Last_Name").Value

引号中的名称区分大小写(在Windows编程中不常见)。它必须与Word实际使用的名称相匹配,这可能与数据源中的名称不同。