邮件合并循环和传递查询参数

时间:2013-04-19 14:53:27

标签: vba ms-access

我希望优化和重写一些代码来循环一系列在命令点击上运行的邮件合并。现在,存在8个单独的合并,它们相继运行。我的问题是我运行了8个查询,这些查询都需要一个开始/结束日期来从表中提取信息并将其提供给邮件合并文档。我想通过输入框指定参数日期,然后将其传递给循环中的所有合并。

For i = 1 To 1 'will change to 8 :)

Select Case i
 Case 1
wordDoc = pathToDocToMerge
sqlStr = "SELECT * FROM [QUERY - FIRST LETTERS]"
sqlConex = "QUERY - FIRST LETTERS"
strExport = "Normal"
fileout = desktopPath & "\ " & strmonth & " - FIRSTLETTERS.pdf"
Case 2
Case 3
Case 4
Case 5
Case 6
Case 7
Case 8
End Select


    Set objword = GetObject(wordDoc)

    objword.Application.Visible = False

    objword.MailMerge.OpenDataSource _
    Name:=pathToMDB, _
    LinkToSource:=True, _
    Connection:=sqlConex, _
    sqlstatement:=sqlStr

    objword.MailMerge.Destination = wdSendToNewDocument
    objword.MailMerge.Execute

    If printtopdf = vbYes Then

    objword.Application.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
    fileout _
    , ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
    wdExportOptimizeForPrint, Range:=wdExportAllDocument
     objword.Application.ActiveDocument.close SaveChanges:=wdDoNotSaveChanges

    Else

    objword.Application.Options.PrintBackground = False
    'Print one copy of the letter
    objword.Application.ActiveDocument.PrintOut
    'Close Word and do not save the changes

    End If

    objword.Application.Quit SaveChanges:=wdDoNotSaveChanges
    Set objword = Nothing

Next i

我知道参数可以像这样传递:

Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Dim prm As DAO.Parameter
Dim rst As DAO.Recordset

Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("qry_AMIS")

For Each prm In qdf.Parameters
    prm = Eval(prm.Name)
Next prm

Set rst = qdf.OpenRecordset

但是我不确定如何将其绑定到邮件合并中,因为查询变为RST。任何人都能解释一下吗?

1 个答案:

答案 0 :(得分:0)

快速查看MailMerge.OpenDataSource here的文档后,我不明白为什么您不能仅仅更改现有代码......

sqlStr = "SELECT * FROM [QUERY - FIRST LETTERS]"

......类似......

sqlStr = "SELECT * FROM [QUERY - FIRST LETTERS] WHERE SomeDate=#" & Format(CDate(Me.txtSpecifyDate.Value), "yyyy-mm-dd") & "#"

...其中Me.txtSpecifyDate是您用来提示用户提供日期的表单上的文本框。