vba 使用数据库字段名称作为文件名从 Mailmerge 保存 Word 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16348682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving a Word File from Mailmerge with Data Base Field Name as the File Name
提问by Aaron
I would like to able to save the active file in Word 2010 MailMerge, with its file name derived from the database field "First_Name" and from the database Field "Last_Name" into a subfolder that is a hardcoded subfolder.
我希望能够将活动文件保存在 Word 2010 MailMerge 中,其文件名从数据库字段“First_Name”和数据库字段“Last_Name”派生到作为硬编码子文件夹的子文件夹中。
I receive an error that the "requested member of the collection does not exist"
.
我收到一个错误,说明"requested member of the collection does not exist"
.
I know this error occurs when you try to access an object that does not exist. The data base field is First_Name, and I have tried First Name as well in case the code was searching for the Address Field of First Name, which has been paired with the Data Base Field of First_Name. Here is what I have tried:
我知道当您尝试访问不存在的对象时会发生此错误。数据库字段是名字,我也尝试过名字,以防代码搜索名字的地址字段,该字段已与名字的数据库字段配对。这是我尝试过的:
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
When I hardcoded the name with
当我用硬编码名称时
firstname = "John"
lastname = "Doe"
I had no other errors and the active file saved.
我没有其他错误并且保存了活动文件。
I also attempted to use without success:
我也尝试使用但没有成功:
Dim firstname As Field
Dim lastname As Field
采纳答案by Aaron
Instead of
代替
firstname = ActiveDocument.FormFields("First_Name").Result
lastname = ActiveDocument.FormFields("Last_Name").Result
you need
你需要
firstname = ActiveDocument.MailMerge.DataSource.DataFields("First_Name").Value
lastname = ActiveDocument.MailMerge.DataSource.DataFields("Last_Name").Value
The name in quotes is case-sensitive (unusual in Windows programming). It has to match the name that Word is actually using, which may not be identical to the one in the data source.
引号中的名称区分大小写(在 Windows 编程中不常见)。它必须与 Word 实际使用的名称相匹配,该名称可能与数据源中的名称不同。